@trpc/server 11.22.2-canary.9.85bcf328a → 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/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- package/dist/ws-DJ2SSChC.mjs.map +0 -1
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# HTTP Subscription Link
|
|
2
|
+
|
|
3
|
+
> A terminating link for subscriptions over Server-sent Events
|
|
4
|
+
|
|
5
|
+
From https://trpc.io/docs/client/links/httpSubscriptionLink
|
|
6
|
+
|
|
7
|
+
`httpSubscriptionLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that uses [Server-sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (SSE) for subscriptions.
|
|
8
|
+
|
|
9
|
+
SSE is a good option for real-time as it's a bit easier than setting up a WebSockets-server.
|
|
10
|
+
|
|
11
|
+
## Setup
|
|
12
|
+
|
|
13
|
+
> [!NOTE] Info
|
|
14
|
+
> If your client's environment doesn't support EventSource, you need an [EventSource polyfill](https://www.npmjs.com/package/event-source-polyfill). For React Native specific instructions please defer to the [compatibility section](https://trpc.io/docs/client/links/httpSubscriptionLink#compatibility-react-native).
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
To use `httpSubscriptionLink`, you need to use a [splitLink](https://trpc.io/docs/client/links/splitLink) to make it explicit that we want to use SSE for subscriptions.
|
|
18
|
+
|
|
19
|
+
```ts no-check title="client/index.ts"
|
|
20
|
+
import {
|
|
21
|
+
createTRPCClient,
|
|
22
|
+
httpBatchLink,
|
|
23
|
+
httpSubscriptionLink,
|
|
24
|
+
loggerLink,
|
|
25
|
+
splitLink,
|
|
26
|
+
} from '@trpc/client';
|
|
27
|
+
import type { AppRouter } from './server';
|
|
28
|
+
|
|
29
|
+
const trpcClient = createTRPCClient<AppRouter>({
|
|
30
|
+
/**
|
|
31
|
+
* @see https://trpc.io/docs/v11/client/links
|
|
32
|
+
*/
|
|
33
|
+
links: [
|
|
34
|
+
// adds pretty logs to your console in development and logs errors in production
|
|
35
|
+
loggerLink(),
|
|
36
|
+
splitLink({
|
|
37
|
+
// uses the httpSubscriptionLink for subscriptions
|
|
38
|
+
condition: (op) => op.type === 'subscription',
|
|
39
|
+
true: httpSubscriptionLink({
|
|
40
|
+
url: `/api/trpc`,
|
|
41
|
+
}),
|
|
42
|
+
false: httpBatchLink({
|
|
43
|
+
url: `/api/trpc`,
|
|
44
|
+
}),
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
> [!TIP]
|
|
51
|
+
> The document here outlines the specific details of using `httpSubscriptionLink`. For general usage of subscriptions, see [our subscriptions guide](https://trpc.io/docs/server/subscriptions).
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
## Headers and authorization / authentication
|
|
55
|
+
|
|
56
|
+
### Web apps
|
|
57
|
+
|
|
58
|
+
#### Same domain
|
|
59
|
+
|
|
60
|
+
If you're doing a web application, cookies are sent as part of the request as long as your client is on the same domain as the server.
|
|
61
|
+
|
|
62
|
+
#### Cross-domain
|
|
63
|
+
|
|
64
|
+
If the client and server are not on the same domain, you can use `withCredentials: true` ([read more on MDN here](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/withCredentials)).
|
|
65
|
+
|
|
66
|
+
**Example:**
|
|
67
|
+
|
|
68
|
+
```tsx no-check
|
|
69
|
+
// [...]
|
|
70
|
+
httpSubscriptionLink({
|
|
71
|
+
url: 'https://example.com/api/trpc',
|
|
72
|
+
eventSourceOptions() {
|
|
73
|
+
return {
|
|
74
|
+
withCredentials: true, // <---
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Custom headers through ponyfill
|
|
81
|
+
|
|
82
|
+
**Recommended for non-web environments**
|
|
83
|
+
|
|
84
|
+
You can ponyfill `EventSource` and use the `eventSourceOptions` -callback to populate headers.
|
|
85
|
+
|
|
86
|
+
```tsx no-check
|
|
87
|
+
import {
|
|
88
|
+
createTRPCClient,
|
|
89
|
+
httpBatchLink,
|
|
90
|
+
httpSubscriptionLink,
|
|
91
|
+
splitLink,
|
|
92
|
+
} from '@trpc/client';
|
|
93
|
+
import { EventSourcePolyfill } from 'event-source-polyfill';
|
|
94
|
+
import type { AppRouter } from './server';
|
|
95
|
+
|
|
96
|
+
// Initialize the tRPC client
|
|
97
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
98
|
+
links: [
|
|
99
|
+
splitLink({
|
|
100
|
+
condition: (op) => op.type === 'subscription',
|
|
101
|
+
true: httpSubscriptionLink({
|
|
102
|
+
url: 'http://localhost:3000',
|
|
103
|
+
// ponyfill EventSource
|
|
104
|
+
EventSource: EventSourcePolyfill,
|
|
105
|
+
// options to pass to the EventSourcePolyfill constructor
|
|
106
|
+
eventSourceOptions: async ({ op }) => {
|
|
107
|
+
// ^ Includes the operation that's being executed
|
|
108
|
+
// you can use this to generate a signature for the operation
|
|
109
|
+
const signature = await getSignature(op);
|
|
110
|
+
return {
|
|
111
|
+
headers: {
|
|
112
|
+
authorization: 'Bearer supersecret',
|
|
113
|
+
'x-signature': signature,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
},
|
|
117
|
+
}),
|
|
118
|
+
false: httpBatchLink({
|
|
119
|
+
url: 'http://localhost:3000',
|
|
120
|
+
}),
|
|
121
|
+
}),
|
|
122
|
+
],
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Updating configuration on an active connection
|
|
127
|
+
|
|
128
|
+
`httpSubscriptionLink` leverages SSE through `EventSource`, ensuring that connections encountering errors like network failures or bad response codes are automatically retried. However, `EventSource` does not allow re-execution of the `eventSourceOptions()` or `url()` options to update its configuration, which is particularly important in scenarios where authentication has expired since the last connection.
|
|
129
|
+
|
|
130
|
+
To address this limitation, you can use a [`retryLink`](https://trpc.io/docs/client/links/retryLink) in conjunction with `httpSubscriptionLink`. This approach ensures that the connection is re-established with the latest configuration, including any updated authentication details.
|
|
131
|
+
|
|
132
|
+
> [!WARNING] Caution
|
|
133
|
+
> Please note that restarting the connection will result in the `EventSource` being recreated from scratch, which means any previously tracked events will be lost.
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
```tsx no-check
|
|
137
|
+
import {
|
|
138
|
+
createTRPCClient,
|
|
139
|
+
httpBatchLink,
|
|
140
|
+
httpSubscriptionLink,
|
|
141
|
+
retryLink,
|
|
142
|
+
splitLink,
|
|
143
|
+
} from '@trpc/client';
|
|
144
|
+
import {
|
|
145
|
+
EventSourcePolyfill,
|
|
146
|
+
EventSourcePolyfillInit,
|
|
147
|
+
} from 'event-source-polyfill';
|
|
148
|
+
import type { AppRouter } from './server';
|
|
149
|
+
|
|
150
|
+
// Initialize the tRPC client
|
|
151
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
152
|
+
links: [
|
|
153
|
+
splitLink({
|
|
154
|
+
condition: (op) => op.type === 'subscription',
|
|
155
|
+
false: httpBatchLink({
|
|
156
|
+
url: 'http://localhost:3000',
|
|
157
|
+
}),
|
|
158
|
+
true: [
|
|
159
|
+
retryLink({
|
|
160
|
+
retry: (opts) => {
|
|
161
|
+
opts.op.type;
|
|
162
|
+
const code = opts.error.data?.code;
|
|
163
|
+
if (!code) {
|
|
164
|
+
// This shouldn't happen as our httpSubscriptionLink will automatically retry within when there's a non-parsable response
|
|
165
|
+
console.error('No error code found, retrying', opts);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
if (code === 'UNAUTHORIZED' || code === 'FORBIDDEN') {
|
|
169
|
+
console.log('Retrying due to 401/403 error');
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
},
|
|
174
|
+
}),
|
|
175
|
+
httpSubscriptionLink({
|
|
176
|
+
url: async () => {
|
|
177
|
+
// calculate the latest URL if needed...
|
|
178
|
+
return getAuthenticatedUri();
|
|
179
|
+
},
|
|
180
|
+
// ponyfill EventSource
|
|
181
|
+
EventSource: EventSourcePolyfill,
|
|
182
|
+
eventSourceOptions: async () => {
|
|
183
|
+
// ...or maybe renew an access token
|
|
184
|
+
const token = await auth.getOrRenewToken();
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
headers: {
|
|
188
|
+
authorization: `Bearer ${token}`,
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
}),
|
|
193
|
+
],
|
|
194
|
+
}),
|
|
195
|
+
],
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Connection params
|
|
200
|
+
|
|
201
|
+
In order to authenticate with `EventSource`, you can define `connectionParams` in `httpSubscriptionLink`. This will be sent as part of the URL, which is why other methods are preferred.
|
|
202
|
+
|
|
203
|
+
```ts no-check title="server/context.ts"
|
|
204
|
+
import type { CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
|
|
205
|
+
|
|
206
|
+
export const createContext = async (opts: CreateHTTPContextOptions) => {
|
|
207
|
+
const token = opts.info.connectionParams?.token;
|
|
208
|
+
|
|
209
|
+
// [... authenticate]
|
|
210
|
+
|
|
211
|
+
return {};
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
export type Context = Awaited<ReturnType<typeof createContext>>;
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
```ts no-check title="client/trpc.ts"
|
|
218
|
+
import {
|
|
219
|
+
createTRPCClient,
|
|
220
|
+
httpBatchLink,
|
|
221
|
+
httpSubscriptionLink,
|
|
222
|
+
splitLink,
|
|
223
|
+
} from '@trpc/client';
|
|
224
|
+
import type { AppRouter } from './server';
|
|
225
|
+
|
|
226
|
+
// Initialize the tRPC client
|
|
227
|
+
const trpc = createTRPCClient<AppRouter>({
|
|
228
|
+
links: [
|
|
229
|
+
splitLink({
|
|
230
|
+
condition: (op) => op.type === 'subscription',
|
|
231
|
+
true: httpSubscriptionLink({
|
|
232
|
+
url: 'http://localhost:3000',
|
|
233
|
+
connectionParams: async () => {
|
|
234
|
+
// Will be serialized as part of the URL
|
|
235
|
+
return {
|
|
236
|
+
token: 'supersecret',
|
|
237
|
+
};
|
|
238
|
+
},
|
|
239
|
+
}),
|
|
240
|
+
false: httpBatchLink({
|
|
241
|
+
url: 'http://localhost:3000',
|
|
242
|
+
}),
|
|
243
|
+
}),
|
|
244
|
+
],
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## Timeout Configuration
|
|
249
|
+
|
|
250
|
+
The `httpSubscriptionLink` supports configuring a timeout for inactivity through the `reconnectAfterInactivityMs` option. If no messages (including ping messages) are received within the specified timeout period, the connection will be marked as "connecting" and automatically attempt to reconnect.
|
|
251
|
+
|
|
252
|
+
The timeout configuration is set on the server side when initializing tRPC:
|
|
253
|
+
|
|
254
|
+
```ts no-check title="server/trpc.ts"
|
|
255
|
+
import { initTRPC } from '@trpc/server';
|
|
256
|
+
|
|
257
|
+
export const t = initTRPC.create({
|
|
258
|
+
sse: {
|
|
259
|
+
client: {
|
|
260
|
+
reconnectAfterInactivityMs: 3_000,
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## Server Ping Configuration
|
|
267
|
+
|
|
268
|
+
The server can be configured to send periodic ping messages to keep the connection alive and prevent timeout disconnections. This is particularly useful when combined with the `reconnectAfterInactivityMs`-option.
|
|
269
|
+
|
|
270
|
+
```ts no-check title="server/trpc.ts"
|
|
271
|
+
import { initTRPC } from '@trpc/server';
|
|
272
|
+
|
|
273
|
+
export const t = initTRPC.create({
|
|
274
|
+
sse: {
|
|
275
|
+
// Maximum duration of a single SSE connection in milliseconds
|
|
276
|
+
// maxDurationMs: 60_000,
|
|
277
|
+
ping: {
|
|
278
|
+
// Enable periodic ping messages to keep connection alive
|
|
279
|
+
enabled: true,
|
|
280
|
+
// Send ping message every 2s
|
|
281
|
+
intervalMs: 2_000,
|
|
282
|
+
},
|
|
283
|
+
// client: {
|
|
284
|
+
// reconnectAfterInactivityMs: 3_000
|
|
285
|
+
// }
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Compatibility (React Native)
|
|
291
|
+
|
|
292
|
+
The `httpSubscriptionLink` makes use of the `EventSource` API, Streams API, and `AsyncIterator`s, these are not natively supported by React Native and will have to be ponyfilled.
|
|
293
|
+
|
|
294
|
+
To ponyfill `EventSource` we recommend to use a polyfill that utilizes the networking library exposed by React Native, over using a polyfill that uses the `XMLHttpRequest` API. Libraries that polyfill `EventSource` using `XMLHttpRequest` fail to reconnect after the app has been in the background. Consider using the [rn-eventsource-reborn](https://www.npmjs.com/package/rn-eventsource-reborn) package.
|
|
295
|
+
|
|
296
|
+
The Streams API can be ponyfilled using the [web-streams-polyfill](https://www.npmjs.com/package/web-streams-polyfill) package.
|
|
297
|
+
|
|
298
|
+
`AsyncIterator`s can be polyfilled using the [@azure/core-asynciterator-polyfill](https://www.npmjs.com/package/@azure/core-asynciterator-polyfill) package.
|
|
299
|
+
|
|
300
|
+
### Installation
|
|
301
|
+
|
|
302
|
+
Install the required polyfills:
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
npm install rn-eventsource-reborn web-streams-polyfill @azure/core-asynciterator-polyfill
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Add the polyfills to your project before the link is used (e.g. where you add your TRPCReact.Provider):
|
|
309
|
+
|
|
310
|
+
```ts no-check title="utils/api.tsx"
|
|
311
|
+
import '@azure/core-asynciterator-polyfill';
|
|
312
|
+
import { RNEventSource } from 'rn-eventsource-reborn';
|
|
313
|
+
import { ReadableStream, TransformStream } from 'web-streams-polyfill';
|
|
314
|
+
|
|
315
|
+
globalThis.ReadableStream = globalThis.ReadableStream || ReadableStream;
|
|
316
|
+
globalThis.TransformStream = globalThis.TransformStream || TransformStream;
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Once the ponyfills are added, you can continue setting up the `httpSubscriptionLink` as described in the [setup](https://trpc.io/docs/client/links/httpSubscriptionLink#setup) section.
|
|
320
|
+
|
|
321
|
+
## `httpSubscriptionLink` Options
|
|
322
|
+
|
|
323
|
+
```ts no-check
|
|
324
|
+
type HTTPSubscriptionLinkOptions<
|
|
325
|
+
TRoot extends AnyClientTypes,
|
|
326
|
+
TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,
|
|
327
|
+
> = {
|
|
328
|
+
/**
|
|
329
|
+
* The URL to connect to (can be a function that returns a URL)
|
|
330
|
+
*/
|
|
331
|
+
url: string | (() => string | Promise<string>);
|
|
332
|
+
/**
|
|
333
|
+
* Connection params that are available in `createContext()`
|
|
334
|
+
* Serialized as part of the URL under the `connectionParams` query parameter
|
|
335
|
+
*/
|
|
336
|
+
connectionParams?:
|
|
337
|
+
| Record<string, string>
|
|
338
|
+
| null
|
|
339
|
+
| (() =>
|
|
340
|
+
| Record<string, string>
|
|
341
|
+
| null
|
|
342
|
+
| Promise<Record<string, string> | null>);
|
|
343
|
+
/**
|
|
344
|
+
* Data transformer
|
|
345
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
346
|
+
*/
|
|
347
|
+
transformer?: DataTransformerOptions;
|
|
348
|
+
/**
|
|
349
|
+
* EventSource ponyfill
|
|
350
|
+
*/
|
|
351
|
+
EventSource?: TEventSource;
|
|
352
|
+
/**
|
|
353
|
+
* EventSource options or a callback that returns them
|
|
354
|
+
*/
|
|
355
|
+
eventSourceOptions?:
|
|
356
|
+
| EventSourceLike.InitDictOf<TEventSource>
|
|
357
|
+
| ((opts: {
|
|
358
|
+
op: Operation;
|
|
359
|
+
}) =>
|
|
360
|
+
| EventSourceLike.InitDictOf<TEventSource>
|
|
361
|
+
| Promise<EventSourceLike.InitDictOf<TEventSource>>);
|
|
362
|
+
};
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
## SSE Options on the server
|
|
366
|
+
|
|
367
|
+
```ts no-check
|
|
368
|
+
export interface SSEStreamProducerOptions<TValue = unknown> {
|
|
369
|
+
ping?: {
|
|
370
|
+
/**
|
|
371
|
+
* Enable ping comments sent from the server
|
|
372
|
+
* @default false
|
|
373
|
+
*/
|
|
374
|
+
enabled: boolean;
|
|
375
|
+
/**
|
|
376
|
+
* Interval in milliseconds
|
|
377
|
+
* @default 1000
|
|
378
|
+
*/
|
|
379
|
+
intervalMs?: number;
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* Maximum duration in milliseconds for the request before ending the stream
|
|
383
|
+
* @default undefined
|
|
384
|
+
*/
|
|
385
|
+
maxDurationMs?: number;
|
|
386
|
+
/**
|
|
387
|
+
* End the request immediately after data is sent
|
|
388
|
+
* Only useful for serverless runtimes that do not support streaming responses
|
|
389
|
+
* @default false
|
|
390
|
+
*/
|
|
391
|
+
emitAndEndImmediately?: boolean;
|
|
392
|
+
/**
|
|
393
|
+
* Client-specific options - these will be sent to the client as part of the first message
|
|
394
|
+
* @default {}
|
|
395
|
+
*/
|
|
396
|
+
client?: {
|
|
397
|
+
/**
|
|
398
|
+
* Timeout and reconnect after inactivity in milliseconds
|
|
399
|
+
* @default undefined
|
|
400
|
+
*/
|
|
401
|
+
reconnectAfterInactivityMs?: number;
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
```
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# WebSocket Link
|
|
2
|
+
|
|
3
|
+
> A terminating link that sends tRPC operations over a WebSocket
|
|
4
|
+
|
|
5
|
+
From https://trpc.io/docs/client/links/wsLink
|
|
6
|
+
|
|
7
|
+
`wsLink` is a [**terminating link**](https://trpc.io/docs/client/links#the-terminating-link) that's used when using tRPC's WebSockets Client and Subscriptions, which you can learn more about [here](https://trpc.io/docs/server/subscriptions).
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
To use `wsLink`, you need to pass it a `TRPCWebSocketClient`, which you can create with `createWSClient`:
|
|
12
|
+
|
|
13
|
+
```ts no-check title="client/index.ts"
|
|
14
|
+
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';
|
|
15
|
+
import type { AppRouter } from './server';
|
|
16
|
+
|
|
17
|
+
const wsClient = createWSClient({
|
|
18
|
+
url: 'ws://localhost:3000',
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const trpcClient = createTRPCClient<AppRouter>({
|
|
22
|
+
links: [wsLink<AppRouter>({ client: wsClient })],
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Authentication / Connection params
|
|
27
|
+
|
|
28
|
+
[See more here](https://trpc.io/docs/server/websockets#connection-params)
|
|
29
|
+
|
|
30
|
+
## `wsLink` / `createWSClient` Options
|
|
31
|
+
|
|
32
|
+
The `wsLink` function requires a `TRPCWebSocketClient` to be passed, which can be configured with the fields defined in `WebSocketClientOptions`:
|
|
33
|
+
|
|
34
|
+
```ts no-check
|
|
35
|
+
export interface WebSocketLinkOptions {
|
|
36
|
+
client: TRPCWebSocketClient;
|
|
37
|
+
/**
|
|
38
|
+
* Data transformer
|
|
39
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
40
|
+
**/
|
|
41
|
+
transformer?: DataTransformerOptions;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
declare function createWSClient(opts: WebSocketClientOptions): TRPCWebSocketClient;
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
export interface WebSocketClientOptions {
|
|
48
|
+
/**
|
|
49
|
+
* The URL to connect to (can be a function that returns a URL)
|
|
50
|
+
*/
|
|
51
|
+
url: string | (() => MaybePromise<string>);
|
|
52
|
+
/**
|
|
53
|
+
* Connection params that are available in `createContext()`
|
|
54
|
+
* These are sent as the first message
|
|
55
|
+
*/
|
|
56
|
+
connectionParams?: Record<string, string> | null | (() => MaybePromise<Record<string, string> | null>);
|
|
57
|
+
/**
|
|
58
|
+
* Ponyfill which WebSocket implementation to use
|
|
59
|
+
*/
|
|
60
|
+
WebSocket?: typeof WebSocket;
|
|
61
|
+
/**
|
|
62
|
+
* The number of milliseconds before a reconnect is attempted.
|
|
63
|
+
* @default {@link exponentialBackoff}
|
|
64
|
+
*/
|
|
65
|
+
retryDelayMs?: typeof exponentialBackoff;
|
|
66
|
+
/**
|
|
67
|
+
* Triggered when a WebSocket connection is established
|
|
68
|
+
*/
|
|
69
|
+
onOpen?: () => void;
|
|
70
|
+
/**
|
|
71
|
+
* Triggered when a WebSocket connection encounters an error
|
|
72
|
+
*/
|
|
73
|
+
onError?: (evt?: Event) => void;
|
|
74
|
+
/**
|
|
75
|
+
* Triggered when a WebSocket connection is closed
|
|
76
|
+
*/
|
|
77
|
+
onClose?: (cause?: { code?: number }) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)
|
|
80
|
+
*/
|
|
81
|
+
lazy?: {
|
|
82
|
+
/**
|
|
83
|
+
* Enable lazy mode
|
|
84
|
+
* @default false
|
|
85
|
+
*/
|
|
86
|
+
enabled: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Close the WebSocket after this many milliseconds
|
|
89
|
+
* @default 0
|
|
90
|
+
*/
|
|
91
|
+
closeMs: number;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Send ping messages to the server and kill the connection if no pong message is returned
|
|
95
|
+
*/
|
|
96
|
+
keepAlive?: {
|
|
97
|
+
/**
|
|
98
|
+
* @default false
|
|
99
|
+
*/
|
|
100
|
+
enabled: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Send a ping message every this many milliseconds
|
|
103
|
+
* @default 5_000
|
|
104
|
+
*/
|
|
105
|
+
intervalMs?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Close the WebSocket after this many milliseconds if the server does not respond
|
|
108
|
+
* @default 1_000
|
|
109
|
+
*/
|
|
110
|
+
pongTimeoutMs?: number;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Custom encoder for wire encoding (e.g. custom binary formats)
|
|
114
|
+
* @default jsonEncoder
|
|
115
|
+
*/
|
|
116
|
+
experimental_encoder?: Encoder;
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Reference
|
|
121
|
+
|
|
122
|
+
You can check out the source code for this link on [GitHub.](https://github.com/trpc/trpc/blob/main/packages/client/src/links/wsLink)
|