@orpc/openapi 0.0.0-next.ef3ba82 → 0.0.0-next.f17a1a0

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.
Files changed (41) hide show
  1. package/README.md +91 -0
  2. package/dist/chunk-ATDLVTJE.js +32 -0
  3. package/dist/chunk-PGCWJMRO.js +157 -0
  4. package/dist/chunk-XGHV4TH3.js +13 -0
  5. package/dist/fetch.js +7 -666
  6. package/dist/hono.js +9 -0
  7. package/dist/index.js +613 -4333
  8. package/dist/next.js +9 -0
  9. package/dist/node.js +30 -0
  10. package/dist/src/adapters/fetch/index.d.ts +2 -0
  11. package/dist/src/adapters/fetch/openapi-handler.d.ts +11 -0
  12. package/dist/src/adapters/hono/index.d.ts +2 -0
  13. package/dist/src/adapters/next/index.d.ts +2 -0
  14. package/dist/src/adapters/node/index.d.ts +2 -0
  15. package/dist/src/adapters/node/openapi-handler.d.ts +11 -0
  16. package/dist/src/adapters/standard/index.d.ts +4 -0
  17. package/dist/src/adapters/standard/openapi-codec.d.ts +13 -0
  18. package/dist/src/adapters/standard/openapi-handler.d.ts +5 -0
  19. package/dist/src/adapters/standard/openapi-matcher.d.ts +10 -0
  20. package/dist/src/index.d.ts +15 -1
  21. package/dist/src/openapi-content-builder.d.ts +10 -0
  22. package/dist/src/openapi-error.d.ts +3 -0
  23. package/dist/src/openapi-generator.d.ts +67 -0
  24. package/dist/src/openapi-input-structure-parser.d.ts +22 -0
  25. package/dist/src/openapi-operation-extender.d.ts +7 -0
  26. package/dist/src/openapi-output-structure-parser.d.ts +18 -0
  27. package/dist/src/openapi-parameters-builder.d.ts +12 -0
  28. package/dist/src/openapi-path-parser.d.ts +8 -0
  29. package/dist/src/openapi.d.ts +3 -0
  30. package/dist/src/schema-converter.d.ts +16 -0
  31. package/dist/src/schema-utils.d.ts +11 -0
  32. package/dist/src/schema.d.ts +12 -0
  33. package/dist/src/utils.d.ts +4 -0
  34. package/dist/standard.js +10 -0
  35. package/package.json +34 -13
  36. package/dist/src/fetch/base-handler.d.ts +0 -14
  37. package/dist/src/fetch/index.d.ts +0 -3
  38. package/dist/src/fetch/server-handler.d.ts +0 -2
  39. package/dist/src/fetch/serverless-handler.d.ts +0 -2
  40. package/dist/src/generator.d.ts +0 -23
  41. package/dist/src/zod-to-json-schema.d.ts +0 -42
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.
@@ -0,0 +1,32 @@
1
+ import {
2
+ OpenAPICodec,
3
+ OpenAPIMatcher
4
+ } from "./chunk-PGCWJMRO.js";
5
+
6
+ // src/adapters/fetch/openapi-handler.ts
7
+ import { toFetchResponse, toStandardRequest } from "@orpc/server-standard-fetch";
8
+ import { StandardHandler } from "@orpc/server/standard";
9
+ var OpenAPIHandler = class {
10
+ standardHandler;
11
+ constructor(router, options) {
12
+ const matcher = options?.matcher ?? new OpenAPIMatcher();
13
+ const codec = options?.codec ?? new OpenAPICodec();
14
+ this.standardHandler = new StandardHandler(router, matcher, codec, options);
15
+ }
16
+ async handle(request, ...rest) {
17
+ const standardRequest = toStandardRequest(request);
18
+ const result = await this.standardHandler.handle(standardRequest, ...rest);
19
+ if (!result.matched) {
20
+ return result;
21
+ }
22
+ return {
23
+ matched: true,
24
+ response: toFetchResponse(result.response)
25
+ };
26
+ }
27
+ };
28
+
29
+ export {
30
+ OpenAPIHandler
31
+ };
32
+ //# sourceMappingURL=chunk-ATDLVTJE.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-PGCWJMRO.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