@orpc/client 2.0.0-beta.47 → 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 +6 -7
- package/dist/adapters/fetch/index.d.ts +2 -48
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/rpc-link.d.ts +14 -0
- package/dist/adapters/fetch/rpc-link.js +14 -0
- package/dist/adapters/fetch/transport.d.ts +34 -0
- package/dist/adapters/fetch/transport.js +65 -0
- package/dist/adapters/message-port/index.d.ts +3 -80
- package/dist/adapters/message-port/index.js +3 -0
- package/dist/adapters/message-port/message-port.d.ts +29 -0
- package/dist/adapters/message-port/message-port.js +56 -0
- package/dist/adapters/message-port/rpc-link.d.ts +15 -0
- package/dist/adapters/message-port/rpc-link.js +15 -0
- package/dist/adapters/message-port/transport.d.ts +38 -0
- package/dist/adapters/message-port/transport.js +52 -0
- package/dist/adapters/standard/codec.d.ts +14 -0
- package/dist/adapters/standard/codec.js +1 -0
- package/dist/adapters/standard/index.d.ts +5 -60
- package/dist/adapters/standard/index.js +4 -0
- package/dist/adapters/standard/link.d.ts +40 -0
- package/dist/adapters/standard/link.js +85 -0
- package/dist/adapters/standard/plugin.d.ts +32 -0
- package/dist/adapters/standard/plugin.js +16 -0
- package/dist/adapters/standard/{index.d.mts → rpc-link-codec.d.ts} +17 -14
- package/dist/adapters/standard/rpc-link-codec.js +104 -0
- package/dist/adapters/standard/transport.d.ts +14 -0
- package/dist/adapters/standard/transport.js +1 -0
- package/dist/adapters/websocket/index.d.ts +2 -136
- package/dist/adapters/websocket/index.js +2 -0
- package/dist/adapters/websocket/rpc-link.d.ts +14 -0
- package/dist/adapters/websocket/rpc-link.js +14 -0
- package/dist/adapters/websocket/{index.d.mts → transport.d.ts} +32 -53
- package/dist/adapters/websocket/transport.js +133 -0
- package/dist/async-iterator-object.d.ts +2 -0
- package/dist/async-iterator-object.js +29 -0
- package/dist/client-safe.d.ts +18 -0
- package/dist/client-safe.js +36 -0
- package/dist/client.d.ts +40 -0
- package/dist/client.js +39 -0
- package/dist/consts.d.ts +10 -0
- package/dist/consts.js +43 -0
- package/dist/dynamic-link.d.ts +13 -0
- package/dist/dynamic-link.js +17 -0
- package/dist/error-utils.d.ts +21 -0
- package/dist/error-utils.js +58 -0
- package/dist/error.d.ts +132 -0
- package/dist/error.js +178 -0
- package/dist/index.d.ts +38 -129
- package/dist/index.js +40 -0
- package/dist/plugins/batch.d.ts +185 -0
- package/dist/plugins/batch.js +401 -0
- package/dist/plugins/cookie-jar.d.ts +82 -0
- package/dist/plugins/cookie-jar.js +268 -0
- package/dist/plugins/dedupe.d.ts +64 -0
- package/dist/plugins/dedupe.js +226 -0
- package/dist/plugins/index.d.ts +20 -412
- package/dist/plugins/index.js +23 -0
- package/dist/plugins/request-compression.d.ts +44 -0
- package/dist/plugins/request-compression.js +178 -0
- package/dist/plugins/response-compression.d.ts +28 -0
- package/dist/plugins/response-compression.js +91 -0
- package/dist/plugins/retry-after.d.ts +50 -0
- package/dist/plugins/retry-after.js +88 -0
- package/dist/plugins/retry.d.ts +84 -0
- package/dist/plugins/retry.js +140 -0
- package/dist/plugins/timeout.d.ts +25 -0
- package/dist/plugins/timeout.js +37 -0
- package/dist/{shared/client.DqIWeNhQ.d.mts → rpc-json-serializer.d.ts} +9 -41
- package/dist/rpc-json-serializer.js +392 -0
- package/dist/rpc-serializer.d.ts +32 -0
- package/dist/rpc-serializer.js +130 -0
- package/dist/types.d.ts +97 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +47 -0
- package/dist/utils.js +51 -0
- package/package.json +43 -45
- package/dist/adapters/fetch/index.d.mts +0 -48
- package/dist/adapters/fetch/index.mjs +0 -77
- package/dist/adapters/message-port/index.d.mts +0 -80
- package/dist/adapters/message-port/index.mjs +0 -101
- package/dist/adapters/standard/index.mjs +0 -6
- package/dist/adapters/websocket/index.mjs +0 -131
- package/dist/index.d.mts +0 -144
- package/dist/index.mjs +0 -147
- package/dist/plugins/index.d.mts +0 -420
- package/dist/plugins/index.mjs +0 -971
- package/dist/shared/client.BoHJeq15.d.mts +0 -233
- package/dist/shared/client.BoHJeq15.d.ts +0 -233
- package/dist/shared/client.CKQeJJ2U.mjs +0 -172
- package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
- package/dist/shared/client.JBJwBhR8.d.ts +0 -90
- package/dist/shared/client.LF04eOvL.mjs +0 -115
- package/dist/shared/client._wG5INmC.mjs +0 -505
- package/dist/shared/client.euYjjcFz.d.mts +0 -90
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { captureAsyncContext, defer, isAsyncIteratorObject, loadBytes, once, promiseWithResolvers, safeEncodeURIComponent, splitInHalf, stringifyJSON, toArray, value, } from '@orpc/shared';
|
|
2
|
+
import { parseStandardUrl } from '@standard-server/core';
|
|
3
|
+
import { ClientPeer, decodePeerMessage, isPeerMessage, isServerPeerSendMessage, } from '@standard-server/peer';
|
|
4
|
+
/**
|
|
5
|
+
* Header that marks a request as a batch, set by the Batch Link Plugin and detected by the Batch Handler Plugin.
|
|
6
|
+
* Nothing between the client and server, such as a CORS policy or proxy, should block or strip it.
|
|
7
|
+
*
|
|
8
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#setup | Batch Plugin - Setup}
|
|
9
|
+
*/
|
|
10
|
+
export const BATCH_HEADER = 'orpc-batch';
|
|
11
|
+
/**
|
|
12
|
+
* Default `maxSize` of both the Batch Link Plugin and the Batch Handler Plugin.
|
|
13
|
+
*
|
|
14
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_BATCH_MAX_SIZE = 10;
|
|
17
|
+
/**
|
|
18
|
+
* Combines multiple client requests into a single batch request
|
|
19
|
+
* and splits the batch response back into individual responses.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* **Note**: HTTP/2 and later already multiplex requests over a single connection, so this plugin is often less useful than it once was.
|
|
23
|
+
*
|
|
24
|
+
* @see {@link https://orpc.dev/docs/plugins/batch | Batch Plugin}
|
|
25
|
+
*/
|
|
26
|
+
export class BatchLinkPlugin {
|
|
27
|
+
name = '~batch';
|
|
28
|
+
groups;
|
|
29
|
+
filter;
|
|
30
|
+
scope;
|
|
31
|
+
maxSize;
|
|
32
|
+
wait;
|
|
33
|
+
mode;
|
|
34
|
+
batchUrl;
|
|
35
|
+
maxUrlLength;
|
|
36
|
+
batchHeaders;
|
|
37
|
+
mapSubrequest;
|
|
38
|
+
mapSubresponse;
|
|
39
|
+
queue = new Map();
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.groups = options.groups;
|
|
42
|
+
this.filter = options.filter ?? (() => true);
|
|
43
|
+
this.scope = options.scope ?? (() => undefined);
|
|
44
|
+
this.maxSize = options.maxSize ?? DEFAULT_BATCH_MAX_SIZE;
|
|
45
|
+
this.wait = options.wait ?? 0;
|
|
46
|
+
this.mode = options.mode ?? 'buffered';
|
|
47
|
+
this.batchUrl =
|
|
48
|
+
options.url ??
|
|
49
|
+
((options) => {
|
|
50
|
+
const [pathname] = parseStandardUrl(options[0].request.url);
|
|
51
|
+
return `${pathname}/__batch__`;
|
|
52
|
+
});
|
|
53
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
54
|
+
this.batchHeaders =
|
|
55
|
+
options.headers ??
|
|
56
|
+
(async (options) => {
|
|
57
|
+
const headersList = options.map((o) => o.request.headers);
|
|
58
|
+
const commonHeaders = {};
|
|
59
|
+
for (const headers of headersList) {
|
|
60
|
+
for (const key of Object.keys(headers)) {
|
|
61
|
+
const value = headers[key];
|
|
62
|
+
if (headersList.every((h) => h[key] === value)) {
|
|
63
|
+
commonHeaders[key] = value;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return commonHeaders;
|
|
68
|
+
});
|
|
69
|
+
this.mapSubrequest =
|
|
70
|
+
options.mapSubrequest ??
|
|
71
|
+
(({ request }, { headers }) => {
|
|
72
|
+
const subHeaders = { ...request.headers };
|
|
73
|
+
for (const key of Object.keys(headers)) {
|
|
74
|
+
const value = headers[key];
|
|
75
|
+
if (subHeaders[key] === value) {
|
|
76
|
+
subHeaders[key] = undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
...request,
|
|
81
|
+
headers: subHeaders,
|
|
82
|
+
};
|
|
83
|
+
});
|
|
84
|
+
this.mapSubresponse =
|
|
85
|
+
options.mapSubresponse ??
|
|
86
|
+
((subResponse, batchResponse) => {
|
|
87
|
+
return {
|
|
88
|
+
...subResponse,
|
|
89
|
+
headers: {
|
|
90
|
+
...batchResponse.headers, // low-priority
|
|
91
|
+
...subResponse.headers,
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
init(options) {
|
|
97
|
+
const transportInterceptor = async (interceptorOptions) => {
|
|
98
|
+
const { body, signal } = interceptorOptions.request;
|
|
99
|
+
if (body instanceof Blob ||
|
|
100
|
+
body instanceof FormData ||
|
|
101
|
+
body instanceof ReadableStream ||
|
|
102
|
+
isAsyncIteratorObject(body) ||
|
|
103
|
+
signal?.aborted ||
|
|
104
|
+
!value(this.filter, interceptorOptions)) {
|
|
105
|
+
return interceptorOptions.next();
|
|
106
|
+
}
|
|
107
|
+
const group = this.groups.find((group) => value(group.condition, interceptorOptions));
|
|
108
|
+
if (!group) {
|
|
109
|
+
return interceptorOptions.next();
|
|
110
|
+
}
|
|
111
|
+
const scope = this.scope(interceptorOptions);
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
// Schedule only for the first queued request, so later ones cannot extend or split the wait.
|
|
114
|
+
if (!this.queue.size) {
|
|
115
|
+
defer(() => this.processPendingBatches(), this.wait);
|
|
116
|
+
}
|
|
117
|
+
let groups = this.queue.get(scope);
|
|
118
|
+
if (!groups) {
|
|
119
|
+
groups = new Map();
|
|
120
|
+
this.queue.set(scope, groups);
|
|
121
|
+
}
|
|
122
|
+
let queue = groups.get(group);
|
|
123
|
+
if (!queue) {
|
|
124
|
+
queue = [];
|
|
125
|
+
groups.set(group, queue);
|
|
126
|
+
}
|
|
127
|
+
queue.push([interceptorOptions, resolve, reject, captureAsyncContext()]);
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
...options,
|
|
132
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
processPendingBatches() {
|
|
136
|
+
const pending = [...this.queue.values()];
|
|
137
|
+
this.queue.clear();
|
|
138
|
+
for (const groups of pending) {
|
|
139
|
+
for (const [group, items] of groups) {
|
|
140
|
+
const getItems = items.filter(([options]) => options.request.method === 'GET');
|
|
141
|
+
const queryItems = items.filter(([options]) => options.request.method === 'QUERY');
|
|
142
|
+
const unsafeItems = items.filter(([options]) => options.request.method !== 'GET' && options.request.method !== 'QUERY');
|
|
143
|
+
void this.executeBatchInOwnContext('GET', group, getItems);
|
|
144
|
+
void this.executeBatchInOwnContext('QUERY', group, queryItems);
|
|
145
|
+
void this.executeBatchInOwnContext('POST', group, unsafeItems);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Runs the batch in the async context of its first request instead of the timer's,
|
|
151
|
+
* so the transport and batch options see that caller's request state.
|
|
152
|
+
* `executeBatch` always runs in the context of its first request.
|
|
153
|
+
*/
|
|
154
|
+
async executeBatchInOwnContext(method, group, groupItems) {
|
|
155
|
+
await groupItems[0]?.[3](() => this.executeBatch(method, group, groupItems));
|
|
156
|
+
}
|
|
157
|
+
async executeBatch(method, group, groupItems) {
|
|
158
|
+
try {
|
|
159
|
+
if (groupItems.length === 1) {
|
|
160
|
+
const [options, resolve, reject] = groupItems[0];
|
|
161
|
+
options.next().then(resolve).catch(reject);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const subOptionsList = groupItems.map(([options]) => options);
|
|
165
|
+
const maxSize = await value(this.maxSize, subOptionsList);
|
|
166
|
+
if (groupItems.length > maxSize) {
|
|
167
|
+
const [first, second] = splitInHalf(groupItems);
|
|
168
|
+
await Promise.all([
|
|
169
|
+
this.executeBatch(method, group, first),
|
|
170
|
+
this.executeBatchInOwnContext(method, group, second),
|
|
171
|
+
]);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const url = await value(this.batchUrl, subOptionsList);
|
|
175
|
+
const headers = await value(this.batchHeaders, subOptionsList);
|
|
176
|
+
const mode = await value(this.mode, subOptionsList);
|
|
177
|
+
let suppressErrorFromCurrentBatch = false;
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const pendingMessages = [];
|
|
180
|
+
const subrequests = groupItems.map(([subOptions]) => this.mapSubrequest(subOptions, { url, headers }));
|
|
181
|
+
let batchResponse;
|
|
182
|
+
let markRequestSent;
|
|
183
|
+
const openRequestIds = new Set();
|
|
184
|
+
const cancelledRunningRequestIds = new Set();
|
|
185
|
+
let isBatchSent = false;
|
|
186
|
+
const abortIfOnlyCancelledRemain = () => {
|
|
187
|
+
if (openRequestIds.size === 0 && cancelledRunningRequestIds.size > 0) {
|
|
188
|
+
controller.abort();
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
const peer = new ClientPeer(async (message) => {
|
|
192
|
+
pendingMessages.push(message);
|
|
193
|
+
if (message.kind === 'request') {
|
|
194
|
+
openRequestIds.add(message.id);
|
|
195
|
+
markRequestSent?.();
|
|
196
|
+
}
|
|
197
|
+
else if (message.kind === 'cancel' && openRequestIds.delete(message.id) && isBatchSent) {
|
|
198
|
+
cancelledRunningRequestIds.add(message.id);
|
|
199
|
+
abortIfOnlyCancelledRemain();
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
/**
|
|
203
|
+
* Subrequests go to the peer one at a time, so a request message always belongs to the current one.
|
|
204
|
+
* A subrequest aborted before the peer starts sending its request message sends nothing, not even a
|
|
205
|
+
* cancel, so settling also ends the wait for it.
|
|
206
|
+
*/
|
|
207
|
+
for (const [index, [subOptions, resolve, reject]] of groupItems.entries()) {
|
|
208
|
+
const sent = promiseWithResolvers();
|
|
209
|
+
markRequestSent = sent.resolve;
|
|
210
|
+
void peer
|
|
211
|
+
.request(subrequests[index])
|
|
212
|
+
.then((subResponse) => resolve(this.mapSubresponse(subResponse, batchResponse, subOptions)))
|
|
213
|
+
.catch((error) => {
|
|
214
|
+
if (!suppressErrorFromCurrentBatch) {
|
|
215
|
+
reject(error);
|
|
216
|
+
}
|
|
217
|
+
})
|
|
218
|
+
.then(sent.resolve);
|
|
219
|
+
await sent.promise;
|
|
220
|
+
}
|
|
221
|
+
if (openRequestIds.size === 0) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
isBatchSent = true;
|
|
225
|
+
/**
|
|
226
|
+
* Leave out subrequests aborted before the batch is sent: the server counts their request and cancel
|
|
227
|
+
* against its batch size limit and would still run calls the client already rejected.
|
|
228
|
+
*/
|
|
229
|
+
const outgoingMessages = pendingMessages.filter((message) => openRequestIds.has(message.id));
|
|
230
|
+
try {
|
|
231
|
+
const request = {
|
|
232
|
+
url,
|
|
233
|
+
method,
|
|
234
|
+
headers: { ...headers, [BATCH_HEADER]: mode },
|
|
235
|
+
signal: controller.signal,
|
|
236
|
+
};
|
|
237
|
+
if (method === 'GET') {
|
|
238
|
+
const [pathname, search, hash] = parseStandardUrl(url);
|
|
239
|
+
const dataParam = `data=${safeEncodeURIComponent(stringifyJSON(outgoingMessages))}`;
|
|
240
|
+
const newUrl = search
|
|
241
|
+
? `${pathname}${search}&${dataParam}${hash ?? ''}`
|
|
242
|
+
: `${pathname}?${dataParam}${hash ?? ''}`;
|
|
243
|
+
const maxUrlLength = await value(this.maxUrlLength, subOptionsList);
|
|
244
|
+
if (newUrl.length > maxUrlLength) {
|
|
245
|
+
const [first, second] = splitInHalf(groupItems);
|
|
246
|
+
suppressErrorFromCurrentBatch = true;
|
|
247
|
+
await Promise.all([
|
|
248
|
+
this.executeBatch(method, group, first),
|
|
249
|
+
this.executeBatchInOwnContext(method, group, second),
|
|
250
|
+
peer.close(),
|
|
251
|
+
]);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
request.url = newUrl;
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
request.body = outgoingMessages;
|
|
258
|
+
}
|
|
259
|
+
batchResponse = await groupItems[0][0].next({
|
|
260
|
+
...subOptionsList[0],
|
|
261
|
+
context: value(group.context, subOptionsList),
|
|
262
|
+
path: value(group.path, subOptionsList) ?? [],
|
|
263
|
+
request,
|
|
264
|
+
signal: controller.signal,
|
|
265
|
+
});
|
|
266
|
+
/**
|
|
267
|
+
* An error response is not a batch response, so forward it as-is to every subrequest
|
|
268
|
+
* instead of failing to parse it.
|
|
269
|
+
*/
|
|
270
|
+
if (batchResponse.status >= 400) {
|
|
271
|
+
const resolveBody = once(() => batchResponse.resolveBody());
|
|
272
|
+
const errorResponse = { ...batchResponse, resolveBody };
|
|
273
|
+
groupItems.forEach(([subOptions, resolve]) => {
|
|
274
|
+
resolve(this.mapSubresponse(errorResponse, batchResponse, subOptions));
|
|
275
|
+
});
|
|
276
|
+
suppressErrorFromCurrentBatch = true;
|
|
277
|
+
await peer.close();
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const body = await batchResponse.resolveBody();
|
|
281
|
+
if (Array.isArray(body) &&
|
|
282
|
+
body.every((v) => isPeerMessage(v) && isServerPeerSendMessage(v))) {
|
|
283
|
+
for (const message of body) {
|
|
284
|
+
await peer.message(message);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
else if (body instanceof Blob) {
|
|
288
|
+
await decodeLengthPrefixedBlob(body, peer);
|
|
289
|
+
}
|
|
290
|
+
else if (body instanceof ReadableStream) {
|
|
291
|
+
await decodeLengthPrefixedStream(body, async (message) => {
|
|
292
|
+
await peer.message(message);
|
|
293
|
+
if (isLastServerMessage(message)) {
|
|
294
|
+
openRequestIds.delete(message.id);
|
|
295
|
+
cancelledRunningRequestIds.delete(message.id);
|
|
296
|
+
abortIfOnlyCancelledRemain();
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
else {
|
|
301
|
+
throw new TypeError('Invalid batch response format.');
|
|
302
|
+
}
|
|
303
|
+
await peer.close(new TypeError('Batch response is incomplete.'));
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
await peer.close(error);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
groupItems.forEach(([, , reject]) => reject(error));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Whether the server sends nothing more for the subrequest after this message.
|
|
316
|
+
*/
|
|
317
|
+
function isLastServerMessage(message) {
|
|
318
|
+
switch (message.kind) {
|
|
319
|
+
case 'response':
|
|
320
|
+
// A body-less response with a content type or body hint is followed by stream messages
|
|
321
|
+
return (message.json.body !== undefined ||
|
|
322
|
+
message.binary !== undefined ||
|
|
323
|
+
(message.json.headers?.['content-type'] === undefined &&
|
|
324
|
+
message.json.headers?.['standard-server'] === undefined));
|
|
325
|
+
case 'event-stream':
|
|
326
|
+
return message.json.event === 'close' || message.json.event === 'error';
|
|
327
|
+
case 'octet-stream':
|
|
328
|
+
return message.json.close === true;
|
|
329
|
+
case 'cancel':
|
|
330
|
+
return true;
|
|
331
|
+
default:
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
async function decodeLengthPrefixedBlob(blob, peer) {
|
|
336
|
+
const buffer = await loadBytes(blob);
|
|
337
|
+
let offset = 0;
|
|
338
|
+
while (offset < buffer.length) {
|
|
339
|
+
if (offset + 4 > buffer.length) {
|
|
340
|
+
throw new TypeError('Invalid batch response: incomplete length header.');
|
|
341
|
+
}
|
|
342
|
+
const view = new DataView(buffer.buffer, buffer.byteOffset + offset, 4);
|
|
343
|
+
const length = view.getUint32(0, false);
|
|
344
|
+
offset += 4;
|
|
345
|
+
if (offset + length > buffer.length) {
|
|
346
|
+
throw new TypeError('Invalid batch response: incomplete message.');
|
|
347
|
+
}
|
|
348
|
+
const messageBytes = buffer.subarray(offset, offset + length);
|
|
349
|
+
offset += length;
|
|
350
|
+
const result = decodePeerMessage(messageBytes);
|
|
351
|
+
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
352
|
+
throw new TypeError('Invalid batch response: invalid message.');
|
|
353
|
+
}
|
|
354
|
+
await peer.message(result.message);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function decodeLengthPrefixedStream(stream, receive) {
|
|
358
|
+
const reader = stream.getReader();
|
|
359
|
+
let buffer = new Uint8Array(0);
|
|
360
|
+
try {
|
|
361
|
+
while (true) {
|
|
362
|
+
const { done, value: chunk } = await reader.read();
|
|
363
|
+
if (chunk) {
|
|
364
|
+
const newBuffer = new Uint8Array(buffer.length + chunk.length);
|
|
365
|
+
newBuffer.set(buffer);
|
|
366
|
+
newBuffer.set(chunk, buffer.length);
|
|
367
|
+
buffer = newBuffer;
|
|
368
|
+
}
|
|
369
|
+
while (buffer.length >= 4) {
|
|
370
|
+
const view = new DataView(buffer.buffer, buffer.byteOffset, 4);
|
|
371
|
+
const length = view.getUint32(0, false);
|
|
372
|
+
// Zero-length frame is a keep-alive ping; skip it.
|
|
373
|
+
if (length === 0) {
|
|
374
|
+
buffer = buffer.subarray(4);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (buffer.length < 4 + length) {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
const messageBytes = buffer.subarray(4, 4 + length);
|
|
381
|
+
buffer = buffer.subarray(4 + length);
|
|
382
|
+
const result = decodePeerMessage(messageBytes);
|
|
383
|
+
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
384
|
+
throw new TypeError('Invalid batch response: invalid message.');
|
|
385
|
+
}
|
|
386
|
+
await receive(result.message);
|
|
387
|
+
}
|
|
388
|
+
if (done) {
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
// Free the response body so the server stops streaming to a reader that is gone
|
|
395
|
+
reader.cancel(error).catch(() => { });
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
finally {
|
|
399
|
+
reader.releaseLock();
|
|
400
|
+
}
|
|
401
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Value } from '@orpc/shared';
|
|
2
|
+
import type { FetchLinkTransportOptions } from '../adapters/fetch/index.ts';
|
|
3
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
|
|
4
|
+
import type { ClientContext } from '../types.ts';
|
|
5
|
+
export interface CookieJarLinkPluginOptions<T extends ClientContext> {
|
|
6
|
+
/**
|
|
7
|
+
* The link's `origin`, used to match cookies by host and scheme.
|
|
8
|
+
* The plugin does nothing when it resolves to `undefined` or a relative origin, as in a browser.
|
|
9
|
+
*
|
|
10
|
+
* @example 'https://api.example.com'
|
|
11
|
+
*/
|
|
12
|
+
origin: FetchLinkTransportOptions<T>['origin'];
|
|
13
|
+
/**
|
|
14
|
+
* Where cookies are stored. Pass a function to pick a jar per request, e.g. from the client context.
|
|
15
|
+
*
|
|
16
|
+
* @default a new `CookieJar` per plugin
|
|
17
|
+
*/
|
|
18
|
+
jar?: Value<CookieJar, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Stores the cookies servers set and sends them back on later requests, like a browser,
|
|
22
|
+
* for server-side rendering, scripts, and tests.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* **Warning**: On a server, do not share one link between users: create a client per request, or pick a jar per request.
|
|
26
|
+
*
|
|
27
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar | Cookie Jar Plugin}
|
|
28
|
+
*/
|
|
29
|
+
export declare class CookieJarLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
30
|
+
private readonly origin;
|
|
31
|
+
private readonly jar;
|
|
32
|
+
name: string;
|
|
33
|
+
/**
|
|
34
|
+
* Runs per call, before batching, so each call gets the cookies it would get on its own.
|
|
35
|
+
*/
|
|
36
|
+
before: string[];
|
|
37
|
+
constructor(options: NoInfer<CookieJarLinkPluginOptions<T>>);
|
|
38
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
39
|
+
}
|
|
40
|
+
export interface StoredCookie {
|
|
41
|
+
name: string;
|
|
42
|
+
value: string;
|
|
43
|
+
/**
|
|
44
|
+
* The `Domain` attribute, or else the host that set the cookie.
|
|
45
|
+
*/
|
|
46
|
+
domain: string;
|
|
47
|
+
/**
|
|
48
|
+
* True when the cookie has no `Domain` attribute, so it is sent to `domain` only, not its subdomains.
|
|
49
|
+
*/
|
|
50
|
+
hostOnly: boolean;
|
|
51
|
+
path: string;
|
|
52
|
+
secure: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Expiry time in milliseconds since the Unix epoch, `undefined` for a session cookie that lives as long as the jar.
|
|
55
|
+
*/
|
|
56
|
+
expires: number | undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* An in-memory cookie store that follows the browser rules of [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).
|
|
60
|
+
*
|
|
61
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar#custom-jar | Cookie Jar Plugin - Custom Jar}
|
|
62
|
+
*/
|
|
63
|
+
export declare class CookieJar {
|
|
64
|
+
/**
|
|
65
|
+
* Keyed by domain, path, and name. Map order is creation order: replacing a cookie keeps its position.
|
|
66
|
+
*/
|
|
67
|
+
private readonly cookies;
|
|
68
|
+
/**
|
|
69
|
+
* Stores a `Set-Cookie` header value received from `url`.
|
|
70
|
+
* Cookies a browser would reject are ignored, and an expired cookie deletes the one it replaces.
|
|
71
|
+
*/
|
|
72
|
+
setCookie(setCookie: string, url: string): void;
|
|
73
|
+
/**
|
|
74
|
+
* Returns the cookies a browser would send to `url`, longer paths first, then oldest first.
|
|
75
|
+
* Without `url`, returns every stored cookie that has not expired.
|
|
76
|
+
*/
|
|
77
|
+
getCookies(url?: string): StoredCookie[];
|
|
78
|
+
/**
|
|
79
|
+
* Removes every stored cookie.
|
|
80
|
+
*/
|
|
81
|
+
clear(): void;
|
|
82
|
+
}
|