@orpc/openapi 2.0.0-beta.48 → 2.0.0-beta.49
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 +4 -4
- package/dist/adapters/aws-lambda/index.d.ts +15 -0
- package/dist/adapters/aws-lambda/index.js +1 -0
- package/dist/adapters/aws-lambda/openapi-handler.d.ts +18 -0
- package/dist/adapters/aws-lambda/openapi-handler.js +18 -0
- package/dist/adapters/fastify/index.d.ts +1 -0
- package/dist/adapters/fastify/index.js +1 -0
- package/dist/adapters/fastify/openapi-handler.d.ts +15 -0
- package/dist/adapters/fastify/openapi-handler.js +15 -0
- package/dist/adapters/fetch/index.d.ts +2 -0
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/openapi-handler.d.ts +15 -0
- package/dist/adapters/fetch/openapi-handler.js +15 -0
- package/dist/adapters/fetch/openapi-link.d.ts +21 -0
- package/dist/adapters/fetch/openapi-link.js +20 -0
- package/dist/adapters/node/index.d.ts +1 -0
- package/dist/adapters/node/index.js +1 -0
- package/dist/adapters/node/openapi-handler.d.ts +15 -0
- package/dist/adapters/node/openapi-handler.js +15 -0
- package/dist/adapters/standard/index.d.ts +3 -0
- package/dist/adapters/standard/index.js +3 -0
- package/dist/adapters/standard/openapi-handler-codec.d.ts +62 -0
- package/dist/adapters/standard/openapi-handler-codec.js +220 -0
- package/dist/adapters/standard/openapi-link-codec.d.ts +62 -0
- package/dist/adapters/standard/openapi-link-codec.js +405 -0
- package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
- package/dist/adapters/standard/openapi-matcher.js +108 -0
- package/dist/adapters/standard/utils.d.ts +4 -0
- package/dist/adapters/standard/utils.js +47 -0
- package/dist/bracket-notation.d.ts +26 -0
- package/dist/bracket-notation.js +185 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +13 -0
- package/dist/constants.js +4 -0
- package/dist/extensions/route.d.ts +37 -0
- package/dist/extensions/route.js +12 -0
- package/dist/helpers/form-data.d.ts +57 -0
- package/dist/helpers/form-data.js +90 -0
- package/dist/helpers/index.d.ts +1 -0
- package/dist/helpers/index.js +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +11 -0
- package/dist/meta.d.ts +325 -0
- package/dist/meta.js +84 -0
- package/dist/openapi-generator-components.d.ts +31 -0
- package/dist/openapi-generator-components.js +275 -0
- package/dist/openapi-generator-operation.d.ts +34 -0
- package/dist/openapi-generator-operation.js +469 -0
- package/dist/openapi-generator.d.ts +92 -0
- package/dist/openapi-generator.js +147 -0
- package/dist/openapi-json-serializer.d.ts +79 -0
- package/dist/openapi-json-serializer.js +260 -0
- package/dist/openapi-serializer.d.ts +43 -0
- package/dist/openapi-serializer.js +93 -0
- package/dist/plugins/index.d.ts +1 -0
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/openapi-reference.d.ts +115 -0
- package/dist/plugins/openapi-reference.js +187 -0
- package/dist/router-utils.d.ts +20 -0
- package/dist/router-utils.js +36 -0
- package/dist/{types.d.mts → types.d.ts} +23 -19
- package/dist/utils.d.ts +14 -0
- package/dist/utils.js +47 -0
- package/package.json +69 -71
- package/dist/adapters/aws-lambda/index.d.mts +0 -15
- package/dist/adapters/aws-lambda/index.mjs +0 -1
- package/dist/adapters/aws-lambda/openapi-handler.d.mts +0 -17
- package/dist/adapters/aws-lambda/openapi-handler.mjs +0 -11
- package/dist/adapters/fastify/index.d.mts +0 -1
- package/dist/adapters/fastify/index.mjs +0 -1
- package/dist/adapters/fastify/openapi-handler.d.mts +0 -14
- package/dist/adapters/fastify/openapi-handler.mjs +0 -11
- package/dist/adapters/fetch/index.d.mts +0 -2
- package/dist/adapters/fetch/index.mjs +0 -2
- package/dist/adapters/fetch/openapi-handler.d.mts +0 -14
- package/dist/adapters/fetch/openapi-handler.mjs +0 -11
- package/dist/adapters/fetch/openapi-link.d.mts +0 -15
- package/dist/adapters/fetch/openapi-link.mjs +0 -11
- package/dist/adapters/node/index.d.mts +0 -1
- package/dist/adapters/node/index.mjs +0 -1
- package/dist/adapters/node/openapi-handler.d.mts +0 -14
- package/dist/adapters/node/openapi-handler.mjs +0 -11
- package/dist/adapters/standard/index.d.mts +0 -3
- package/dist/adapters/standard/index.mjs +0 -3
- package/dist/adapters/standard/openapi-handler-codec.d.mts +0 -61
- package/dist/adapters/standard/openapi-handler-codec.mjs +0 -203
- package/dist/adapters/standard/openapi-link-codec.d.mts +0 -53
- package/dist/adapters/standard/openapi-link-codec.mjs +0 -356
- package/dist/adapters/standard/openapi-matcher.d.mts +0 -29
- package/dist/adapters/standard/openapi-matcher.mjs +0 -105
- package/dist/adapters/standard/utils.d.mts +0 -4
- package/dist/adapters/standard/utils.mjs +0 -36
- package/dist/bracket-notation.d.mts +0 -26
- package/dist/bracket-notation.mjs +0 -156
- package/dist/client-factory.d.mts +0 -24
- package/dist/client-factory.mjs +0 -5
- package/dist/constants.mjs +0 -4
- package/dist/extensions/route.d.mts +0 -76
- package/dist/extensions/route.mjs +0 -12
- package/dist/helpers/form-data.d.mts +0 -57
- package/dist/helpers/form-data.mjs +0 -36
- package/dist/helpers/index.d.mts +0 -1
- package/dist/helpers/index.mjs +0 -1
- package/dist/index.d.mts +0 -13
- package/dist/index.mjs +0 -11
- package/dist/meta.d.mts +0 -345
- package/dist/meta.mjs +0 -56
- package/dist/openapi-generator-components.d.mts +0 -24
- package/dist/openapi-generator-components.mjs +0 -227
- package/dist/openapi-generator-operation.d.mts +0 -29
- package/dist/openapi-generator-operation.mjs +0 -447
- package/dist/openapi-generator.d.mts +0 -87
- package/dist/openapi-generator.mjs +0 -115
- package/dist/openapi-json-serializer.d.mts +0 -86
- package/dist/openapi-json-serializer.mjs +0 -229
- package/dist/openapi-serializer.d.mts +0 -43
- package/dist/openapi-serializer.mjs +0 -87
- package/dist/plugins/index.d.mts +0 -1
- package/dist/plugins/index.mjs +0 -1
- package/dist/plugins/openapi-reference.d.mts +0 -118
- package/dist/plugins/openapi-reference.mjs +0 -157
- package/dist/router-utils.d.mts +0 -18
- package/dist/router-utils.mjs +0 -29
- package/dist/utils.d.mts +0 -14
- package/dist/utils.mjs +0 -40
- /package/dist/{constants.d.mts → constants.d.ts} +0 -0
- /package/dist/{types.mjs → types.js} +0 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { downgradeSpecV31ToV30, downgradeSpecV32ToV31 } from '@openapi-spec/downgrader';
|
|
2
|
+
import { COMMON_ERROR_STATUS_MAP } from '@orpc/client';
|
|
3
|
+
import { combineJsonSchemasWithComposition, DelegatingJsonSchemaConverter, hoistRecursiveRefToDef, StandardJsonSchemaConverter, } from '@orpc/json-schema';
|
|
4
|
+
import { walkProcedureContractsAsync } from '@orpc/server';
|
|
5
|
+
import { clone, mergeHttpPath, pathToHttpPath, toArray, value } from '@orpc/shared';
|
|
6
|
+
import { DEFAULT_OPENAPI_METHOD } from './constants.js';
|
|
7
|
+
import { getOpenAPIMeta } from './meta.js';
|
|
8
|
+
import { OpenAPIComponentRegistry } from './openapi-generator-components.js';
|
|
9
|
+
import { buildErrorResponse, buildRequest, buildSuccessResponse, OpenAPIGeneratorError, toOpenAPIPath, } from './openapi-generator-operation.js';
|
|
10
|
+
import { OpenAPIJsonSerializer } from './openapi-json-serializer.js';
|
|
11
|
+
import { getDynamicPathParams } from './utils.js';
|
|
12
|
+
export { OpenAPIGeneratorError } from './openapi-generator-operation.js';
|
|
13
|
+
/**
|
|
14
|
+
* Generates an OpenAPI document from a contract or router.
|
|
15
|
+
* Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
|
|
18
|
+
*/
|
|
19
|
+
export class OpenAPIGenerator {
|
|
20
|
+
serializer;
|
|
21
|
+
converter;
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
this.serializer = options.serializer ?? new OpenAPIJsonSerializer();
|
|
24
|
+
this.converter = new DelegatingJsonSchemaConverter([
|
|
25
|
+
...toArray(options.converters),
|
|
26
|
+
new StandardJsonSchemaConverter(),
|
|
27
|
+
]);
|
|
28
|
+
}
|
|
29
|
+
async generate(router, options = {}) {
|
|
30
|
+
const version = options.version ?? '3.2.0';
|
|
31
|
+
const doc = {
|
|
32
|
+
...clone(options.base),
|
|
33
|
+
openapi: '3.2.0',
|
|
34
|
+
info: options.base?.info ?? { title: 'API Reference', version: '0.0.0' },
|
|
35
|
+
};
|
|
36
|
+
const ctx = {
|
|
37
|
+
registry: new OpenAPIComponentRegistry(doc, options.componentName),
|
|
38
|
+
convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction),
|
|
39
|
+
errorStatusMap: options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP,
|
|
40
|
+
errorResponseBodySchema: options.errorResponseBodySchema,
|
|
41
|
+
errorResponseContentType: options.errorResponseContentType ?? 'application/json',
|
|
42
|
+
};
|
|
43
|
+
const errors = [];
|
|
44
|
+
const routeOwners = new Map();
|
|
45
|
+
const operationIdOwners = new Map();
|
|
46
|
+
await walkProcedureContractsAsync(router, (contract, path) => {
|
|
47
|
+
if (value(options.filter, contract, path) === false) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const procedurePath = path.length ? path.join('.') : '(root)';
|
|
51
|
+
try {
|
|
52
|
+
const def = contract['~orpc'];
|
|
53
|
+
const meta = getOpenAPIMeta(contract);
|
|
54
|
+
const method = (meta?.method ?? DEFAULT_OPENAPI_METHOD).toLowerCase();
|
|
55
|
+
if (method === 'query' && !version.startsWith('3.2.')) {
|
|
56
|
+
throw new OpenAPIGeneratorError(`QUERY operations require OpenAPI 3.2, but version "${version}" was requested.`);
|
|
57
|
+
}
|
|
58
|
+
const postPath = meta?.path ?? pathToHttpPath(path);
|
|
59
|
+
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
|
|
60
|
+
const dynamicPathParams = getDynamicPathParams(httpPath);
|
|
61
|
+
const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
|
|
62
|
+
let operation;
|
|
63
|
+
if (meta?.spec !== undefined && typeof meta.spec !== 'function') {
|
|
64
|
+
operation = meta.spec;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
operation = {
|
|
68
|
+
operationId: meta?.operationId ?? path.join('.'),
|
|
69
|
+
summary: meta?.summary,
|
|
70
|
+
description: meta?.description,
|
|
71
|
+
deprecated: meta?.deprecated,
|
|
72
|
+
tags: meta?.tags?.map((tag) => tag),
|
|
73
|
+
};
|
|
74
|
+
buildRequest(ctx, operation, def, meta, dynamicPathParams);
|
|
75
|
+
buildSuccessResponse(ctx, operation, def, meta);
|
|
76
|
+
buildErrorResponse(ctx, operation, def);
|
|
77
|
+
}
|
|
78
|
+
if (typeof meta?.spec === 'function') {
|
|
79
|
+
operation = meta.spec(operation);
|
|
80
|
+
}
|
|
81
|
+
const routeKey = `${method} ${toOpenAPIPath(httpPath, dynamicPathParams?.map((p) => ({ ...p, parameterName: '' })))}`;
|
|
82
|
+
const routeOwner = routeOwners.get(routeKey);
|
|
83
|
+
if (routeOwner !== undefined) {
|
|
84
|
+
throw new OpenAPIGeneratorError(`${method.toUpperCase()} ${openApiPath} is already documented by the procedure at ${routeOwner}.\n` +
|
|
85
|
+
` OpenAPI allows one operation per method and path (path param names are ignored).\n` +
|
|
86
|
+
` Fix: change the method or path of one of them.`);
|
|
87
|
+
}
|
|
88
|
+
const { operationId } = operation;
|
|
89
|
+
if (operationId !== undefined) {
|
|
90
|
+
const operationIdOwner = operationIdOwners.get(operationId);
|
|
91
|
+
if (operationIdOwner !== undefined) {
|
|
92
|
+
throw new OpenAPIGeneratorError(`operationId "${operationId}" is already used by the procedure at ${operationIdOwner}.\n` +
|
|
93
|
+
` OpenAPI requires operationIds to be unique. Fix: give one of them a different operationId.`);
|
|
94
|
+
}
|
|
95
|
+
operationIdOwners.set(operationId, procedurePath);
|
|
96
|
+
}
|
|
97
|
+
routeOwners.set(routeKey, procedurePath);
|
|
98
|
+
doc.paths ??= {};
|
|
99
|
+
doc.paths[openApiPath] ??= {};
|
|
100
|
+
doc.paths[openApiPath][method] = operation;
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
if (!(e instanceof OpenAPIGeneratorError)) {
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
errors.push(`Procedure at ${procedurePath}: ${e.message}`);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
if (errors.length) {
|
|
110
|
+
throw new OpenAPIGeneratorError(`[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? '' : 's'}):\n\n${errors.join('\n\n')}`);
|
|
111
|
+
}
|
|
112
|
+
// serialize first so the downgraders work on JSON values, e.g. `Infinity` as `null`
|
|
113
|
+
const serialized = this.serializer.serializeJson(doc).json;
|
|
114
|
+
return toVersionedOpenAPIDocument(serialized, version);
|
|
115
|
+
}
|
|
116
|
+
convertSchema(schema, direction) {
|
|
117
|
+
const [jsonSchema, optional] = this.converter.convert(schema, direction);
|
|
118
|
+
// composing or hoisting would retarget root-relative refs (`#`, `#/properties/...`),
|
|
119
|
+
// so move a schema that points into itself under a def first
|
|
120
|
+
return [hoistRecursiveRefToDef(strip$schemaField(jsonSchema)), optional];
|
|
121
|
+
}
|
|
122
|
+
convertSchemas(schemas, direction) {
|
|
123
|
+
if (!schemas || schemas.length <= 1) {
|
|
124
|
+
return this.convertSchema(schemas?.[0], direction);
|
|
125
|
+
}
|
|
126
|
+
const results = schemas.map((s) => this.convertSchema(s, direction));
|
|
127
|
+
return [
|
|
128
|
+
combineJsonSchemasWithComposition('allOf', results.map(([jsonSchema]) => jsonSchema)),
|
|
129
|
+
results.every(([, optional]) => optional),
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function toVersionedOpenAPIDocument(doc, version) {
|
|
134
|
+
const downgraded = version.startsWith('3.2.')
|
|
135
|
+
? doc
|
|
136
|
+
: version.startsWith('3.1.')
|
|
137
|
+
? downgradeSpecV32ToV31(doc)
|
|
138
|
+
: downgradeSpecV31ToV30(downgradeSpecV32ToV31(doc));
|
|
139
|
+
return { ...downgraded, openapi: version };
|
|
140
|
+
}
|
|
141
|
+
function strip$schemaField(schema) {
|
|
142
|
+
if (typeof schema !== 'object') {
|
|
143
|
+
return schema;
|
|
144
|
+
}
|
|
145
|
+
const { $schema: _schema, ...rest } = schema;
|
|
146
|
+
return rest;
|
|
147
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Segment } from '@orpc/shared';
|
|
2
|
+
export type OpenAPIJsonSerialization = {
|
|
3
|
+
json: unknown;
|
|
4
|
+
maps?: undefined;
|
|
5
|
+
blobs?: undefined;
|
|
6
|
+
} | {
|
|
7
|
+
json: unknown;
|
|
8
|
+
maps: Segment[][];
|
|
9
|
+
blobs: Blob[];
|
|
10
|
+
};
|
|
11
|
+
export interface OpenAPIJsonSerializerHandler {
|
|
12
|
+
condition(value: unknown): boolean;
|
|
13
|
+
serialize(value: any): unknown;
|
|
14
|
+
/**
|
|
15
|
+
* If false, the result of this serializer will not be further processed by other serializers,
|
|
16
|
+
* even if it matches their conditions and treat it as final serialized value.
|
|
17
|
+
* This can be useful for serializers that return primitive values, which should not be further processed.
|
|
18
|
+
* to improve performance and avoid potential issues with other serializers.
|
|
19
|
+
*
|
|
20
|
+
* @default false
|
|
21
|
+
*/
|
|
22
|
+
isTerminal?: boolean | undefined;
|
|
23
|
+
}
|
|
24
|
+
export interface OpenAPIJsonSerializerOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Extend or override the built-in type handlers used during serialization.
|
|
27
|
+
*
|
|
28
|
+
* Each key is a unique type identifier (e.g. `"date"`, `"bigint"`) and maps to a handler
|
|
29
|
+
* that defines how to detect and serialize values of that type.
|
|
30
|
+
*
|
|
31
|
+
* **Extending:** Add new keys to support custom types:
|
|
32
|
+
* ```ts
|
|
33
|
+
* handlers: {
|
|
34
|
+
* buffer: {
|
|
35
|
+
* condition: (v) => v instanceof Buffer,
|
|
36
|
+
* serialize: (v: Buffer) => v.toString('base64'),
|
|
37
|
+
* isTerminal: true,
|
|
38
|
+
* }
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* **Overriding:** Use an existing key to replace a built-in handler:
|
|
43
|
+
* ```ts
|
|
44
|
+
* handlers: {
|
|
45
|
+
* date: {
|
|
46
|
+
* condition: (v) => v instanceof Date,
|
|
47
|
+
* serialize: (v: Date) => v.getTime(),
|
|
48
|
+
* isTerminal: true,
|
|
49
|
+
* }
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* **Disabling:** Set a key to `undefined` to remove a built-in handler:
|
|
54
|
+
* ```ts
|
|
55
|
+
* handlers: { url: undefined }
|
|
56
|
+
* ```
|
|
57
|
+
*
|
|
58
|
+
* Built-in type keys: `undefined`, `bigint`, `date`, `nan`, `infinity`, `url`, `set`, `map`.
|
|
59
|
+
*/
|
|
60
|
+
handlers?: Record<string, undefined | OpenAPIJsonSerializerHandler> | undefined;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The JSON layer behind `OpenAPISerializer`: one-way serialization of types like `Date`, `BigInt`,
|
|
64
|
+
* and `Set` into JSON-friendly values, for places that only accept JSON.
|
|
65
|
+
*
|
|
66
|
+
* @see {@link https://orpc.dev/docs/openapi/serializer#openapi-json-serializer | OpenAPI Serializer - OpenAPI JSON Serializer}
|
|
67
|
+
*/
|
|
68
|
+
export declare class OpenAPIJsonSerializer {
|
|
69
|
+
private readonly inlineBuiltInHandlers;
|
|
70
|
+
private readonly handlerEntries;
|
|
71
|
+
constructor(options?: OpenAPIJsonSerializerOptions);
|
|
72
|
+
serializeJson(data: unknown): OpenAPIJsonSerialization;
|
|
73
|
+
/**
|
|
74
|
+
* `segments` is a shared mutable stack (push/pop while walking),
|
|
75
|
+
* so it must be copied before being stored in `maps`.
|
|
76
|
+
*/
|
|
77
|
+
private serializeValue;
|
|
78
|
+
deserializeJson(serialized: OpenAPIJsonSerialization): unknown;
|
|
79
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { copyOnWrite, isPlainObject, NullProtoObj } from '@orpc/shared';
|
|
2
|
+
const DEFAULT_OPEN_API_JSON_SERIALIZER_HANDLERS = {
|
|
3
|
+
undefined: {
|
|
4
|
+
condition(data) {
|
|
5
|
+
return data === undefined;
|
|
6
|
+
},
|
|
7
|
+
serialize() {
|
|
8
|
+
return null;
|
|
9
|
+
},
|
|
10
|
+
isTerminal: true,
|
|
11
|
+
},
|
|
12
|
+
bigint: {
|
|
13
|
+
condition(data) {
|
|
14
|
+
return typeof data === 'bigint';
|
|
15
|
+
},
|
|
16
|
+
serialize(data) {
|
|
17
|
+
return data.toString();
|
|
18
|
+
},
|
|
19
|
+
isTerminal: true,
|
|
20
|
+
},
|
|
21
|
+
date: {
|
|
22
|
+
condition(data) {
|
|
23
|
+
return data instanceof Date;
|
|
24
|
+
},
|
|
25
|
+
serialize(data) {
|
|
26
|
+
if (Number.isNaN(data.getTime())) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return data.toISOString();
|
|
30
|
+
},
|
|
31
|
+
isTerminal: true,
|
|
32
|
+
},
|
|
33
|
+
nan: {
|
|
34
|
+
condition(data) {
|
|
35
|
+
return typeof data === 'number' && Number.isNaN(data);
|
|
36
|
+
},
|
|
37
|
+
serialize() {
|
|
38
|
+
return null;
|
|
39
|
+
},
|
|
40
|
+
isTerminal: true,
|
|
41
|
+
},
|
|
42
|
+
infinity: {
|
|
43
|
+
condition(data) {
|
|
44
|
+
return data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY;
|
|
45
|
+
},
|
|
46
|
+
serialize() {
|
|
47
|
+
return null;
|
|
48
|
+
},
|
|
49
|
+
isTerminal: true,
|
|
50
|
+
},
|
|
51
|
+
url: {
|
|
52
|
+
condition(data) {
|
|
53
|
+
return data instanceof URL;
|
|
54
|
+
},
|
|
55
|
+
serialize(data) {
|
|
56
|
+
return data.toString();
|
|
57
|
+
},
|
|
58
|
+
isTerminal: true,
|
|
59
|
+
},
|
|
60
|
+
set: {
|
|
61
|
+
condition(data) {
|
|
62
|
+
return data instanceof Set;
|
|
63
|
+
},
|
|
64
|
+
serialize(data) {
|
|
65
|
+
return Array.from(data);
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
map: {
|
|
69
|
+
condition(data) {
|
|
70
|
+
return data instanceof Map;
|
|
71
|
+
},
|
|
72
|
+
serialize(data) {
|
|
73
|
+
return Array.from(data.entries());
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The JSON layer behind `OpenAPISerializer`: one-way serialization of types like `Date`, `BigInt`,
|
|
79
|
+
* and `Set` into JSON-friendly values, for places that only accept JSON.
|
|
80
|
+
*
|
|
81
|
+
* @see {@link https://orpc.dev/docs/openapi/serializer#openapi-json-serializer | OpenAPI Serializer - OpenAPI JSON Serializer}
|
|
82
|
+
*/
|
|
83
|
+
export class OpenAPIJsonSerializer {
|
|
84
|
+
inlineBuiltInHandlers;
|
|
85
|
+
handlerEntries;
|
|
86
|
+
constructor(options = {}) {
|
|
87
|
+
const customHandlers = options.handlers;
|
|
88
|
+
if (customHandlers === undefined) {
|
|
89
|
+
this.inlineBuiltInHandlers = true;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
let inlineBuiltInHandlers = true;
|
|
93
|
+
let handlerEntries = [];
|
|
94
|
+
for (const key of Object.keys(customHandlers)) {
|
|
95
|
+
const handler = customHandlers[key];
|
|
96
|
+
if (inlineBuiltInHandlers && key in DEFAULT_OPEN_API_JSON_SERIALIZER_HANDLERS) {
|
|
97
|
+
inlineBuiltInHandlers = false;
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
if (handler !== undefined) {
|
|
101
|
+
handlerEntries.push(handler);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (!inlineBuiltInHandlers) {
|
|
105
|
+
handlerEntries = [];
|
|
106
|
+
for (const handler of Object.values({
|
|
107
|
+
...DEFAULT_OPEN_API_JSON_SERIALIZER_HANDLERS,
|
|
108
|
+
...customHandlers,
|
|
109
|
+
})) {
|
|
110
|
+
if (handler !== undefined) {
|
|
111
|
+
handlerEntries.push(handler);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
this.inlineBuiltInHandlers = inlineBuiltInHandlers;
|
|
116
|
+
// undefined = no handlers to check, so the inline path can return primitives early
|
|
117
|
+
this.handlerEntries = handlerEntries.length === 0 ? undefined : handlerEntries;
|
|
118
|
+
}
|
|
119
|
+
serializeJson(data) {
|
|
120
|
+
const maps = [];
|
|
121
|
+
const blobs = [];
|
|
122
|
+
const json = this.serializeValue(data, [], maps, blobs);
|
|
123
|
+
return { json, maps, blobs };
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* `segments` is a shared mutable stack (push/pop while walking),
|
|
127
|
+
* so it must be copied before being stored in `maps`.
|
|
128
|
+
*/
|
|
129
|
+
serializeValue(data, segments, maps, blobs) {
|
|
130
|
+
const handlerEntries = this.handlerEntries;
|
|
131
|
+
/**
|
|
132
|
+
* Inlined version of DEFAULT_OPEN_API_JSON_SERIALIZER_HANDLERS: primitives
|
|
133
|
+
* are dispatched on typeof and skip every handler condition check.
|
|
134
|
+
* Must match the built-in handlers exactly.
|
|
135
|
+
* Primitives without a built-in handler return early unless custom handlers must see them.
|
|
136
|
+
*/
|
|
137
|
+
if (this.inlineBuiltInHandlers) {
|
|
138
|
+
switch (typeof data) {
|
|
139
|
+
case 'string':
|
|
140
|
+
case 'boolean':
|
|
141
|
+
if (handlerEntries === undefined) {
|
|
142
|
+
return data;
|
|
143
|
+
}
|
|
144
|
+
break;
|
|
145
|
+
case 'number':
|
|
146
|
+
if (!Number.isFinite(data)) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
if (handlerEntries === undefined) {
|
|
150
|
+
return data;
|
|
151
|
+
}
|
|
152
|
+
break;
|
|
153
|
+
case 'undefined':
|
|
154
|
+
return null;
|
|
155
|
+
case 'bigint':
|
|
156
|
+
return data.toString();
|
|
157
|
+
case 'object': {
|
|
158
|
+
if (data === null) {
|
|
159
|
+
if (handlerEntries === undefined) {
|
|
160
|
+
return data;
|
|
161
|
+
}
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
if (data instanceof Date) {
|
|
165
|
+
return Number.isNaN(data.getTime()) ? null : data.toISOString();
|
|
166
|
+
}
|
|
167
|
+
if (data instanceof URL) {
|
|
168
|
+
return data.toString();
|
|
169
|
+
}
|
|
170
|
+
if (data instanceof Set) {
|
|
171
|
+
return this.serializeValue(Array.from(data), segments, maps, blobs);
|
|
172
|
+
}
|
|
173
|
+
if (data instanceof Map) {
|
|
174
|
+
return this.serializeValue(Array.from(data.entries()), segments, maps, blobs);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (handlerEntries) {
|
|
180
|
+
for (let i = 0; i < handlerEntries.length; i++) {
|
|
181
|
+
const handler = handlerEntries[i];
|
|
182
|
+
if (handler.condition(data)) {
|
|
183
|
+
const serialized = handler.serialize(data);
|
|
184
|
+
if (handler.isTerminal) {
|
|
185
|
+
if (serialized instanceof Blob) {
|
|
186
|
+
maps.push(segments.slice());
|
|
187
|
+
blobs.push(serialized);
|
|
188
|
+
}
|
|
189
|
+
return serialized;
|
|
190
|
+
}
|
|
191
|
+
return this.serializeValue(serialized, segments, maps, blobs);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (typeof data !== 'object' || data === null) {
|
|
196
|
+
return data;
|
|
197
|
+
}
|
|
198
|
+
if (data instanceof Blob) {
|
|
199
|
+
maps.push(segments.slice());
|
|
200
|
+
blobs.push(data);
|
|
201
|
+
return data;
|
|
202
|
+
}
|
|
203
|
+
if (Array.isArray(data)) {
|
|
204
|
+
const json = [];
|
|
205
|
+
for (let i = 0; i < data.length; i++) {
|
|
206
|
+
segments.push(i);
|
|
207
|
+
json.push(this.serializeValue(data[i], segments, maps, blobs));
|
|
208
|
+
segments.pop();
|
|
209
|
+
}
|
|
210
|
+
return json;
|
|
211
|
+
}
|
|
212
|
+
if (isPlainObject(data)) {
|
|
213
|
+
const json = new NullProtoObj();
|
|
214
|
+
for (const k of Object.keys(data)) {
|
|
215
|
+
const v = data[k];
|
|
216
|
+
/**
|
|
217
|
+
* Skip custom toJSON methods to avoid JSON.stringify invoking them,
|
|
218
|
+
* which could cause meta and serialized data mismatches during deserialization.
|
|
219
|
+
* Instead, rely on custom handlers.
|
|
220
|
+
*/
|
|
221
|
+
if (k === 'toJSON' && typeof v === 'function') {
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (v === undefined) {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
segments.push(k);
|
|
228
|
+
json[k] = this.serializeValue(v, segments, maps, blobs);
|
|
229
|
+
segments.pop();
|
|
230
|
+
}
|
|
231
|
+
return json;
|
|
232
|
+
}
|
|
233
|
+
return data;
|
|
234
|
+
}
|
|
235
|
+
deserializeJson(serialized) {
|
|
236
|
+
const ref = { json: serialized.json };
|
|
237
|
+
if (serialized.blobs?.length) {
|
|
238
|
+
for (let i = 0; i < serialized.maps.length; i++) {
|
|
239
|
+
const blob = serialized.blobs[i];
|
|
240
|
+
if (!(blob instanceof Blob)) {
|
|
241
|
+
throw new TypeError(`Invalid OpenAPI serialized data: blob ${i} is not a Blob.`);
|
|
242
|
+
}
|
|
243
|
+
const segments = serialized.maps[i];
|
|
244
|
+
let original = serialized;
|
|
245
|
+
let currentRef = ref;
|
|
246
|
+
let preSegment = 'json';
|
|
247
|
+
for (let j = 0; j < segments.length; j++) {
|
|
248
|
+
original = original[preSegment];
|
|
249
|
+
currentRef = copyOnWrite(currentRef, preSegment, original);
|
|
250
|
+
preSegment = segments[j];
|
|
251
|
+
if (!Object.hasOwn(currentRef, preSegment)) {
|
|
252
|
+
throw new TypeError(`Invalid OpenAPI serialized data: segment "${preSegment}" does not exist.`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
currentRef[preSegment] = blob;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return ref.json;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { StandardBody } from '@standard-server/core';
|
|
2
|
+
import type { BracketNotationSerializerOptions } from './bracket-notation.ts';
|
|
3
|
+
import type { OpenAPIJsonSerializerOptions } from './openapi-json-serializer.ts';
|
|
4
|
+
import { OpenAPIJsonSerializer } from './openapi-json-serializer.ts';
|
|
5
|
+
export interface OpenAPISerializerSerializeOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Use FormData for serialization when nested blobs are present.
|
|
8
|
+
* Does not apply to root-level Blob values.
|
|
9
|
+
*
|
|
10
|
+
* @default true
|
|
11
|
+
*/
|
|
12
|
+
useFormDataForBlobFields?: boolean | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* When enabled, the serialized output is always returned as a FormData instance using bracket notation.
|
|
15
|
+
*
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
asFormData?: boolean | undefined;
|
|
19
|
+
}
|
|
20
|
+
export interface OpenAPISerializerOptions extends OpenAPIJsonSerializerOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Options for bracket notation serializer, like maxDeserializingEmptySlots
|
|
23
|
+
*/
|
|
24
|
+
bracketNotation?: BracketNotationSerializerOptions | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Default options for serialize method
|
|
27
|
+
*/
|
|
28
|
+
serialize?: OpenAPISerializerSerializeOptions | undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Handles one-way serialization of oRPC payloads into JSON-friendly formats,
|
|
32
|
+
* partially supporting complex data types beyond plain JSON such as `Date`, `BigInt`, and `Set`.
|
|
33
|
+
*
|
|
34
|
+
* @see {@link https://orpc.dev/docs/openapi/serializer | OpenAPI Serializer}
|
|
35
|
+
*/
|
|
36
|
+
export declare class OpenAPISerializer extends OpenAPIJsonSerializer {
|
|
37
|
+
private readonly bracketNotation;
|
|
38
|
+
private readonly defaultSerializeOptions;
|
|
39
|
+
constructor({ bracketNotation, serialize, ...options }?: OpenAPISerializerOptions);
|
|
40
|
+
serialize(data: unknown, options?: OpenAPISerializerSerializeOptions): StandardBody;
|
|
41
|
+
private serializePayload;
|
|
42
|
+
deserialize(data: StandardBody): unknown;
|
|
43
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createORPCErrorFromJson, isORPCErrorJson, toORPCError, wrapAsyncIteratorPreservingEventMeta, } from '@orpc/client';
|
|
2
|
+
import { isAsyncIteratorObject } from '@orpc/shared';
|
|
3
|
+
import { EventStreamErrorEvent } from '@standard-server/core';
|
|
4
|
+
import { BracketNotationSerializer } from './bracket-notation.js';
|
|
5
|
+
import { OpenAPIJsonSerializer } from './openapi-json-serializer.js';
|
|
6
|
+
/**
|
|
7
|
+
* Handles one-way serialization of oRPC payloads into JSON-friendly formats,
|
|
8
|
+
* partially supporting complex data types beyond plain JSON such as `Date`, `BigInt`, and `Set`.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link https://orpc.dev/docs/openapi/serializer | OpenAPI Serializer}
|
|
11
|
+
*/
|
|
12
|
+
export class OpenAPISerializer extends OpenAPIJsonSerializer {
|
|
13
|
+
bracketNotation;
|
|
14
|
+
defaultSerializeOptions;
|
|
15
|
+
constructor({ bracketNotation, serialize, ...options } = {}) {
|
|
16
|
+
super(options);
|
|
17
|
+
this.bracketNotation = new BracketNotationSerializer(bracketNotation);
|
|
18
|
+
this.defaultSerializeOptions = serialize;
|
|
19
|
+
}
|
|
20
|
+
serialize(data, options = {}) {
|
|
21
|
+
if (!options.asFormData) {
|
|
22
|
+
// standard body already supports these types without additional serialization.
|
|
23
|
+
if (data === undefined || data instanceof ReadableStream || data instanceof Blob) {
|
|
24
|
+
return data;
|
|
25
|
+
}
|
|
26
|
+
if (isAsyncIteratorObject(data)) {
|
|
27
|
+
return wrapAsyncIteratorPreservingEventMeta(data, {
|
|
28
|
+
mapResult: (result) => {
|
|
29
|
+
// standard event stream data already supports these types without additional serialization.
|
|
30
|
+
if (result.value === undefined) {
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
return { done: result.done, value: this.serializePayload(result.value, false, false) };
|
|
34
|
+
},
|
|
35
|
+
mapError: (e) => new EventStreamErrorEvent(this.serializePayload(toORPCError(e).toJSON(), false, false), {
|
|
36
|
+
cause: e,
|
|
37
|
+
}),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const useFormDataForBlobFields = options.useFormDataForBlobFields ??
|
|
42
|
+
this.defaultSerializeOptions?.useFormDataForBlobFields ??
|
|
43
|
+
true;
|
|
44
|
+
const asFormData = options.asFormData ?? this.defaultSerializeOptions?.asFormData ?? false;
|
|
45
|
+
return this.serializePayload(data, useFormDataForBlobFields, asFormData);
|
|
46
|
+
}
|
|
47
|
+
serializePayload(value, useFormDataForBlobFields, asFormData) {
|
|
48
|
+
const { json, blobs } = this.serializeJson(value);
|
|
49
|
+
if (!asFormData &&
|
|
50
|
+
(json instanceof Blob || json === undefined || !blobs?.length || !useFormDataForBlobFields)) {
|
|
51
|
+
return json;
|
|
52
|
+
}
|
|
53
|
+
const form = new FormData();
|
|
54
|
+
for (const [path, value] of this.bracketNotation.serialize(json)) {
|
|
55
|
+
if (value instanceof Blob) {
|
|
56
|
+
form.append(path, value);
|
|
57
|
+
}
|
|
58
|
+
else if (value !== undefined && value !== null) {
|
|
59
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
60
|
+
form.append(path, String(value));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return form;
|
|
64
|
+
}
|
|
65
|
+
deserialize(data) {
|
|
66
|
+
if (data === undefined || data instanceof ReadableStream || data instanceof Blob) {
|
|
67
|
+
return data;
|
|
68
|
+
}
|
|
69
|
+
if (isAsyncIteratorObject(data)) {
|
|
70
|
+
return wrapAsyncIteratorPreservingEventMeta(data, {
|
|
71
|
+
mapResult: (result) => {
|
|
72
|
+
if (result.value === undefined) {
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
return { done: result.done, value: this.deserializeJson({ json: result.value }) };
|
|
76
|
+
},
|
|
77
|
+
mapError: (e) => {
|
|
78
|
+
if (e instanceof EventStreamErrorEvent) {
|
|
79
|
+
const deserialized = this.deserializeJson({ json: e.data });
|
|
80
|
+
if (isORPCErrorJson(deserialized)) {
|
|
81
|
+
return createORPCErrorFromJson(deserialized, { cause: e });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return e;
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
if (data instanceof URLSearchParams || data instanceof FormData) {
|
|
89
|
+
data = this.bracketNotation.deserialize(Array.from(data.entries()));
|
|
90
|
+
}
|
|
91
|
+
return this.deserializeJson({ json: data });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './openapi-reference.ts';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './openapi-reference.js';
|