@orpc/openapi 0.0.0-next.ccd4e42 → 0.0.0-next.d0e429d

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 ADDED
@@ -0,0 +1,91 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/openapi">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fopenapi?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
30
+ - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
+ - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
+ - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
+ - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
+ - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
+ - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
+ - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
+ - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
+ - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
+ - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
+ - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
+ - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
+ - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
+ - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
+ - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
+ - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
61
+
62
+ ## `@orpc/openapi`
63
+
64
+ Generate OpenAPI specs and handle OpenAPI requests. Read the [documentation](https://orpc.unnoq.com/docs/openapi/getting-started) for more information.
65
+
66
+ ```ts
67
+ import { createServer } from 'node:http'
68
+ import { OpenAPIHandler } from '@orpc/openapi/node'
69
+ import { CORSPlugin } from '@orpc/server/plugins'
70
+
71
+ const handler = new OpenAPIHandler(router, {
72
+ plugins: [new CORSPlugin()]
73
+ })
74
+
75
+ const server = createServer(async (req, res) => {
76
+ const result = await handler.handle(req, res, {
77
+ context: { headers: req.headers }
78
+ })
79
+
80
+ if (!result.matched) {
81
+ res.statusCode = 404
82
+ res.end('No procedure matched')
83
+ }
84
+ })
85
+
86
+ server.listen(3000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:3000'))
87
+ ```
88
+
89
+ ## License
90
+
91
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -1,27 +1,27 @@
1
1
  import {
2
2
  OpenAPICodec,
3
3
  OpenAPIMatcher
4
- } from "./chunk-M5HOHBLW.js";
4
+ } from "./chunk-LTTK3H5J.js";
5
5
 
6
6
  // src/adapters/fetch/openapi-handler.ts
7
- import { fetchRequestToStandardRequest, standardResponseToFetchResponse } from "@orpc/server/fetch";
8
7
  import { StandardHandler } from "@orpc/server/standard";
