@trpc/client 11.22.2-canary.7.c01346ec8 → 11.23.0
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 +0 -8
- package/dist/TRPCClientError-CxFRO7Js.mjs.map +1 -1
- package/dist/{httpBatchLink-DO3WQoxu.cjs → httpBatchLink-Cmao5uUF.cjs} +1 -1
- package/dist/{httpBatchLink-BMtWxLJV.mjs → httpBatchLink-DPypDRI1.mjs} +2 -2
- package/dist/httpBatchLink-DPypDRI1.mjs.map +1 -0
- package/dist/{httpLink-Tm93WWFA.mjs → httpLink--yqaZ9lA.mjs} +2 -2
- package/dist/{httpLink-Tm93WWFA.mjs.map → httpLink--yqaZ9lA.mjs.map} +1 -1
- package/dist/{httpLink-MDJTSlpi.cjs → httpLink-B6E1HSLY.cjs} +1 -1
- package/dist/{httpUtils-CB_100ND.mjs → httpUtils-CAZsqwOQ.mjs} +3 -2
- package/dist/httpUtils-CAZsqwOQ.mjs.map +1 -0
- package/dist/{httpUtils-cggqcHz0.cjs → httpUtils-CrSF2CZF.cjs} +2 -1
- package/dist/index.cjs +13 -7
- package/dist/index.d.cts +8 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +8 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +13 -8
- package/dist/index.mjs.map +1 -1
- package/dist/links/httpBatchLink.cjs +1 -1
- package/dist/links/httpBatchLink.mjs +1 -1
- package/dist/links/httpLink.cjs +1 -1
- package/dist/links/httpLink.mjs +1 -1
- package/dist/links/wsLink/wsLink.cjs +1 -1
- package/dist/links/wsLink/wsLink.mjs +1 -1
- package/dist/types-BxbMkv6C.d.cts.map +1 -1
- package/dist/types-CAPs7vhA.d.mts.map +1 -1
- package/dist/{wsLink-Bm5LKL6z.mjs → wsLink--7trqYPG.mjs} +2 -1
- package/dist/wsLink--7trqYPG.mjs.map +1 -0
- package/dist/wsLink-C3hsDLsL.d.cts.map +1 -1
- package/dist/{wsLink-CKAsNP9P.cjs → wsLink-CQGBu_VZ.cjs} +1 -0
- package/dist/wsLink-DnvK9sTv.d.mts.map +1 -1
- package/package.json +10 -21
- package/skills/client-setup/SKILL.md +240 -207
- package/skills/links/SKILL.md +98 -224
- package/skills/links/references/client-links-httpBatchLink.md +210 -0
- package/skills/links/references/client-links-httpBatchStreamLink.md +159 -0
- package/skills/links/references/client-links-httpLink.md +63 -0
- package/skills/links/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/links/references/client-links-localLink.md +78 -0
- package/skills/links/references/client-links-loggerLink.md +66 -0
- package/skills/links/references/client-links-retryLink.md +89 -0
- package/skills/links/references/client-links-splitLink.md +103 -0
- package/skills/links/references/client-links-wsLink.md +122 -0
- package/skills/superjson/SKILL.md +132 -183
- package/src/TRPCClientError.ts +2 -2
- package/src/createTRPCClient.ts +1 -1
- package/src/getFetch.ts +0 -1
- package/src/internals/dataLoader.ts +1 -1
- package/src/links/httpBatchStreamLink.ts +1 -1
- package/src/links/internals/httpUtils.ts +6 -1
- package/src/links/localLink.ts +10 -4
- package/src/links/types.ts +2 -1
- package/src/links/wsLink/wsClient/utils.ts +1 -1
- package/src/links/wsLink/wsClient/wsClient.ts +4 -0
- package/bin/intent.js +0 -20
- package/dist/httpBatchLink-BMtWxLJV.mjs.map +0 -1
- package/dist/httpUtils-CB_100ND.mjs.map +0 -1
- package/dist/wsLink-Bm5LKL6z.mjs.map +0 -1
- package/skills/links/references/link-options.md +0 -248
|
@@ -1,90 +1,95 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: superjson
|
|
3
|
-
description:
|
|
4
|
-
Configure SuperJSON transformer on both server initTRPC.create({ transformer:
|
|
5
|
-
superjson }) and every client terminating link (httpBatchLink, httpLink, wsLink,
|
|
6
|
-
httpSubscriptionLink) to support Date, Map, Set, BigInt over the wire. Transformer
|
|
7
|
-
must match on both sides. In v11, transformer goes on individual links, not the
|
|
8
|
-
client constructor.
|
|
9
|
-
type: composition
|
|
10
|
-
library: trpc
|
|
11
|
-
library_version: '11.16.0'
|
|
3
|
+
description: "Configure SuperJSON transformer on both server initTRPC.create({ transformer: superjson }) and every client terminating link (httpBatchLink, httpLink, httpBatchStreamLink, wsLink, httpSubscriptionLink), including each splitLink branch, to support Date, Map, Set, BigInt over the wire. Transformer must match on both sides. In v11, transformer goes on individual links, not the client constructor. Also devalue, custom and separate input/output transformers."
|
|
12
4
|
requires:
|
|
13
5
|
- server-setup
|
|
14
6
|
- client-setup
|
|
15
7
|
sources:
|
|
16
|
-
- www/docs/server/data-transformers.md
|
|
8
|
+
- www/v11/docs/server/data-transformers.md
|
|
9
|
+
metadata:
|
|
10
|
+
type: composition
|
|
11
|
+
library: trpc
|
|
12
|
+
library_version: 11.23.0
|
|
17
13
|
---
|
|
18
14
|
|
|
19
|
-
|
|
15
|
+
<!-- Generated from www/v11/docs/server/data-transformers.md by www/build/skills.ts. Edit the docs instead. -->
|
|
20
16
|
|
|
21
|
-
|
|
17
|
+
# Data Transformers
|
|
22
18
|
|
|
23
|
-
|
|
19
|
+
From https://trpc.io/docs/server/data-transformers
|
|
20
|
+
|
|
21
|
+
You are able to serialize the response data & input args. The transformers need to be added both to the server and the client.
|
|
22
|
+
|
|
23
|
+
> [!NOTE] Info
|
|
24
|
+
> A transformer is optional. Without one, tRPC serializes data with `JSON.stringify`, so values that JSON can't represent don't round-trip: a `Date` arrives on the client as a string, and a `Map` or `Set` are always converted to an empty object (`{}`). Add a transformer like superjson (below) if you need those types preserved on the client.
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
## Using [superjson](https://github.com/blitz-js/superjson)
|
|
28
|
+
|
|
29
|
+
SuperJSON allows us to transparently use, e.g., standard `Date`/`Map`/`Set`s over the wire between the server and client. That is, you can return any of these types from your API-resolver and use them in the client without having to recreate the objects from JSON.
|
|
30
|
+
|
|
31
|
+
### How to
|
|
32
|
+
|
|
33
|
+
#### 1. Install
|
|
24
34
|
|
|
25
35
|
```bash
|
|
26
36
|
npm install superjson
|
|
27
37
|
```
|
|
28
38
|
|
|
29
|
-
|
|
39
|
+
#### 2. Add to your `initTRPC`
|
|
30
40
|
|
|
31
|
-
```ts
|
|
32
|
-
// server/trpc.ts
|
|
41
|
+
```ts no-check title="server/routers/_app.ts"
|
|
33
42
|
import { initTRPC } from '@trpc/server';
|
|
34
43
|
import superjson from 'superjson';
|
|
35
44
|
|
|
36
|
-
const t = initTRPC.create({
|
|
45
|
+
export const t = initTRPC.create({
|
|
37
46
|
transformer: superjson,
|
|
38
47
|
});
|
|
39
|
-
|
|
40
|
-
export const router = t.router;
|
|
41
|
-
export const publicProcedure = t.procedure;
|
|
42
48
|
```
|
|
43
49
|
|
|
44
|
-
|
|
50
|
+
#### 3. Add to `httpLink()`, `wsLink()`, etc
|
|
51
|
+
|
|
52
|
+
> TypeScript will guide you to where you need to add `transformer` as soon as you've added it on the `initTRPC`-object
|
|
45
53
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
54
|
+
`createTRPCClient()`:
|
|
55
|
+
|
|
56
|
+
```ts no-check title="src/app/_trpc/client.ts"
|
|
57
|
+
import { createTRPCClient, httpLink } from '@trpc/client';
|
|
58
|
+
import type { AppRouter } from './server';
|
|
49
59
|
import superjson from 'superjson';
|
|
50
|
-
import type { AppRouter } from './server/trpc';
|
|
51
60
|
|
|
52
|
-
const client = createTRPCClient<AppRouter>({
|
|
61
|
+
export const client = createTRPCClient<AppRouter>({
|
|
53
62
|
links: [
|
|
54
|
-
|
|
55
|
-
url: 'http://localhost:3000
|
|
63
|
+
httpLink({
|
|
64
|
+
url: 'http://localhost:3000',
|
|
56
65
|
transformer: superjson,
|
|
57
66
|
}),
|
|
58
67
|
],
|
|
59
68
|
});
|
|
60
69
|
```
|
|
61
70
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
## Core Patterns
|
|
71
|
+
Every terminating link needs the transformer, including both branches of a [`splitLink`](https://trpc.io/docs/client/links/splitLink). With [`wsLink`](https://trpc.io/docs/client/links/wsLink), it goes on `wsLink()`, not `createWSClient()`.
|
|
65
72
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
```ts
|
|
73
|
+
```ts no-check title="src/app/_trpc/client.ts"
|
|
69
74
|
import {
|
|
70
75
|
createTRPCClient,
|
|
71
76
|
httpBatchLink,
|
|
72
77
|
httpSubscriptionLink,
|
|
73
78
|
splitLink,
|
|
74
79
|
} from '@trpc/client';
|
|
80
|
+
import type { AppRouter } from './server';
|
|
75
81
|
import superjson from 'superjson';
|
|
76
|
-
import type { AppRouter } from './server/trpc';
|
|
77
82
|
|
|
78
|
-
const client = createTRPCClient<AppRouter>({
|
|
83
|
+
export const client = createTRPCClient<AppRouter>({
|
|
79
84
|
links: [
|
|
80
85
|
splitLink({
|
|
81
86
|
condition: (op) => op.type === 'subscription',
|
|
82
87
|
true: httpSubscriptionLink({
|
|
83
|
-
url: 'http://localhost:3000
|
|
88
|
+
url: 'http://localhost:3000',
|
|
84
89
|
transformer: superjson,
|
|
85
90
|
}),
|
|
86
91
|
false: httpBatchLink({
|
|
87
|
-
url: 'http://localhost:3000
|
|
92
|
+
url: 'http://localhost:3000',
|
|
88
93
|
transformer: superjson,
|
|
89
94
|
}),
|
|
90
95
|
}),
|
|
@@ -92,182 +97,126 @@ const client = createTRPCClient<AppRouter>({
|
|
|
92
97
|
});
|
|
93
98
|
```
|
|
94
99
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
### SuperJSON with wsLink
|
|
100
|
+
Now a `Date` returned by a procedure is a `Date` on the client:
|
|
98
101
|
|
|
99
|
-
```ts
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
102
|
+
```ts no-check title="src/usage.ts"
|
|
103
|
+
const event = await client.event.query();
|
|
104
|
+
event.at.getFullYear();
|
|
105
|
+
```
|
|
103
106
|
|
|
104
|
-
|
|
105
|
-
url: 'ws://localhost:3000',
|
|
106
|
-
});
|
|
107
|
+
## Using [devalue](https://github.com/Rich-Harris/devalue)
|
|
107
108
|
|
|
108
|
-
|
|
109
|
-
links: [
|
|
110
|
-
wsLink<AppRouter>({
|
|
111
|
-
client: wsClient,
|
|
112
|
-
transformer: superjson,
|
|
113
|
-
}),
|
|
114
|
-
],
|
|
115
|
-
});
|
|
116
|
-
```
|
|
109
|
+
Devalue works like superjson, focusing on performance and compact payloads, but at the cost of a less human-readable body.
|
|
117
110
|
|
|
118
|
-
###
|
|
119
|
-
|
|
120
|
-
```ts
|
|
121
|
-
// server
|
|
122
|
-
import { z } from 'zod';
|
|
123
|
-
import { publicProcedure, router } from './trpc';
|
|
124
|
-
|
|
125
|
-
const appRouter = router({
|
|
126
|
-
getEvent: publicProcedure
|
|
127
|
-
.input(z.object({ id: z.string() }))
|
|
128
|
-
.query(({ input }) => {
|
|
129
|
-
return {
|
|
130
|
-
id: input.id,
|
|
131
|
-
name: 'Launch Party',
|
|
132
|
-
date: new Date('2025-01-01T00:00:00Z'),
|
|
133
|
-
};
|
|
134
|
-
}),
|
|
135
|
-
});
|
|
111
|
+
### How to
|
|
136
112
|
|
|
137
|
-
|
|
138
|
-
```
|
|
113
|
+
#### 1. Install
|
|
139
114
|
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
const event = await client.getEvent.query({ id: '1' });
|
|
143
|
-
console.log(event.date instanceof Date); // true
|
|
144
|
-
console.log(event.date.getFullYear()); // 2025
|
|
115
|
+
```bash
|
|
116
|
+
npm install devalue
|
|
145
117
|
```
|
|
146
118
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
## Common Mistakes
|
|
119
|
+
#### 2. Add to `utils/trpc.ts`
|
|
150
120
|
|
|
151
|
-
|
|
121
|
+
Here we use `parse` and `stringify` as they [mitigate XSS](https://github.com/Rich-Harris/devalue?tab=readme-ov-file#xss-mitigation).
|
|
152
122
|
|
|
153
|
-
|
|
123
|
+
```ts no-check title="utils/trpc.ts"
|
|
124
|
+
import { parse, stringify } from 'devalue';
|
|
154
125
|
|
|
155
|
-
|
|
156
|
-
// Server
|
|
157
|
-
const t = initTRPC.create({ transformer: superjson });
|
|
126
|
+
// [...]
|
|
158
127
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
128
|
+
export const transformer = {
|
|
129
|
+
deserialize: (object: any) => parse(object),
|
|
130
|
+
serialize: (object: any) => stringify(object),
|
|
131
|
+
};
|
|
163
132
|
```
|
|
164
133
|
|
|
165
|
-
|
|
134
|
+
#### 3. Add to your `initTRPC`
|
|
166
135
|
|
|
167
|
-
```ts
|
|
168
|
-
|
|
169
|
-
|
|
136
|
+
```ts no-check title="server/routers/_app.ts"
|
|
137
|
+
import { initTRPC } from '@trpc/server';
|
|
138
|
+
import { transformer } from '../../utils/trpc';
|
|
170
139
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
links: [
|
|
174
|
-
httpBatchLink({
|
|
175
|
-
url: 'http://localhost:3000/trpc',
|
|
176
|
-
transformer: superjson,
|
|
177
|
-
}),
|
|
178
|
-
],
|
|
140
|
+
export const t = initTRPC.create({
|
|
141
|
+
transformer,
|
|
179
142
|
});
|
|
180
143
|
```
|
|
181
144
|
|
|
182
|
-
|
|
145
|
+
#### 4. Add to `httpLink()`, `wsLink()`, etc
|
|
183
146
|
|
|
184
|
-
|
|
147
|
+
> TypeScript will guide you to where you need to add `transformer` as soon as you've added it on the `initTRPC`-object
|
|
185
148
|
|
|
186
|
-
|
|
149
|
+
`createTRPCClient()`:
|
|
187
150
|
|
|
188
|
-
|
|
151
|
+
```ts no-check title="src/app/_trpc/client.ts"
|
|
152
|
+
import { createTRPCClient, httpLink } from '@trpc/client';
|
|
153
|
+
import type { AppRouter } from './server/routers/_app';
|
|
154
|
+
import { transformer } from './utils/trpc';
|
|
189
155
|
|
|
190
|
-
|
|
191
|
-
createTRPCClient<AppRouter>({
|
|
156
|
+
export const client = createTRPCClient<AppRouter>({
|
|
192
157
|
links: [
|
|
193
|
-
|
|
194
|
-
url: 'http://localhost:3000
|
|
195
|
-
transformer
|
|
158
|
+
httpLink({
|
|
159
|
+
url: 'http://localhost:3000',
|
|
160
|
+
transformer,
|
|
196
161
|
}),
|
|
197
162
|
],
|
|
198
163
|
});
|
|
199
164
|
```
|
|
200
165
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
Wrong:
|
|
246
|
-
|
|
247
|
-
```ts
|
|
248
|
-
// Server -- no transformer
|
|
249
|
-
const t = initTRPC.create();
|
|
250
|
-
|
|
251
|
-
// Client
|
|
252
|
-
httpBatchLink({ url, transformer: superjson });
|
|
253
|
-
```
|
|
254
|
-
|
|
255
|
-
Correct:
|
|
256
|
-
|
|
257
|
-
```ts
|
|
258
|
-
// Server
|
|
259
|
-
const t = initTRPC.create({ transformer: superjson });
|
|
260
|
-
|
|
261
|
-
// Client
|
|
262
|
-
httpBatchLink({ url, transformer: superjson });
|
|
166
|
+
## Different transformers for upload and download
|
|
167
|
+
|
|
168
|
+
If a transformer should only be used for one direction or different transformers should be used for upload and download (e.g., for performance reasons), you can provide individual transformers for upload and download. Make sure you use the same combined transformer everywhere.
|
|
169
|
+
|
|
170
|
+
## `DataTransformer` interface
|
|
171
|
+
|
|
172
|
+
```ts no-check
|
|
173
|
+
export interface DataTransformer {
|
|
174
|
+
serialize(object: any): any;
|
|
175
|
+
deserialize(object: any): any;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
interface InputDataTransformer extends DataTransformer {
|
|
179
|
+
/**
|
|
180
|
+
* This function runs **on the client** before sending the data to the server.
|
|
181
|
+
*/
|
|
182
|
+
serialize(object: any): any;
|
|
183
|
+
/**
|
|
184
|
+
* This function runs **on the server** to transform the data before it is passed to the resolver
|
|
185
|
+
*/
|
|
186
|
+
deserialize(object: any): any;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
interface OutputDataTransformer extends DataTransformer {
|
|
190
|
+
/**
|
|
191
|
+
* This function runs **on the server** before sending the data to the client.
|
|
192
|
+
*/
|
|
193
|
+
serialize(object: any): any;
|
|
194
|
+
/**
|
|
195
|
+
* This function runs **only on the client** to transform the data sent from the server.
|
|
196
|
+
*/
|
|
197
|
+
deserialize(object: any): any;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export interface CombinedDataTransformer {
|
|
201
|
+
/**
|
|
202
|
+
* Specify how the data sent from the client to the server should be transformed.
|
|
203
|
+
*/
|
|
204
|
+
input: InputDataTransformer;
|
|
205
|
+
/**
|
|
206
|
+
* Specify how the data sent from the server to the client should be transformed.
|
|
207
|
+
*/
|
|
208
|
+
output: OutputDataTransformer;
|
|
209
|
+
}
|
|
263
210
|
```
|
|
264
211
|
|
|
265
|
-
|
|
212
|
+
## Common mistakes
|
|
266
213
|
|
|
267
|
-
|
|
214
|
+
- **A transformer on only one side, or on only some links.** As long as the client is typed with your `AppRouter`, TypeScript catches this: a link without `transformer` fails with `Property 'transformer' is missing`, and a `transformer` on the client when the server has none fails with ``You must define a transformer on your `initTRPC`-object first``. If the types are bypassed, the mismatch shows up at runtime instead: data arrives still encoded (superjson's `{ json, meta }` wrapper), or calls fail with `Unable to transform response from server`.
|
|
215
|
+
- **Creating a link outside the `links` array.** A link created on its own, for example inside a custom link, isn't checked against your router, so a missing transformer isn't reported. Pass the router type, as in `httpBatchLink<AppRouter>({ url, transformer })`, to get the check back.
|
|
216
|
+
- **Passing `transformer` to `createTRPCClient()`.** TypeScript rejects it with `The transformer property has moved to httpLink/httpBatchLink/wsLink`.
|
|
217
|
+
- **Forgetting to transform data you hydrate yourself.** The links only transform tRPC requests and responses. If you dehydrate a TanStack Query cache on the server and hydrate it on the client, also set `serializeData` and `deserializeData`, as shown in [the Query Client factory](https://trpc.io/docs/client/tanstack-react-query/server-components#3-create-a-query-client-factory).
|
|
268
218
|
|
|
269
|
-
##
|
|
219
|
+
## Related skills
|
|
270
220
|
|
|
271
|
-
- `
|
|
272
|
-
- `
|
|
273
|
-
- `server-setup` -- initTRPC.create() where the server transformer is configured
|
|
221
|
+
- `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`
|
|
222
|
+
- `client-setup` (https://trpc.io/docs/client/vanilla/setup): `npx @tanstack/intent@latest load @trpc/client#client-setup`
|
package/src/TRPCClientError.ts
CHANGED
|
@@ -48,7 +48,7 @@ export class TRPCClientError<TRouterOrProcedure extends InferrableClientTypes>
|
|
|
48
48
|
extends Error
|
|
49
49
|
implements TRPCClientErrorBase<inferErrorShape<TRouterOrProcedure>>
|
|
50
50
|
{
|
|
51
|
-
//
|
|
51
|
+
// oxlint-disable-next-line typescript/ban-ts-comment
|
|
52
52
|
// @ts-ignore override doesn't work in all environments due to "This member cannot have an 'override' modifier because it is not declared in the base class 'Error'"
|
|
53
53
|
public override readonly cause;
|
|
54
54
|
public readonly shape: Maybe<inferErrorShape<TRouterOrProcedure>>;
|
|
@@ -70,7 +70,7 @@ export class TRPCClientError<TRouterOrProcedure extends InferrableClientTypes>
|
|
|
70
70
|
) {
|
|
71
71
|
const cause = opts?.cause;
|
|
72
72
|
|
|
73
|
-
//
|
|
73
|
+
// oxlint-disable-next-line typescript/ban-ts-comment
|
|
74
74
|
// @ts-ignore https://github.com/tc39/proposal-error-cause
|
|
75
75
|
super(message, { cause });
|
|
76
76
|
|
package/src/createTRPCClient.ts
CHANGED
package/src/getFetch.ts
CHANGED
|
@@ -124,7 +124,7 @@ export function httpBatchStreamLink<TRouter extends AnyRouter>(
|
|
|
124
124
|
const [head] = await jsonlStreamConsumer<
|
|
125
125
|
Record<string, Promise<any>>
|
|
126
126
|
>({
|
|
127
|
-
//
|
|
127
|
+
// oxlint-disable-next-line typescript/no-non-null-assertion
|
|
128
128
|
from: res.body!,
|
|
129
129
|
deserialize: (data) =>
|
|
130
130
|
resolvedOpts.transformer.output.deserialize(data),
|
|
@@ -206,8 +206,13 @@ export async function fetchHTTPResponse(opts: HTTPRequestOptions) {
|
|
|
206
206
|
}
|
|
207
207
|
return heads;
|
|
208
208
|
})();
|
|
209
|
+
// Header names are case-insensitive, so a `Content-Type` set by the caller
|
|
210
|
+
// replaces ours instead of being sent alongside it
|
|
211
|
+
const hasContentType = Object.keys(resolvedHeaders).some(
|
|
212
|
+
(key) => key.toLowerCase() === 'content-type',
|
|
213
|
+
);
|
|
209
214
|
const headers = {
|
|
210
|
-
...(opts.contentTypeHeader && method !== 'GET'
|
|
215
|
+
...(opts.contentTypeHeader && method !== 'GET' && !hasContentType
|
|
211
216
|
? { 'content-type': opts.contentTypeHeader }
|
|
212
217
|
: {}),
|
|
213
218
|
...(opts.trpcAcceptHeader
|
package/src/links/localLink.ts
CHANGED
|
@@ -37,7 +37,7 @@ export type LocalLinkOptions<TRouter extends AnyRouter> = {
|
|
|
37
37
|
*
|
|
38
38
|
* @see https://trpc.io/docs/client/links/localLink
|
|
39
39
|
*/
|
|
40
|
-
export function
|
|
40
|
+
export function localLink<TRouter extends AnyRouter>(
|
|
41
41
|
opts: LocalLinkOptions<TRouter>,
|
|
42
42
|
): TRPCLink<TRouter> {
|
|
43
43
|
const transformer = getTransformer(opts.transformer);
|
|
@@ -286,8 +286,14 @@ export function unstable_localLink<TRouter extends AnyRouter>(
|
|
|
286
286
|
};
|
|
287
287
|
});
|
|
288
288
|
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* @deprecated use {@link localLink} instead
|
|
292
|
+
* @function
|
|
293
|
+
*/
|
|
294
|
+
export const unstable_localLink = localLink;
|
|
295
|
+
|
|
289
296
|
/**
|
|
290
|
-
* @deprecated
|
|
297
|
+
* @deprecated use {@link localLink} instead
|
|
291
298
|
*/
|
|
292
|
-
export const experimental_localLink
|
|
293
|
-
unstable_localLink;
|
|
299
|
+
export const experimental_localLink = localLink;
|
package/src/links/types.ts
CHANGED
|
@@ -40,7 +40,8 @@ interface HeadersInitEsque {
|
|
|
40
40
|
* @internal
|
|
41
41
|
*/
|
|
42
42
|
export type HTTPHeaders =
|
|
43
|
-
|
|
43
|
+
| HeadersInitEsque
|
|
44
|
+
| Record<string, string[] | string | undefined>;
|
|
44
45
|
|
|
45
46
|
/**
|
|
46
47
|
* The default `fetch` implementation has an overloaded signature. By convention this library
|
|
@@ -62,7 +62,7 @@ export function withResolvers<T>() {
|
|
|
62
62
|
reject = rej;
|
|
63
63
|
});
|
|
64
64
|
|
|
65
|
-
//
|
|
65
|
+
// oxlint-disable-next-line typescript/no-non-null-assertion
|
|
66
66
|
return { promise, resolve: resolve!, reject: reject! };
|
|
67
67
|
}
|
|
68
68
|
|
|
@@ -255,6 +255,10 @@ export class WsClient {
|
|
|
255
255
|
*/
|
|
256
256
|
private reconnecting: Promise<void> | null = null;
|
|
257
257
|
private reconnect(closedError: TRPCWebSocketClosedError) {
|
|
258
|
+
if (!this.allowReconnect) {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
|
|
258
262
|
this.connectionState.next({
|
|
259
263
|
type: 'state',
|
|
260
264
|
state: 'connecting',
|
package/bin/intent.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Auto-generated by @tanstack/intent setup
|
|
3
|
-
// Exposes the intent end-user CLI for consumers of this library.
|
|
4
|
-
// Commit this file, then add to your package.json:
|
|
5
|
-
// "bin": { "intent": "./bin/intent.js" }
|
|
6
|
-
try {
|
|
7
|
-
await import('@tanstack/intent/intent-library');
|
|
8
|
-
} catch (e) {
|
|
9
|
-
if (e?.code === 'ERR_MODULE_NOT_FOUND' || e?.code === 'MODULE_NOT_FOUND') {
|
|
10
|
-
console.error('@tanstack/intent is not installed.');
|
|
11
|
-
console.error('');
|
|
12
|
-
console.error('Install it as a dev dependency:');
|
|
13
|
-
console.error(' npm add -D @tanstack/intent');
|
|
14
|
-
console.error('');
|
|
15
|
-
console.error('Or run directly:');
|
|
16
|
-
console.error(' npx @tanstack/intent@latest list');
|
|
17
|
-
process.exit(1);
|
|
18
|
-
}
|
|
19
|
-
throw e;
|
|
20
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"httpBatchLink-BMtWxLJV.mjs","names":[],"sources":["../src/internals/dataLoader.ts","../src/links/httpBatchLink.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\ntype BatchItem<TKey, TValue> = {\n aborted: boolean;\n key: TKey;\n resolve: ((value: TValue) => void) | null;\n reject: ((error: Error) => void) | null;\n batch: Batch<TKey, TValue> | null;\n};\ntype Batch<TKey, TValue> = {\n items: BatchItem<TKey, TValue>[];\n};\nexport type BatchLoader<TKey, TValue> = {\n validate: (keys: TKey[]) => boolean;\n fetch: (keys: TKey[]) => Promise<TValue[] | Promise<TValue>[]>;\n};\n\n/**\n * A function that should never be called unless we messed something up.\n */\nconst throwFatalError = () => {\n throw new Error(\n 'Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new',\n );\n};\n\n/**\n * Dataloader that's very inspired by https://github.com/graphql/dataloader\n * Less configuration, no caching, and allows you to cancel requests\n * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled\n */\nexport function dataLoader<TKey, TValue>(\n batchLoader: BatchLoader<TKey, TValue>,\n) {\n let pendingItems: BatchItem<TKey, TValue>[] | null = null;\n let dispatchTimer: ReturnType<typeof setTimeout> | null = null;\n\n const destroyTimerAndPendingItems = () => {\n clearTimeout(dispatchTimer as any);\n dispatchTimer = null;\n pendingItems = null;\n };\n\n /**\n * Iterate through the items and split them into groups based on the `batchLoader`'s validate function\n */\n function groupItems(items: BatchItem<TKey, TValue>[]) {\n const groupedItems: BatchItem<TKey, TValue>[][] = [[]];\n let index = 0;\n while (true) {\n const item = items[index];\n if (!item) {\n // we're done\n break;\n }\n const lastGroup = groupedItems[groupedItems.length - 1]!;\n\n if (item.aborted) {\n // Item was aborted before it was dispatched\n item.reject?.(new Error('Aborted'));\n index++;\n continue;\n }\n\n const isValid = batchLoader.validate(\n lastGroup.concat(item).map((it) => it.key),\n );\n\n if (isValid) {\n lastGroup.push(item);\n index++;\n continue;\n }\n\n if (lastGroup.length === 0) {\n item.reject?.(new Error('Input is too big for a single dispatch'));\n index++;\n continue;\n }\n // Create new group, next iteration will try to add the item to that\n groupedItems.push([]);\n }\n return groupedItems;\n }\n\n function dispatch() {\n const groupedItems = groupItems(pendingItems!);\n destroyTimerAndPendingItems();\n\n // Create batches for each group of items\n for (const items of groupedItems) {\n if (!items.length) {\n continue;\n }\n const batch: Batch<TKey, TValue> = {\n items,\n };\n for (const item of items) {\n item.batch = batch;\n }\n const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));\n\n promise\n .then(async (result) => {\n await Promise.all(\n result.map(async (valueOrPromise, index) => {\n const item = batch.items[index]!;\n try {\n const value = await Promise.resolve(valueOrPromise);\n\n item.resolve?.(value);\n } catch (cause) {\n item.reject?.(cause as Error);\n }\n\n item.batch = null;\n item.reject = null;\n item.resolve = null;\n }),\n );\n\n for (const item of batch.items) {\n item.reject?.(new Error('Missing result'));\n item.batch = null;\n }\n })\n .catch((cause) => {\n for (const item of batch.items) {\n item.reject?.(cause);\n item.batch = null;\n }\n });\n }\n }\n function load(key: TKey): Promise<TValue> {\n const item: BatchItem<TKey, TValue> = {\n aborted: false,\n key,\n batch: null,\n resolve: throwFatalError,\n reject: throwFatalError,\n };\n\n const promise = new Promise<TValue>((resolve, reject) => {\n item.reject = reject;\n item.resolve = resolve;\n\n pendingItems ??= [];\n pendingItems.push(item);\n });\n\n dispatchTimer ??= setTimeout(dispatch);\n\n return promise;\n }\n\n return {\n load,\n };\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport { transformResult } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport { allAbortSignals, raceAbortSignals } from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n getUrl,\n jsonHttpRequester,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\n/**\n * @see https://trpc.io/docs/client/links/httpBatchLink\n */\nexport function httpBatchLink<TRouter extends AnyRouter>(\n opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<Operation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n const signal = allAbortSignals(...batchOps.map((op) => op.signal));\n\n const res = await jsonHttpRequester({\n ...resolvedOpts,\n path,\n inputs,\n type,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<Operation>,\n });\n }\n return opts.headers;\n },\n signal,\n });\n const resJSON = Array.isArray(res.json)\n ? res.json\n : batchOps.map(() => res.json);\n const result = resJSON.map((item) => ({\n meta: res.meta,\n json: item,\n }));\n return result;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const promise = loader.load({\n ...op,\n signal: raceAbortSignals(op.signal, ac.signal),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n const transformed = transformResult(\n res.json,\n resolvedOpts.transformer.output,\n );\n\n if (!transformed.ok) {\n observer.error(\n TRPCClientError.from(transformed.error, {\n meta: res.meta,\n }),\n );\n return;\n }\n observer.next({\n context: res.meta,\n result: transformed.result,\n });\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,wBAAwB;CAC5B,MAAM,IAAI,MACR,yFACF;AACF;;;;;;AAOA,SAAgB,WACd,aACA;CACA,IAAI,eAAiD;CACrD,IAAI,gBAAsD;CAE1D,MAAM,oCAAoC;EACxC,aAAa,aAAoB;EACjC,gBAAgB;EAChB,eAAe;CACjB;;;;CAKA,SAAS,WAAW,OAAkC;EACpD,MAAM,eAA4C,CAAC,CAAC,CAAC;EACrD,IAAI,QAAQ;EACZ,OAAO,MA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IACX,QACG,MAAM,QAAQ;KACb,SAAS;KACT,OAAO;KACP,MAAM,cAAc,gBAClB,IAAI,MACJ,aAAa,YAAY,MAC3B;KAEA,IAAI,CAAC,YAAY,IAAI;MACnB,SAAS,MACP,gBAAgB,KAAK,YAAY,OAAO,EACtC,MAAM,IAAI,KACZ,CAAC,CACH;MACA;KACF;KACA,SAAS,KAAK;MACZ,SAAS,IAAI;MACb,QAAQ,YAAY;KACtB,CAAC;KACD,SAAS,SAAS;IACpB,CAAC,CAAC,CACD,OAAO,QAAQ;KACd,SAAS;KACT,SAAS,MACP,gBAAgB,KAAK,KAAK,EACxB,MAAA,SAAA,QAAA,SAAA,KAAA,IAAA,KAAA,IAAM,KAAM,KACd,CAAC,CACH;IACF,CAAC;IAEH,aAAa;KACX,IAAI,CAAC,QACH,GAAG,MAAM;IAEb;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"httpUtils-CB_100ND.mjs","names":[],"sources":["../src/getFetch.ts","../src/internals/signals.ts","../src/links/internals/httpUtils.ts"],"sourcesContent":["import type { FetchEsque, NativeFetchEsque } from './internals/types';\n\ntype AnyFn = (...args: any[]) => unknown;\n\nconst isFunction = (fn: unknown): fn is AnyFn => typeof fn === 'function';\n\nexport function getFetch(\n customFetchImpl?: FetchEsque | NativeFetchEsque,\n): FetchEsque {\n if (customFetchImpl) {\n return customFetchImpl as FetchEsque;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (typeof window !== 'undefined' && isFunction(window.fetch)) {\n return window.fetch.bind(window);\n }\n\n if (typeof globalThis !== 'undefined' && isFunction(globalThis.fetch)) {\n return globalThis.fetch;\n }\n\n throw new Error('No fetch implementation found');\n}\n","import type { Maybe } from '@trpc/server/unstable-core-do-not-import';\n\n/**\n * Like `Promise.all()` but for abort signals\n * - When all signals have been aborted, the merged signal will be aborted\n * - If one signal is `null`, no signal will be aborted\n */\nexport function allAbortSignals(...signals: Maybe<AbortSignal>[]): AbortSignal {\n const ac = new AbortController();\n\n const count = signals.length;\n\n let abortedCount = 0;\n\n const onAbort = () => {\n if (++abortedCount === count) {\n ac.abort();\n }\n };\n\n for (const signal of signals) {\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, {\n once: true,\n });\n }\n }\n\n return ac.signal;\n}\n\n/**\n * Like `Promise.race` but for abort signals\n *\n * Basically, a ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function raceAbortSignals(\n ...signals: Maybe<AbortSignal>[]\n): AbortSignal {\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal?.aborted) {\n ac.abort();\n } else {\n signal?.addEventListener('abort', () => ac.abort(), { once: true });\n }\n }\n\n return ac.signal;\n}\n\nexport function abortSignalToPromise(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n signal.addEventListener(\n 'abort',\n () => {\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n","import type {\n AnyClientTypes,\n CombinedDataTransformer,\n Maybe,\n ProcedureType,\n TRPCAcceptHeader,\n TRPCResponse,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { getFetch } from '../../getFetch';\nimport type {\n FetchEsque,\n RequestInitEsque,\n ResponseEsque,\n} from '../../internals/types';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { HTTPHeaders } from '../types';\n\n/**\n * @internal\n */\nexport type HTTPLinkBaseOptions<\n TRoot extends Pick<AnyClientTypes, 'transformer'>,\n> = {\n url: string | URL;\n /**\n * Add ponyfill for fetch\n */\n fetch?: FetchEsque;\n /**\n * Send all requests `as POST`s requests regardless of the procedure type\n * The HTTP handler must separately allow overriding the method. See:\n * @see https://trpc.io/docs/rpc\n */\n methodOverride?: 'POST';\n} & TransformerOptions<TRoot>;\n\nexport interface ResolvedHTTPLinkOptions {\n url: string;\n fetch?: FetchEsque;\n transformer: CombinedDataTransformer;\n methodOverride?: 'POST';\n}\n\nexport function resolveHTTPLinkOptions(\n opts: HTTPLinkBaseOptions<AnyClientTypes>,\n): ResolvedHTTPLinkOptions {\n return {\n url: opts.url.toString(),\n fetch: opts.fetch,\n transformer: getTransformer(opts.transformer),\n methodOverride: opts.methodOverride,\n };\n}\n\n// https://github.com/trpc/trpc/pull/669\nfunction arrayToDict(array: unknown[]) {\n const dict: Record<number, unknown> = {};\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n dict[index] = element;\n }\n return dict;\n}\n\nconst METHOD = {\n query: 'GET',\n mutation: 'POST',\n subscription: 'PATCH',\n} as const;\n\nexport interface HTTPResult {\n json: TRPCResponse;\n meta: {\n response: ResponseEsque;\n responseJSON?: unknown;\n };\n}\n\ntype GetInputOptions = {\n transformer: CombinedDataTransformer;\n} & ({ input: unknown } | { inputs: unknown[] });\n\nexport function getInput(opts: GetInputOptions) {\n return 'input' in opts\n ? opts.transformer.input.serialize(opts.input)\n : arrayToDict(\n opts.inputs.map((_input) => opts.transformer.input.serialize(_input)),\n );\n}\n\nexport type HTTPBaseRequestOptions = GetInputOptions &\n ResolvedHTTPLinkOptions & {\n type: ProcedureType;\n path: string;\n signal: Maybe<AbortSignal>;\n };\n\ntype GetUrl = (opts: HTTPBaseRequestOptions) => string;\ntype GetBody = (opts: HTTPBaseRequestOptions) => RequestInitEsque['body'];\n\nexport type ContentOptions = {\n trpcAcceptHeader?: TRPCAcceptHeader;\n trpcAcceptHeaderKey?: 'trpc-accept' | 'accept';\n contentTypeHeader?: string;\n getUrl: GetUrl;\n getBody: GetBody;\n};\n\nexport const getUrl: GetUrl = (opts) => {\n const parts = opts.url.split('?') as [string, string?];\n const base = parts[0].replace(/\\/$/, ''); // Remove any trailing slashes\n\n let url = base + '/' + opts.path;\n const queryParts: string[] = [];\n\n if (parts[1]) {\n queryParts.push(parts[1]);\n }\n if ('inputs' in opts) {\n queryParts.push('batch=1');\n }\n if (opts.type === 'query' || opts.type === 'subscription') {\n const input = getInput(opts);\n if (input !== undefined && opts.methodOverride !== 'POST') {\n queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);\n }\n }\n if (queryParts.length) {\n url += '?' + queryParts.join('&');\n }\n return url;\n};\n\nexport const getBody: GetBody = (opts) => {\n if (opts.type === 'query' && opts.methodOverride !== 'POST') {\n return undefined;\n }\n const input = getInput(opts);\n return input !== undefined ? JSON.stringify(input) : undefined;\n};\n\nexport type Requester = (\n opts: HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n },\n) => Promise<HTTPResult>;\n\nexport const jsonHttpRequester: Requester = (opts) => {\n return httpRequest({\n ...opts,\n contentTypeHeader: 'application/json',\n getUrl,\n getBody,\n });\n};\n\n/**\n * Polyfill for DOMException with AbortError name\n */\nclass AbortError extends Error {\n constructor() {\n const name = 'AbortError';\n super(name);\n this.name = name;\n this.message = name;\n }\n}\n\nexport type HTTPRequestOptions = ContentOptions &\n HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n };\n\n/**\n * Polyfill for `signal.throwIfAborted()`\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted\n */\nconst throwIfAborted = (signal: Maybe<AbortSignal>) => {\n if (!signal?.aborted) {\n return;\n }\n // If available, use the native implementation\n signal.throwIfAborted?.();\n\n // If we have `DOMException`, use it\n if (typeof DOMException !== 'undefined') {\n throw new DOMException('AbortError', 'AbortError');\n }\n\n // Otherwise, use our own implementation\n throw new AbortError();\n};\n\nexport async function fetchHTTPResponse(opts: HTTPRequestOptions) {\n throwIfAborted(opts.signal);\n\n const url = opts.getUrl(opts);\n const body = opts.getBody(opts);\n const method = opts.methodOverride ?? METHOD[opts.type];\n const resolvedHeaders = await (async () => {\n const heads = await opts.headers();\n if (Symbol.iterator in heads) {\n return Object.fromEntries(heads);\n }\n return heads;\n })();\n const headers = {\n ...(opts.contentTypeHeader && method !== 'GET'\n ? { 'content-type': opts.contentTypeHeader }\n : {}),\n ...(opts.trpcAcceptHeader\n ? { [opts.trpcAcceptHeaderKey ?? 'trpc-accept']: opts.trpcAcceptHeader }\n : undefined),\n ...resolvedHeaders,\n };\n\n return getFetch(opts.fetch)(url, {\n method,\n signal: opts.signal,\n body,\n headers,\n });\n}\n\nexport async function httpRequest(\n opts: HTTPRequestOptions,\n): Promise<HTTPResult> {\n const meta = {} as HTTPResult['meta'];\n\n const res = await fetchHTTPResponse(opts);\n meta.response = res;\n\n const json = await res.json();\n\n meta.responseJSON = json;\n\n return {\n json: json as TRPCResponse,\n meta,\n };\n}\n"],"mappings":";;;AAIA,MAAM,cAAc,OAA6B,OAAO,OAAO;AAE/D,SAAgB,SACd,iBACY;CACZ,IAAI,iBACF,OAAO;CAIT,IAAI,OAAO,WAAW,eAAe,WAAW,OAAO,KAAK,GAC1D,OAAO,OAAO,MAAM,KAAK,MAAM;CAGjC,IAAI,OAAO,eAAe,eAAe,WAAW,WAAW,KAAK,GAClE,OAAO,WAAW;CAGpB,MAAM,IAAI,MAAM,+BAA+B;AACjD;;;;;;;;AChBA,SAAgB,gBAAgB,GAAG,SAA4C;CAC7E,MAAM,KAAK,IAAI,gBAAgB;CAE/B,MAAM,QAAQ,QAAQ;CAEtB,IAAI,eAAe;CAEnB,MAAM,gBAAgB;EACpB,IAAI,EAAE,iBAAiB,OACrB,GAAG,MAAM;CAEb;CAEA,KAAK,MAAM,UAAU,SACnB,IAAA,WAAA,QAAA,WAAA,KAAA,IAAA,KAAA,IAAI,OAAQ,SACV,QAAQ;MAER,WAAA,QAAA,WAAA,KAAA,KAAA,OAAQ,iBAAiB,SAAS,SAAS,EACzC,MAAM,KACR,CAAC;CAIL,OAAO,GAAG;AACZ;;;;;;;AAQA,SAAgB,iBACd,GAAG,SACU;CACb,MAAM,KAAK,IAAI,gBAAgB;CAE/B,KAAK,MAAM,UAAU,SACnB,IAAA,WAAA,QAAA,W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