@orpc/trpc 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 CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
6
6
  </a>
7
7
  <a href="https://www.npmjs.com/package/@orpc/trpc">
8
- <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Ftrpc?logo=npm" />
8
+ <img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Ftrpc?logo=npm" />
9
9
  </a>
10
10
  <a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
11
11
  <img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
@@ -41,10 +41,11 @@ export const router = {
41
41
  Then call them from a client that knows every input and output, without generating anything:
42
42
 
43
43
  ```ts
44
- import type { RouterClient } from '@orpc/server'
45
- import type { router } from './router'
46
44
  import { createORPCClient } from '@orpc/client'
47
45
  import { RPCLink } from '@orpc/client/fetch'
46
+ import type { RouterClient } from '@orpc/server'
47
+
48
+ import type { router } from './router'
48
49
 
49
50
  const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
50
51
  const client: RouterClient<typeof router> = createORPCClient(link)
@@ -208,7 +209,6 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
208
209
  <tr>
209
210
  <td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
210
211
  <td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&amp;v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
211
- <td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
212
212
  </tr>
213
213
  </table>
214
214
 
@@ -0,0 +1,2 @@
1
+ export * from './to-orpc-router.ts';
2
+ export * from './to-trpc-meta.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './to-orpc-router.js';
2
+ export * from './to-trpc-meta.js';
@@ -0,0 +1,16 @@
1
+ import * as ORPC from '@orpc/server';
2
+ import type { AsyncIteratorClass } from '@orpc/shared';
3
+ import type { AnyProcedure, AnyRouter, inferRouterContext } from '@trpc/server';
4
+ export type ToORPCOutput<T> = T extends AsyncIterable<infer TData, infer TReturn, infer TNext> ? AsyncIteratorClass<TData, TReturn, TNext> : T;
5
+ export type ToORPCRouterResult<TContext extends ORPC.Context, TRecord extends Record<string, any>> = {
6
+ [K in keyof TRecord]: TRecord[K] extends AnyProcedure ? ORPC.Procedure<TContext, object, ORPC.Schema<TRecord[K]['_def']['$types']['input'], unknown>, ORPC.Schema<unknown, ToORPCOutput<TRecord[K]['_def']['$types']['output']>>, object> : TRecord[K] extends Record<string, any> ? ToORPCRouterResult<TContext, TRecord[K]> : never;
7
+ };
8
+ /**
9
+ * Converts a tRPC router into an oRPC router that works with any oRPC feature.
10
+ *
11
+ * @remarks
12
+ * **Note**: tRPC Error Formatting is not supported — errors thrown by tRPC are wrapped in `ORPCError`.
13
+ *
14
+ * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
15
+ */
16
+ export declare function toORPCRouter<T extends AnyRouter>(router: T): ToORPCRouterResult<inferRouterContext<T>, T['_def']['record']>;
@@ -0,0 +1,125 @@
1
+ import * as ORPC from '@orpc/server';
2
+ import { isNonPrimitive, set, wrapAsyncIterator } from '@orpc/shared';
3
+ import { isTrackedEnvelope, TRPCError } from '@trpc/server';
4
+ import { isAsyncIterable, isObject } from '@trpc/server/unstable-core-do-not-import';
5
+ /**
6
+ * Converts a tRPC router into an oRPC router that works with any oRPC feature.
7
+ *
8
+ * @remarks
9
+ * **Note**: tRPC Error Formatting is not supported — errors thrown by tRPC are wrapped in `ORPCError`.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
12
+ */
13
+ export function toORPCRouter(router) {
14
+ const result = recordToORPCRouterRecord(router._def.record);
15
+ for (const [key, item] of Object.entries(router._def.lazy)) {
16
+ set(result, key.split('.'), new ORPC.Lazy({
17
+ meta: {},
18
+ loader: async () => {
19
+ const router = await item.ref();
20
+ return { default: toORPCRouter(router) };
21
+ },
22
+ }));
23
+ }
24
+ return result;
25
+ }
26
+ function recordToORPCRouterRecord(records) {
27
+ const orpcRouter = {};
28
+ for (const key of Object.keys(records)) {
29
+ const item = records[key];
30
+ if (typeof item === 'function') {
31
+ orpcRouter[key] = toORPCProcedure(item);
32
+ }
33
+ else {
34
+ orpcRouter[key] = recordToORPCRouterRecord(item);
35
+ }
36
+ }
37
+ return orpcRouter;
38
+ }
39
+ function toORPCProcedure(procedure) {
40
+ const inputSchema = toStandardSchema(procedure._def.inputs.at(-1));
41
+ const outputSchema = toStandardSchema(procedure._def.output);
42
+ const meta = (procedure._def.meta ?? {});
43
+ return new ORPC.Procedure({
44
+ errorMap: {},
45
+ meta,
46
+ // `.router` (and similar) rebuilds meta from its own meta + the procedure's meta plugins,
47
+ // so the tRPC meta must be a plugin too, otherwise it would be dropped.
48
+ metaPlugins: [toTRPCMetaPlugin(meta)],
49
+ orderedMiddlewares: [],
50
+ inputSchemas: inputSchema ? [inputSchema] : undefined,
51
+ outputSchemas: outputSchema ? [outputSchema] : undefined,
52
+ // tRPC procedure calling already validates the input/output
53
+ disableInputValidation: true,
54
+ disableOutputValidation: true,
55
+ handler: async ({ context, signal, path, input, lastEventId }) => {
56
+ try {
57
+ const trpcInput = lastEventId !== undefined && (input === undefined || isObject(input))
58
+ ? { ...input, lastEventId }
59
+ : input;
60
+ const output = await procedure({
61
+ ctx: context,
62
+ signal,
63
+ path: path.join('.'),
64
+ type: procedure._def.type,
65
+ // Only the raw input: tRPC merges `input` into the parsed input, so passing it would keep keys the schema strips
66
+ getRawInput: async () => trpcInput,
67
+ // TODO: this should infer from context when using oRPC Batch Plugin
68
+ batchIndex: 0,
69
+ });
70
+ if (isAsyncIterable(output)) {
71
+ return wrapAsyncIterator(output[Symbol.asyncIterator](), {
72
+ mapResult: (result) => {
73
+ if (isTrackedEnvelope(result.value)) {
74
+ const [id, data] = result.value;
75
+ return {
76
+ done: result.done,
77
+ value: ORPC.withEventMeta({
78
+ id,
79
+ data,
80
+ }, {
81
+ id,
82
+ }),
83
+ };
84
+ }
85
+ return result;
86
+ },
87
+ mapError: toORPCError,
88
+ });
89
+ }
90
+ return output;
91
+ }
92
+ catch (cause) {
93
+ throw toORPCError(cause);
94
+ }
95
+ },
96
+ });
97
+ }
98
+ /**
99
+ * Re-applies tRPC meta on top of the incoming meta, shallow merged like tRPC `.meta` calls.
100
+ */
101
+ function toTRPCMetaPlugin(trpcMeta) {
102
+ return {
103
+ name: '~trpc',
104
+ init: (meta) => ({ ...meta, ...trpcMeta }),
105
+ };
106
+ }
107
+ function toORPCError(error) {
108
+ if (error instanceof TRPCError) {
109
+ return new ORPC.ORPCError(error.code, {
110
+ message: error.message,
111
+ cause: error,
112
+ });
113
+ }
114
+ return error;
115
+ }
116
+ /**
117
+ * Ensures the parser is a standard schema before exposing it to oRPC,
118
+ * so schemas remain usable for type inference and OpenAPI generation.
119
+ */
120
+ function toStandardSchema(schema) {
121
+ if (!isNonPrimitive(schema) || !('~standard' in schema) || !isNonPrimitive(schema['~standard'])) {
122
+ return undefined;
123
+ }
124
+ return schema;
125
+ }
@@ -0,0 +1,31 @@
1
+ import type { AnyMetaPlugin } from '@orpc/contract';
2
+ /**
3
+ * Resolve oRPC meta plugins into a plain meta object usable as tRPC meta.
4
+ *
5
+ * This simulates how oRPC builders apply meta plugins, so well-known plugins
6
+ * like `openapi` from `@orpc/openapi` can be used with tRPC builders.
7
+ *
8
+ * @remarks
9
+ * **Warning**: Chained tRPC `.meta` calls merge shallowly, so oRPC metadata merge logic
10
+ * (e.g. accumulating openapi `tags`) only works within a single `toTRPCMeta` call.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const example = t.procedure
15
+ * .meta(toTRPCMeta(openapi({ path: '/hello' })))
16
+ * .query(() => 'Hello, World!')
17
+ *
18
+ * const merged = t.procedure
19
+ * .meta({
20
+ * ...toTRPCMeta(
21
+ * openapi({ path: '/hello' }),
22
+ * openapi({ method: 'POST' }),
23
+ * ),
24
+ * other: 'value',
25
+ * })
26
+ * .mutation(() => 'Hello, World!')
27
+ * ```
28
+ *
29
+ * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
30
+ */
31
+ export declare function toTRPCMeta(...plugins: AnyMetaPlugin[]): Record<string, any>;
@@ -0,0 +1,34 @@
1
+ import { resolveMetaPlugins } from '@orpc/contract';
2
+ /**
3
+ * Resolve oRPC meta plugins into a plain meta object usable as tRPC meta.
4
+ *
5
+ * This simulates how oRPC builders apply meta plugins, so well-known plugins
6
+ * like `openapi` from `@orpc/openapi` can be used with tRPC builders.
7
+ *
8
+ * @remarks
9
+ * **Warning**: Chained tRPC `.meta` calls merge shallowly, so oRPC metadata merge logic
10
+ * (e.g. accumulating openapi `tags`) only works within a single `toTRPCMeta` call.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const example = t.procedure
15
+ * .meta(toTRPCMeta(openapi({ path: '/hello' })))
16
+ * .query(() => 'Hello, World!')
17
+ *
18
+ * const merged = t.procedure
19
+ * .meta({
20
+ * ...toTRPCMeta(
21
+ * openapi({ path: '/hello' }),
22
+ * openapi({ method: 'POST' }),
23
+ * ),
24
+ * other: 'value',
25
+ * })
26
+ * .mutation(() => 'Hello, World!')
27
+ * ```
28
+ *
29
+ * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
30
+ */
31
+ export function toTRPCMeta(...plugins) {
32
+ const [meta] = resolveMetaPlugins({}, undefined, plugins);
33
+ return meta;
34
+ }
package/package.json CHANGED
@@ -1,55 +1,53 @@
1
1
  {
2
2
  "name": "@orpc/trpc",
3
- "type": "module",
4
- "version": "2.0.0-beta.48",
3
+ "version": "2.0.0-beta.49",
5
4
  "description": "tRPC interop for oRPC: reuse existing tRPC routers with oRPC clients and OpenAPI",
6
- "license": "MIT",
7
- "funding": [
8
- "https://github.com/sponsors/dinwwwh",
9
- "https://opencollective.com/middleapi"
5
+ "keywords": [
6
+ "interop",
7
+ "migration",
8
+ "openapi",
9
+ "orpc",
10
+ "rpc",
11
+ "trpc",
12
+ "typesafe",
13
+ "typescript"
10
14
  ],
11
15
  "homepage": "https://orpc.dev",
16
+ "license": "MIT",
12
17
  "repository": {
13
18
  "type": "git",
14
19
  "url": "git+https://github.com/middleapi/orpc.git",
15
20
  "directory": "packages/trpc"
16
21
  },
17
- "keywords": [
18
- "orpc",
19
- "trpc",
20
- "interop",
21
- "migration",
22
- "rpc",
23
- "openapi",
24
- "typescript",
25
- "typesafe"
22
+ "funding": [
23
+ "https://github.com/sponsors/dinwwwh",
24
+ "https://opencollective.com/middleapi"
26
25
  ],
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "type": "module",
27
30
  "sideEffects": false,
28
31
  "exports": {
29
32
  "./package.json": "./package.json",
30
33
  ".": {
31
- "types": "./dist/index.d.mts",
32
- "import": "./dist/index.mjs",
33
- "default": "./dist/index.mjs"
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js",
36
+ "default": "./dist/index.js"
34
37
  }
35
38
  },
36
- "files": [
37
- "dist"
38
- ],
39
- "peerDependencies": {
40
- "@trpc/server": ">=11.4.2"
41
- },
42
39
  "dependencies": {
43
- "@orpc/contract": "2.0.0-beta.48",
44
- "@orpc/server": "2.0.0-beta.48",
45
- "@orpc/shared": "2.0.0-beta.48"
40
+ "@orpc/contract": "2.0.0-beta.49",
41
+ "@orpc/server": "2.0.0-beta.49",
42
+ "@orpc/shared": "2.0.0-beta.49"
46
43
  },
47
44
  "devDependencies": {
48
- "@orpc/openapi": "2.0.0-beta.48",
49
- "@trpc/server": "^11.22.1",
45
+ "@orpc/openapi": "2.0.0-beta.49",
46
+ "@trpc/server": "^11.23.0",
50
47
  "zod": "^4.6.7"
51
48
  },
52
- "scripts": {
53
- "type:check": "tsc -b"
54
- }
49
+ "peerDependencies": {
50
+ "@trpc/server": ">=11.4.2"
51
+ },
52
+ "scripts": {}
55
53
  }
package/dist/index.d.mts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./to-orpc-router.mjs";
2
- export * from "./to-trpc-meta.mjs";
package/dist/index.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from "./to-orpc-router.mjs";
2
- export * from "./to-trpc-meta.mjs";
@@ -1,17 +0,0 @@
1
- import type { AsyncIteratorClass } from "@orpc/shared";
2
- import type { AnyProcedure, AnyRouter, inferRouterContext } from "@trpc/server";
3
- import * as ORPC from "@orpc/server";
4
- export type ToORPCOutput<T> = T extends AsyncIterable<infer TData, infer TReturn, infer TNext> ? AsyncIteratorClass<TData, TReturn, TNext> : T;
5
- export type ToORPCRouterResult<
6
- TContext extends ORPC.Context,
7
- TRecord extends Record<string, any>
8
- > = { [K in keyof TRecord]: TRecord[K] extends AnyProcedure ? ORPC.Procedure<TContext, object, ORPC.Schema<TRecord[K]["_def"]["$types"]["input"], unknown>, ORPC.Schema<unknown, ToORPCOutput<TRecord[K]["_def"]["$types"]["output"]>>, object> : TRecord[K] extends Record<string, any> ? ToORPCRouterResult<TContext, TRecord[K]> : never };
9
- /**
10
- * Converts a tRPC router into an oRPC router that works with any oRPC feature.
11
- *
12
- * @remarks
13
- * **Note**: tRPC Error Formatting is not supported — errors thrown by tRPC are wrapped in `ORPCError`.
14
- *
15
- * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
16
- */
17
- export declare function toORPCRouter<T extends AnyRouter>(router: T): ToORPCRouterResult<inferRouterContext<T>, T["_def"]["record"]>;
@@ -1,99 +0,0 @@
1
- import * as ORPC from "@orpc/server";
2
- import { isTypescriptObject, set, wrapAsyncIterator } from "@orpc/shared";
3
- import { isTrackedEnvelope, TRPCError } from "@trpc/server";
4
- import { isAsyncIterable, isObject } from "@trpc/server/unstable-core-do-not-import";
5
-
6
- export function toORPCRouter(router) {
7
- const result = recordToORPCRouterRecord(router._def.record);
8
- for (const [key, item] of Object.entries(router._def.lazy)) {
9
- set(result, key.split("."), new ORPC.Lazy({
10
- meta: {},
11
- loader: async () => {
12
- const router = await item.ref();
13
- return { default: toORPCRouter(router) };
14
- }
15
- }));
16
- }
17
- return result;
18
- }
19
- function recordToORPCRouterRecord(records) {
20
- const orpcRouter = {};
21
- for (const key of Object.keys(records)) {
22
- const item = records[key];
23
- if (typeof item === "function") {
24
- orpcRouter[key] = toORPCProcedure(item);
25
- } else {
26
- orpcRouter[key] = recordToORPCRouterRecord(item);
27
- }
28
- }
29
- return orpcRouter;
30
- }
31
- function toORPCProcedure(procedure) {
32
- const inputSchema = toStandardSchema(procedure._def.inputs.at(-1));
33
- const outputSchema = toStandardSchema(procedure._def.output);
34
- return new ORPC.Procedure({
35
- errorMap: {},
36
- meta: procedure._def.meta ?? {},
37
- orderedMiddlewares: [],
38
- inputSchemas: inputSchema ? [inputSchema] : undefined,
39
- outputSchemas: outputSchema ? [outputSchema] : undefined,
40
-
41
- disableInputValidation: true,
42
- disableOutputValidation: true,
43
- handler: async ({ context, signal, path, input, lastEventId }) => {
44
- try {
45
- const trpcInput = lastEventId !== undefined && (input === undefined || isObject(input)) ? {
46
- ...input,
47
- lastEventId
48
- } : input;
49
- const output = await procedure({
50
- ctx: context,
51
- signal,
52
- path: path.join("."),
53
- type: procedure._def.type,
54
-
55
- getRawInput: async () => trpcInput,
56
-
57
- batchIndex: 0
58
- });
59
- if (isAsyncIterable(output)) {
60
- return wrapAsyncIterator(output[Symbol.asyncIterator](), {
61
- mapResult: (result) => {
62
- if (isTrackedEnvelope(result.value)) {
63
- const [id, data] = result.value;
64
- return {
65
- done: result.done,
66
- value: ORPC.withEventMeta({
67
- id,
68
- data
69
- }, { id })
70
- };
71
- }
72
- return result;
73
- },
74
- mapError: toORPCError
75
- });
76
- }
77
- return output;
78
- } catch (cause) {
79
- throw toORPCError(cause);
80
- }
81
- }
82
- });
83
- }
84
- function toORPCError(error) {
85
- if (error instanceof TRPCError) {
86
- return new ORPC.ORPCError(error.code, {
87
- message: error.message,
88
- cause: error
89
- });
90
- }
91
- return error;
92
- }
93
-
94
- function toStandardSchema(schema) {
95
- if (!isTypescriptObject(schema) || !("~standard" in schema) || !isTypescriptObject(schema["~standard"])) {
96
- return undefined;
97
- }
98
- return schema;
99
- }
@@ -1,31 +0,0 @@
1
- import type { AnyMetaPlugin } from "@orpc/contract";
2
- /**
3
- * Resolve oRPC meta plugins into a plain meta object usable as tRPC meta.
4
- *
5
- * This simulates how oRPC builders apply meta plugins, so well-known plugins
6
- * like `openapi` from `@orpc/openapi` can be used with tRPC builders.
7
- *
8
- * @remarks
9
- * **Warning**: Chained tRPC `.meta` calls merge shallowly, so oRPC metadata merge logic
10
- * (e.g. accumulating openapi `tags`) only works within a single `toTRPCMeta` call.
11
- *
12
- * @example
13
- * ```ts
14
- * const example = t.procedure
15
- * .meta(toTRPCMeta(openapi({ path: '/hello' })))
16
- * .query(() => 'Hello, World!')
17
- *
18
- * const merged = t.procedure
19
- * .meta({
20
- * ...toTRPCMeta(
21
- * openapi({ path: '/hello' }),
22
- * openapi({ method: 'POST' }),
23
- * ),
24
- * other: 'value',
25
- * })
26
- * .mutation(() => 'Hello, World!')
27
- * ```
28
- *
29
- * @see {@link https://orpc.dev/docs/integrations/trpc | tRPC Integration}
30
- */
31
- export declare function toTRPCMeta(...plugins: AnyMetaPlugin[]): Record<string, any>;
@@ -1,6 +0,0 @@
1
- import { resolveMetaPlugins } from "@orpc/contract";
2
-
3
- export function toTRPCMeta(...plugins) {
4
- const [meta] = resolveMetaPlugins({}, undefined, plugins);
5
- return meta;
6
- }