8
+ import { toFetchResponse, toStandardRequest } from "@orpc/standard-server-fetch";
9
9
  var OpenAPIHandler = class {
10
10
  standardHandler;
11
11
  constructor(router, options) {
12
- const matcher = options?.matcher ?? new OpenAPIMatcher(options);
13
- const codec = options?.codec ?? new OpenAPICodec(options);
12
+ const matcher = options?.matcher ?? new OpenAPIMatcher();
13
+ const codec = options?.codec ?? new OpenAPICodec();
14
14
  this.standardHandler = new StandardHandler(router, matcher, codec, options);
15
15
  }
16
- async handle(request, ...rest) {
17
- const standardRequest = fetchRequestToStandardRequest(request);
18
- const result = await this.standardHandler.handle(standardRequest, ...rest);
16
+ async handle(request, ...[options]) {
17
+ const standardRequest = toStandardRequest(request);
18
+ const result = await this.standardHandler.handle(standardRequest, options);
19
19
  if (!result.matched) {
20
20
  return result;
21
21
  }
22
22
  return {
23
23
  matched: true,
24
- response: standardResponseToFetchResponse(result.response)
24
+ response: toFetchResponse(result.response, options)
25
25
  };
26
26
  }
27
27
  };
@@ -29,4 +29,4 @@ var OpenAPIHandler = class {
29
29
  export {
30
30
  OpenAPIHandler
31
31
  };
32
- //# sourceMappingURL=chunk-HQ34JZI7.js.map
32
+ //# sourceMappingURL=chunk-5TK7F2TC.js.map
@@ -0,0 +1,157 @@
1
+ import {
2
+ standardizeHTTPPath
3
+ } from "./chunk-XGHV4TH3.js";
4
+
5
+ // src/adapters/standard/openapi-codec.ts
6
+ import { OpenAPISerializer } from "@orpc/client/openapi";
7
+ import { fallbackContractConfig } from "@orpc/contract";
8
+ import { isObject } from "@orpc/shared";
9
+ var OpenAPICodec = class {
10
+ constructor(serializer = new OpenAPISerializer()) {
11
+ this.serializer = serializer;
12
+ }
13
+ async decode(request, params, procedure) {
14
+ const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
15
+ if (inputStructure === "compact") {
16
+ const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
17
+ if (data === void 0) {
18
+ return params;
19
+ }
20
+ if (isObject(data)) {
21
+ return {
22
+ ...params,
23
+ ...data
24
+ };
25
+ }
26
+ return data;
27
+ }
28
+ const deserializeSearchParams = () => {
29
+ return this.serializer.deserialize(request.url.searchParams);
30
+ };
31
+ return {
32
+ params,
33
+ get query() {
34
+ const value = deserializeSearchParams();
35
+ Object.defineProperty(this, "query", { value, writable: true });
36
+ return value;
37
+ },
38
+ set query(value) {
39
+ Object.defineProperty(this, "query", { value, writable: true });
40
+ },
41
+ headers: request.headers,
42
+ body: this.serializer.deserialize(await request.body())
43
+ };
44
+ }
45
+ encode(output, procedure) {
46
+ const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
47
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
48
+ if (outputStructure === "compact") {
49
+ return {
50
+ status: successStatus,
51
+ headers: {},
52
+ body: this.serializer.serialize(output)
53
+ };
54
+ }
55
+ if (!isObject(output)) {
56
+ throw new Error(
57
+ 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
58
+ );
59
+ }
60
+ return {
61
+ status: successStatus,
62
+ headers: output.headers ?? {},
63
+ body: this.serializer.serialize(output.body)
64
+ };
65
+ }
66
+ encodeError(error) {
67
+ return {
68
+ status: error.status,
69
+ headers: {},
70
+ body: this.serializer.serialize(error.toJSON())
71
+ };
72
+ }
73
+ };
74
+
75
+ // src/adapters/standard/openapi-matcher.ts
76
+ import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
77
+ import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
78
+ import { addRoute, createRouter, findRoute } from "rou3";
79
+ var OpenAPIMatcher = class {
80
+ tree = createRouter();
81
+ pendingRouters = [];
82
+ init(router, path = []) {
83
+ const laziedOptions = eachContractProcedure({
84
+ router,
85
+ path
86
+ }, ({ path: path2, contract }) => {
87
+ const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
88
+ const httpPath = contract["~orpc"].route.path ? toRou3Pattern(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
89
+ if (isProcedure(contract)) {
90
+ addRoute(this.tree, method, httpPath, {
91
+ path: path2,
92
+ contract,
93
+ procedure: contract,
94
+ // this mean dev not used contract-first so we can used contract as procedure directly
95
+ router
96
+ });
97
+ } else {
98
+ addRoute(this.tree, method, httpPath, {
99
+ path: path2,
100
+ contract,
101
+ procedure: void 0,
102
+ router
103
+ });
104
+ }
105
+ });
106
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
107
+ ...option,
108
+ httpPathPrefix: convertPathToHttpPath(option.path),
109
+ laziedPrefix: getLazyRouterPrefix(option.lazied)
110
+ })));
111
+ }
112
+ async match(method, pathname) {
113
+ if (this.pendingRouters.length) {
114
+ const newPendingRouters = [];
115
+ for (const pendingRouter of this.pendingRouters) {
116
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
117
+ const { default: router } = await unlazy(pendingRouter.lazied);
118
+ this.init(router, pendingRouter.path);
119
+ } else {
120
+ newPendingRouters.push(pendingRouter);
121
+ }
122
+ }
123
+ this.pendingRouters = newPendingRouters;
124
+ }
125
+ const match = findRoute(this.tree, method, pathname);
126
+ if (!match) {
127
+ return void 0;
128
+ }
129
+ if (!match.data.procedure) {
130
+ const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
131
+ if (!isProcedure(maybeProcedure)) {
132
+ throw new Error(`
133
+ [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
134
+ Ensure that the procedure is correctly defined and matches the expected contract.
135
+ `);
136
+ }
137
+ match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
138
+ }
139
+ return {
140
+ path: match.data.path,
141
+ procedure: match.data.procedure,
142
+ params: match.params ? decodeParams(match.params) : void 0
143
+ };
144
+ }
145
+ };
146
+ function toRou3Pattern(path) {
147
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "**:$1").replace(/\{([^}]+)\}/g, ":$1");
148
+ }
149
+ function decodeParams(params) {
150
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
151
+ }
152
+
153
+ export {
154
+ OpenAPICodec,
155
+ OpenAPIMatcher
156
+ };
157
+ //# sourceMappingURL=chunk-LTTK3H5J.js.map
@@ -0,0 +1,13 @@
1
+ // src/utils.ts
2
+ function standardizeHTTPPath(path) {
3
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
4
+ }
5
+ function toOpenAPI31RoutePattern(path) {
6
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "{$1}");
7
+ }
8
+
9
+ export {
10
+ standardizeHTTPPath,
11
+ toOpenAPI31RoutePattern
12
+ };
13
+ //# sourceMappingURL=chunk-XGHV4TH3.js.map
package/dist/fetch.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-HQ34JZI7.js";
4
- import "./chunk-M5HOHBLW.js";
5
- import "./chunk-BHJYKXQL.js";
3
+ } from "./chunk-5TK7F2TC.js";
4
+ import "./chunk-LTTK3H5J.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/hono.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-HQ34JZI7.js";
4
- import "./chunk-M5HOHBLW.js";
5
- import "./chunk-BHJYKXQL.js";
3
+ } from "./chunk-5TK7F2TC.js";
4
+ import "./chunk-LTTK3H5J.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/index.js CHANGED
@@ -1,7 +1,53 @@
1
1
  import {
2
- JSONSerializer,
3
- standardizeHTTPPath
4
- } from "./chunk-BHJYKXQL.js";
2
+ standardizeHTTPPath,
3
+ toOpenAPI31RoutePattern
4
+ } from "./chunk-XGHV4TH3.js";
5
+
6
+ // src/openapi-operation-extender.ts
7
+ import { isProcedure } from "@orpc/server";
8
+ var OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
9
+ function setOperationExtender(o, extend) {
10
+ return new Proxy(o, {
11
+ get(target, prop, receiver) {
12
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
13
+ return extend;
14
+ }
15
+ return Reflect.get(target, prop, receiver);
16
+ }
17
+ });
18
+ }
19
+ function getOperationExtender(o) {
20
+ return o[OPERATION_EXTENDER_SYMBOL];
21
+ }
22
+ function extendOperation(operation, procedure) {
23
+ const operationExtenders = [];
24
+ for (const errorItem of Object.values(procedure["~orpc"].errorMap)) {
25
+ const maybeExtender = getOperationExtender(errorItem);
26
+ if (maybeExtender) {
27
+ operationExtenders.push(maybeExtender);
28
+ }
29
+ }
30
+ if (isProcedure(procedure)) {
31
+ for (const middleware of procedure["~orpc"].middlewares) {
32
+ const maybeExtender = getOperationExtender(middleware);
33
+ if (maybeExtender) {
34
+ operationExtenders.push(maybeExtender);
35
+ }
36
+ }
37
+ }
38
+ let currentOperation = operation;
39
+ for (const extender of operationExtenders) {
40
+ if (typeof extender === "function") {
41
+ currentOperation = extender(currentOperation, procedure);
42
+ } else {
43
+ currentOperation = {
44
+ ...currentOperation,
45
+ ...extender
46
+ };
47
+ }
48
+ }
49
+ return currentOperation;
50
+ }
5
51
 
6
52
  // src/openapi.ts
7
53
  import { OpenApiBuilder } from "openapi3-ts/oas31";
@@ -34,7 +80,9 @@ var OpenAPIContentBuilder = class {
34
80
  };
35
81
 
36
82
  // src/openapi-generator.ts
37
- import { fallbackContractConfig as fallbackContractConfig2, fallbackORPCErrorStatus } from "@orpc/contract";
83
+ import { fallbackORPCErrorStatus } from "@orpc/client";
84
+ import { OpenAPIJsonSerializer } from "@orpc/client/openapi";
85
+ import { fallbackContractConfig as fallbackContractConfig2, getEventIteratorSchemaDetails } from "@orpc/contract";
38
86
  import { eachAllContractProcedure } from "@orpc/server";
39
87
  import { group } from "@orpc/shared";
40
88
 
@@ -183,14 +231,14 @@ var OpenAPIOutputStructureParser = class {
183
231
  };
184
232
 
185
233
  // src/openapi-parameters-builder.ts
186
- import { get, isPlainObject, omit } from "@orpc/shared";
234
+ import { get, isObject, omit } from "@orpc/shared";
187
235
  var OpenAPIParametersBuilder = class {
188
236
  build(paramIn, jsonSchema, options) {
189
237
  const parameters = [];
190
238
  for (const name in jsonSchema.properties) {
191
239
  const schema = jsonSchema.properties[name];
192
240
  const paramExamples = jsonSchema.examples?.filter((example) => {
193
- return isPlainObject(example) && name in example;
241
+ return isObject(example) && name in example;
194
242
  }).map((example) => {
195
243
  return example[name];
196
244
  });
@@ -251,7 +299,7 @@ var CompositeSchemaConverter = class {
251
299
  };
252
300
 
253
301
  // src/schema-utils.ts
254
- import { isPlainObject as isPlainObject2 } from "@orpc/shared";
302
+ import { isObject as isObject2 } from "@orpc/shared";
255
303
 
256
304
  // src/schema.ts
257
305
  import * as JSONSchema from "json-schema-typed/draft-2020-12";
@@ -287,10 +335,10 @@ var NON_LOGIC_KEYWORDS = [
287
335
  // src/schema-utils.ts
288
336
  var SchemaUtils = class {
289
337
  isFileSchema(schema) {
290
- return typeof schema === "object" && schema.type === "string" && typeof schema.contentMediaType === "string";
338
+ return isObject2(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
291
339
  }
292
340
  isObjectSchema(schema) {
293
- return typeof schema === "object" && schema.type === "object";
341
+ return isObject2(schema) && schema.type === "object";
294
342
  }
295
343
  isAnySchema(schema) {
296
344
  return schema === true || Object.keys(schema).filter((key) => !NON_LOGIC_KEYWORDS.includes(key)).length === 0;
@@ -313,7 +361,7 @@ var SchemaUtils = class {
313
361
  }, {});
314
362
  matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
315
363
  matched.examples = schema.examples?.map((example) => {
316
- if (!isPlainObject2(example)) {
364
+ if (!isObject2(example)) {
317
365
  return example;
318
366
  }
319
367
  return Object.entries(example).reduce((acc, [key, value]) => {
@@ -329,7 +377,7 @@ var SchemaUtils = class {
329
377
  }, {});
330
378
  rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
331
379
  rest.examples = schema.examples?.map((example) => {
332
- if (!isPlainObject2(example)) {
380
+ if (!isObject2(example)) {
333
381
  return example;
334
382
  }
335
383
  return Object.entries(example).reduce((acc, [key, value]) => {
@@ -389,7 +437,7 @@ var OpenAPIGenerator = class {
389
437
  this.parametersBuilder = options?.parametersBuilder ?? new OpenAPIParametersBuilder();
390
438
  this.schemaConverter = new CompositeSchemaConverter(options?.schemaConverters ?? []);
391
439
  this.schemaUtils = options?.schemaUtils ?? new SchemaUtils();
392
- this.jsonSerializer = options?.jsonSerializer ?? new JSONSerializer();
440
+ this.jsonSerializer = options?.jsonSerializer ?? new OpenAPIJsonSerializer();
393
441
  this.contentBuilder = options?.contentBuilder ?? new OpenAPIContentBuilder(this.schemaUtils);
394
442
  this.pathParser = new OpenAPIPathParser();
395
443
  this.inputStructureParser = options?.inputStructureParser ?? new OpenAPIInputStructureParser(this.schemaConverter, this.schemaUtils, this.pathParser);
@@ -415,27 +463,124 @@ var OpenAPIGenerator = class {
415
463
  return;
416
464
  }
417
465
  const method = fallbackContractConfig2("defaultMethod", def.route?.method);
418
- const httpPath = def.route?.path ? standardizeHTTPPath(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
419
- const inputStructure = fallbackContractConfig2("defaultInputStructure", def.route?.inputStructure);
420
- const outputStructure = fallbackContractConfig2("defaultOutputStructure", def.route?.outputStructure);
421
- const { paramsSchema, querySchema, headersSchema, bodySchema } = this.inputStructureParser.parse(contract, inputStructure);
422
- const { headersSchema: resHeadersSchema, bodySchema: resBodySchema } = this.outputStructureParser.parse(contract, outputStructure);
423
- const params = paramsSchema ? this.parametersBuilder.build("path", paramsSchema, {
424
- required: true
425
- }) : [];
426
- const query = querySchema ? this.parametersBuilder.build("query", querySchema) : [];
427
- const headers = headersSchema ? this.parametersBuilder.build("header", headersSchema) : [];
428
- const parameters = [...params, ...query, ...headers];
429
- const requestBody = bodySchema !== void 0 ? {
430
- required: this.schemaUtils.isUndefinableSchema(bodySchema),
431
- content: this.contentBuilder.build(bodySchema)
432
- } : void 0;
433
- const responses = {};
434
- responses[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
435
- description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
436
- content: resBodySchema !== void 0 ? this.contentBuilder.build(resBodySchema) : void 0,
437
- headers: resHeadersSchema !== void 0 ? this.parametersBuilder.buildHeadersObject(resHeadersSchema) : void 0
438
- };
466
+ const httpPath = def.route?.path ? toOpenAPI31RoutePattern(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
467
+ const { parameters, requestBody } = (() => {
468
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(def.inputSchema);
469
+ if (eventIteratorSchemaDetails) {
470
+ const requestBody3 = {
471
+ required: true,
472
+ content: {
473
+ "text/event-stream": {
474
+ schema: {
475
+ oneOf: [
476
+ {
477
+ type: "object",
478
+ properties: {
479
+ event: { type: "string", const: "message" },
480
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.yields, { strategy: "input" }),
481
+ id: { type: "string" },
482
+ retry: { type: "number" }
483
+ },
484
+ required: ["event", "data"]
485
+ },
486
+ {
487
+ type: "object",
488
+ properties: {
489
+ event: { type: "string", const: "done" },
490
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.returns, { strategy: "input" }),
491
+ id: { type: "string" },
492
+ retry: { type: "number" }
493
+ },
494
+ required: ["event", "data"]
495
+ },
496
+ {
497
+ type: "object",
498
+ properties: {
499
+ event: { type: "string", const: "error" },
500
+ data: {},
501
+ id: { type: "string" },
502
+ retry: { type: "number" }
503
+ },
504
+ required: ["event", "data"]
505
+ }
506
+ ]
507
+ }
508
+ }
509
+ }
510
+ };
511
+ return { requestBody: requestBody3, parameters: [] };
512
+ }
513
+ const inputStructure = fallbackContractConfig2("defaultInputStructure", def.route?.inputStructure);
514
+ const { paramsSchema, querySchema, headersSchema, bodySchema } = this.inputStructureParser.parse(contract, inputStructure);
515
+ const params = paramsSchema ? this.parametersBuilder.build("path", paramsSchema, {
516
+ required: true
517
+ }) : [];
518
+ const query = querySchema ? this.parametersBuilder.build("query", querySchema) : [];
519
+ const headers = headersSchema ? this.parametersBuilder.build("header", headersSchema) : [];
520
+ const parameters2 = [...params, ...query, ...headers];
521
+ const requestBody2 = bodySchema !== void 0 ? {
522
+ required: this.schemaUtils.isUndefinableSchema(bodySchema),
523
+ content: this.contentBuilder.build(bodySchema)
524
+ } : void 0;
525
+ return { parameters: parameters2, requestBody: requestBody2 };
526
+ })();
527
+ const { responses } = (() => {
528
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(def.outputSchema);
529
+ if (eventIteratorSchemaDetails) {
530
+ const responses3 = {};
531
+ responses3[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
532
+ description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
533
+ content: {
534
+ "text/event-stream": {
535
+ schema: {
536
+ oneOf: [
537
+ {
538
+ type: "object",
539
+ properties: {
540
+ event: { type: "string", const: "message" },
541
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.yields, { strategy: "input" }),
542
+ id: { type: "string" },
543
+ retry: { type: "number" }
544
+ },
545
+ required: ["event", "data"]
546
+ },
547
+ {
548
+ type: "object",
549
+ properties: {
550
+ event: { type: "string", const: "done" },
551
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.returns, { strategy: "input" }),
552
+ id: { type: "string" },
553
+ retry: { type: "number" }
554
+ },
555
+ required: ["event", "data"]
556
+ },
557
+ {
558
+ type: "object",
559
+ properties: {
560
+ event: { type: "string", const: "error" },
561
+ data: {},
562
+ id: { type: "string" },
563
+ retry: { type: "number" }
564
+ },
565
+ required: ["event", "data"]
566
+ }
567
+ ]
568
+ }
569
+ }
570
+ }
571
+ };
572
+ return { responses: responses3 };
573
+ }
574
+ const outputStructure = fallbackContractConfig2("defaultOutputStructure", def.route?.outputStructure);
575
+ const { headersSchema: resHeadersSchema, bodySchema: resBodySchema } = this.outputStructureParser.parse(contract, outputStructure);
576
+ const responses2 = {};
577
+ responses2[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
578
+ description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
579
+ content: resBodySchema !== void 0 ? this.contentBuilder.build(resBodySchema) : void 0,
580
+ headers: resHeadersSchema !== void 0 ? this.parametersBuilder.buildHeadersObject(resHeadersSchema) : void 0
581
+ };
582
+ return { responses: responses2 };
583
+ })();
439
584
  const errors = group(Object.entries(def.errorMap ?? {}).filter(([_, config]) => config).map(([code, config]) => ({
440
585
  ...config,
441
586
  code,
@@ -506,8 +651,9 @@ var OpenAPIGenerator = class {
506
651
  requestBody,
507
652
  responses
508
653
  };
654
+ const extendedOperation = extendOperation(operation, contract);
509
655
  builder.addPath(httpPath, {
510
- [method.toLocaleLowerCase()]: operation
656
+ [method.toLocaleLowerCase()]: extendedOperation
511
657
  });
512
658
  } catch (e) {
513
659
  if (e instanceof OpenAPIError) {
@@ -526,14 +672,18 @@ var OpenAPIGenerator = class {
526
672
  }
527
673
  }
528
674
  });
529
- return this.jsonSerializer.serialize(builder.getSpec());
675
+ return this.jsonSerializer.serialize(builder.getSpec())[0];
530
676
  }
531
677
  };
678
+
679
+ // src/index.ts
680
+ var oo = {
681
+ spec: setOperationExtender
682
+ };
532
683
  export {
533
684
  CompositeSchemaConverter,
534
685
  JSONSchema,
535
686
  Format as JSONSchemaFormat,
536
- JSONSerializer,
537
687
  NON_LOGIC_KEYWORDS,
538
688
  OpenAPIContentBuilder,
539
689
  OpenAPIGenerator,
@@ -541,6 +691,11 @@ export {
541
691
  OpenAPIPathParser,
542
692
  OpenApiBuilder,
543
693
  SchemaUtils,
544
- standardizeHTTPPath
694
+ extendOperation,
695
+ getOperationExtender,
696
+ oo,
697
+ setOperationExtender,
698
+ standardizeHTTPPath,
699
+ toOpenAPI31RoutePattern
545
700
  };
546
701
  //# sourceMappingURL=index.js.map
package/dist/next.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-HQ34JZI7.js";
4
- import "./chunk-M5HOHBLW.js";
5
- import "./chunk-BHJYKXQL.js";
3
+ } from "./chunk-5TK7F2TC.js";
4
+ import "./chunk-LTTK3H5J.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };