@trpc/client 10.0.0-alpha.28 → 10.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/createTRPCClient.d.ts +5 -1
  2. package/dist/createTRPCClient.d.ts.map +1 -1
  3. package/dist/index.js +49 -40
  4. package/dist/index.mjs +49 -40
  5. package/dist/internals/TRPCClient.d.ts +3 -5
  6. package/dist/internals/TRPCClient.d.ts.map +1 -1
  7. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.d.ts +1 -0
  8. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.dev.js +280 -0
  9. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.js +7 -0
  10. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.cjs.prod.js +280 -0
  11. package/links/httpBatchLink/dist/trpc-client-links-httpBatchLink.esm.js +272 -0
  12. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.d.ts +1 -0
  13. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.dev.js +134 -0
  14. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.js +7 -0
  15. package/links/httpLink/dist/trpc-client-links-httpLink.cjs.prod.js +134 -0
  16. package/links/httpLink/dist/trpc-client-links-httpLink.esm.js +126 -0
  17. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.d.ts +1 -0
  18. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.dev.js +89 -0
  19. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.js +7 -0
  20. package/links/loggerLink/dist/trpc-client-links-loggerLink.cjs.prod.js +89 -0
  21. package/links/loggerLink/dist/trpc-client-links-loggerLink.esm.js +85 -0
  22. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.d.ts +1 -0
  23. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.dev.js +19 -0
  24. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.js +7 -0
  25. package/links/splitLink/dist/trpc-client-links-splitLink.cjs.prod.js +19 -0
  26. package/links/splitLink/dist/trpc-client-links-splitLink.esm.js +15 -0
  27. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.d.ts +1 -0
  28. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.dev.js +397 -0
  29. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.js +7 -0
  30. package/links/wsLink/dist/trpc-client-links-wsLink.cjs.prod.js +397 -0
  31. package/links/wsLink/dist/trpc-client-links-wsLink.esm.js +392 -0
  32. package/package.json +4 -4
  33. package/src/createTRPCClient.ts +56 -1
  34. package/src/internals/TRPCClient.ts +0 -17
@@ -0,0 +1,392 @@
1
+ import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
2
+ import _createClass from '@babel/runtime/helpers/esm/createClass';
3
+ import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
4
+ import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';
5
+ import _inherits from '@babel/runtime/helpers/esm/inherits';
6
+ import _createSuper from '@babel/runtime/helpers/esm/createSuper';
7
+ import _wrapNativeSuper from '@babel/runtime/helpers/esm/wrapNativeSuper';
8
+ import { T as TRPCClientError } from '../../../dist/TRPCClientError-09b8a26b.esm.js';
9
+
10
+ /* istanbul ignore next */
11
+ var retryDelay = function retryDelay(attemptIndex) {
12
+ return attemptIndex === 0 ? 0 : Math.min(1000 * Math.pow(2, attemptIndex), 30000);
13
+ };
14
+
15
+ function createWSClient(opts) {
16
+ var url = opts.url,
17
+ _opts$WebSocket = opts.WebSocket,
18
+ WebSocketImpl = _opts$WebSocket === void 0 ? WebSocket : _opts$WebSocket,
19
+ _opts$retryDelayMs = opts.retryDelayMs,
20
+ retryDelayFn = _opts$retryDelayMs === void 0 ? retryDelay : _opts$retryDelayMs;
21
+ /* istanbul ignore next */
22
+
23
+ if (!WebSocketImpl) {
24
+ throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
25
+ }
26
+ /**
27
+ * outgoing messages buffer whilst not open
28
+ */
29
+
30
+
31
+ var outgoing = [];
32
+ /**
33
+ * pending outgoing requests that are awaiting callback
34
+ */
35
+
36
+ var pendingRequests = Object.create(null);
37
+ var connectAttempt = 0;
38
+ var dispatchTimer = null;
39
+ var connectTimer = null;
40
+ var activeConnection = createWS();
41
+ var state = 'connecting';
42
+ /**
43
+ * tries to send the list of messages
44
+ */
45
+
46
+ function dispatch() {
47
+ if (state !== 'open' || dispatchTimer) {
48
+ return;
49
+ }
50
+
51
+ dispatchTimer = setTimeout(function () {
52
+ dispatchTimer = null;
53
+
54
+ if (outgoing.length === 1) {
55
+ // single send
56
+ activeConnection.send(JSON.stringify(outgoing.pop()));
57
+ } else {
58
+ // batch send
59
+ activeConnection.send(JSON.stringify(outgoing));
60
+ } // clear
61
+
62
+
63
+ outgoing = [];
64
+ });
65
+ }
66
+
67
+ function tryReconnect() {
68
+ if (connectTimer || state === 'closed') {
69
+ return;
70
+ }
71
+
72
+ var timeout = retryDelayFn(connectAttempt++);
73
+ reconnectInMs(timeout);
74
+ }
75
+
76
+ function reconnect() {
77
+ state = 'connecting';
78
+ var oldConnection = activeConnection;
79
+ activeConnection = createWS();
80
+ closeIfNoPending(oldConnection);
81
+ }
82
+
83
+ function reconnectInMs(ms) {
84
+ if (connectTimer) {
85
+ return;
86
+ }
87
+
88
+ state = 'connecting';
89
+ connectTimer = setTimeout(reconnect, ms);
90
+ }
91
+
92
+ function closeIfNoPending(conn) {
93
+ // disconnect as soon as there are are no pending result
94
+ var hasPendingRequests = Object.values(pendingRequests).some(function (p) {
95
+ return p.ws === conn;
96
+ });
97
+
98
+ if (!hasPendingRequests) {
99
+ conn.close();
100
+ }
101
+ }
102
+
103
+ function resumeSubscriptionOnReconnect(req) {
104
+ if (outgoing.some(function (r) {
105
+ return r.id === req.op.id;
106
+ })) {
107
+ return;
108
+ }
109
+
110
+ request(req.op, req.callbacks);
111
+ }
112
+
113
+ function createWS() {
114
+ var conn = new WebSocketImpl(url);
115
+ clearTimeout(connectTimer);
116
+ connectTimer = null;
117
+ conn.addEventListener('open', function () {
118
+ /* istanbul ignore next */
119
+ if (conn !== activeConnection) {
120
+ return;
121
+ }
122
+
123
+ connectAttempt = 0;
124
+ state = 'open';
125
+ dispatch();
126
+ });
127
+ conn.addEventListener('error', function () {
128
+ if (conn === activeConnection) {
129
+ tryReconnect();
130
+ }
131
+ });
132
+
133
+ var handleIncomingRequest = function handleIncomingRequest(req) {
134
+ if (req.method === 'reconnect' && conn === activeConnection) {
135
+ reconnect(); // notify subscribers
136
+
137
+ for (var _i = 0, _Object$values = Object.values(pendingRequests); _i < _Object$values.length; _i++) {
138
+ var pendingReq = _Object$values[_i];
139
+
140
+ if (pendingReq.type === 'subscription') {
141
+ resumeSubscriptionOnReconnect(pendingReq);
142
+ }
143
+ }
144
+ }
145
+ };
146
+
147
+ var handleIncomingResponse = function handleIncomingResponse(res) {
148
+ var _req$callbacks$onNext, _req$callbacks2;
149
+
150
+ var req = res.id !== null && pendingRequests[res.id];
151
+
152
+ if (!req) {
153
+ // do something?
154
+ return;
155
+ }
156
+
157
+ if ('error' in res) {
158
+ var _req$callbacks$onErro, _req$callbacks;
159
+
160
+ (_req$callbacks$onErro = (_req$callbacks = req.callbacks).onError) === null || _req$callbacks$onErro === void 0 ? void 0 : _req$callbacks$onErro.call(_req$callbacks, res);
161
+ return;
162
+ }
163
+
164
+ (_req$callbacks$onNext = (_req$callbacks2 = req.callbacks).onNext) === null || _req$callbacks$onNext === void 0 ? void 0 : _req$callbacks$onNext.call(_req$callbacks2, res.result);
165
+
166
+ if (req.ws !== activeConnection && conn === activeConnection) {
167
+ var oldWs = req.ws; // gracefully replace old connection with this
168
+
169
+ req.ws = activeConnection;
170
+ closeIfNoPending(oldWs);
171
+ }
172
+
173
+ if (res.result.type === 'stopped' && conn === activeConnection) {
174
+ var _req$callbacks$onDone, _req$callbacks3;
175
+
176
+ (_req$callbacks$onDone = (_req$callbacks3 = req.callbacks).onDone) === null || _req$callbacks$onDone === void 0 ? void 0 : _req$callbacks$onDone.call(_req$callbacks3);
177
+ }
178
+ };
179
+
180
+ conn.addEventListener('message', function (_ref) {
181
+ var data = _ref.data;
182
+ var msg = JSON.parse(data);
183
+
184
+ if ('method' in msg) {
185
+ handleIncomingRequest(msg);
186
+ } else {
187
+ handleIncomingResponse(msg);
188
+ }
189
+
190
+ if (conn !== activeConnection || state === 'closed') {
191
+ // when receiving a message, we close old connection that has no pending requests
192
+ closeIfNoPending(conn);
193
+ }
194
+ });
195
+ conn.addEventListener('close', function () {
196
+ if (activeConnection === conn) {
197
+ // connection might have been replaced already
198
+ tryReconnect();
199
+ }
200
+
201
+ for (var key in pendingRequests) {
202
+ var _req$callbacks$onErro2, _req$callbacks4;
203
+
204
+ var req = pendingRequests[key];
205
+
206
+ if (req.ws !== conn) {
207
+ continue;
208
+ }
209
+
210
+ (_req$callbacks$onErro2 = (_req$callbacks4 = req.callbacks).onError) === null || _req$callbacks$onErro2 === void 0 ? void 0 : _req$callbacks$onErro2.call(_req$callbacks4, TRPCClientError.from(new TRPCWebSocketClosedError('WebSocket closed prematurely')));
211
+
212
+ if (req.type !== 'subscription') {
213
+ var _req$callbacks$onDone2, _req$callbacks5;
214
+
215
+ delete pendingRequests[key];
216
+ (_req$callbacks$onDone2 = (_req$callbacks5 = req.callbacks).onDone) === null || _req$callbacks$onDone2 === void 0 ? void 0 : _req$callbacks$onDone2.call(_req$callbacks5);
217
+ } else if (state !== 'closed') {
218
+ // request restart of sub with next connection
219
+ resumeSubscriptionOnReconnect(req);
220
+ }
221
+ }
222
+ });
223
+ return conn;
224
+ }
225
+
226
+ function request(op, callbacks) {
227
+ var type = op.type,
228
+ input = op.input,
229
+ path = op.path,
230
+ id = op.id;
231
+ var envelope = {
232
+ id: id,
233
+ jsonrpc: '2.0',
234
+ method: type,
235
+ params: {
236
+ input: input,
237
+ path: path
238
+ }
239
+ };
240
+ pendingRequests[id] = {
241
+ ws: activeConnection,
242
+ type: type,
243
+ callbacks: callbacks,
244
+ op: op
245
+ }; // enqueue message
246
+
247
+ outgoing.push(envelope);
248
+ dispatch();
249
+ return function () {
250
+ var _pendingRequests$id, _callbacks$onDone;
251
+
252
+ var callbacks = (_pendingRequests$id = pendingRequests[id]) === null || _pendingRequests$id === void 0 ? void 0 : _pendingRequests$id.callbacks;
253
+ delete pendingRequests[id];
254
+ outgoing = outgoing.filter(function (msg) {
255
+ return msg.id !== id;
256
+ });
257
+ callbacks === null || callbacks === void 0 ? void 0 : (_callbacks$onDone = callbacks.onDone) === null || _callbacks$onDone === void 0 ? void 0 : _callbacks$onDone.call(callbacks);
258
+
259
+ if (op.type === 'subscription') {
260
+ outgoing.push({
261
+ id: id,
262
+ method: 'subscription.stop',
263
+ params: undefined
264
+ });
265
+ dispatch();
266
+ }
267
+ };
268
+ }
269
+
270
+ return {
271
+ close: function close() {
272
+ state = 'closed';
273
+ closeIfNoPending(activeConnection);
274
+ clearTimeout(connectTimer);
275
+ connectTimer = null;
276
+ },
277
+ request: request,
278
+ getConnection: function getConnection() {
279
+ return activeConnection;
280
+ }
281
+ };
282
+ }
283
+
284
+ var TRPCWebSocketClosedError = /*#__PURE__*/function (_Error) {
285
+ _inherits(TRPCWebSocketClosedError, _Error);
286
+
287
+ var _super = /*#__PURE__*/_createSuper(TRPCWebSocketClosedError);
288
+
289
+ function TRPCWebSocketClosedError(message) {
290
+ var _this;
291
+
292
+ _classCallCheck(this, TRPCWebSocketClosedError);
293
+
294
+ _this = _super.call(this, message);
295
+ _this.name = 'TRPCWebSocketClosedError';
296
+ Object.setPrototypeOf(_assertThisInitialized(_this), TRPCWebSocketClosedError.prototype);
297
+ return _this;
298
+ }
299
+
300
+ return _createClass(TRPCWebSocketClosedError);
301
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
302
+
303
+ var TRPCSubscriptionEndedError = /*#__PURE__*/function (_Error2) {
304
+ _inherits(TRPCSubscriptionEndedError, _Error2);
305
+
306
+ var _super2 = /*#__PURE__*/_createSuper(TRPCSubscriptionEndedError);
307
+
308
+ function TRPCSubscriptionEndedError(message) {
309
+ var _this2;
310
+
311
+ _classCallCheck(this, TRPCSubscriptionEndedError);
312
+
313
+ _this2 = _super2.call(this, message);
314
+ _this2.name = 'TRPCSubscriptionEndedError';
315
+ Object.setPrototypeOf(_assertThisInitialized(_this2), TRPCSubscriptionEndedError.prototype);
316
+ return _this2;
317
+ }
318
+
319
+ return _createClass(TRPCSubscriptionEndedError);
320
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
321
+
322
+ function wsLink(opts) {
323
+ // initialized config
324
+ return function (rt) {
325
+ var client = opts.client;
326
+ return function (_ref2) {
327
+ var op = _ref2.op,
328
+ prev = _ref2.prev,
329
+ onDestroy = _ref2.onDestroy;
330
+ var type = op.type,
331
+ rawInput = op.input,
332
+ path = op.path,
333
+ id = op.id;
334
+ var input = rt.transformer.serialize(rawInput);
335
+ var isDone = false;
336
+ var unsub = client.request({
337
+ type: type,
338
+ path: path,
339
+ input: input,
340
+ id: id
341
+ }, {
342
+ onNext: function onNext(result) {
343
+ if (isDone) {
344
+ return;
345
+ }
346
+
347
+ if ('data' in result) {
348
+ var data = rt.transformer.deserialize(result.data);
349
+ prev({
350
+ type: 'data',
351
+ data: data
352
+ });
353
+ } else {
354
+ prev(result);
355
+ }
356
+
357
+ if (op.type !== 'subscription') {
358
+ // if it isn't a subscription we don't care about next response
359
+ isDone = true;
360
+ unsub();
361
+ }
362
+ },
363
+ onError: function onError(err) {
364
+ if (isDone) {
365
+ return;
366
+ }
367
+
368
+ prev(err instanceof Error ? err : TRPCClientError.from(_objectSpread(_objectSpread({}, err), {}, {
369
+ error: rt.transformer.deserialize(err.error)
370
+ })));
371
+ },
372
+ onDone: function onDone() {
373
+ if (isDone) {
374
+ return;
375
+ }
376
+
377
+ var result = new TRPCSubscriptionEndedError('Operation ended prematurely');
378
+ prev(TRPCClientError.from(result, {
379
+ isDone: true
380
+ }));
381
+ isDone = true;
382
+ }
383
+ });
384
+ onDestroy(function () {
385
+ isDone = true;
386
+ unsub();
387
+ });
388
+ };
389
+ };
390
+ }
391
+
392
+ export { createWSClient, wsLink };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trpc/client",
3
- "version": "10.0.0-alpha.28",
3
+ "version": "10.0.0-alpha.30",
4
4
  "description": "tRPC Client lib",
5
5
  "author": "KATT",
6
6
  "license": "MIT",
@@ -67,13 +67,13 @@
67
67
  "@babel/runtime": "^7.9.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@trpc/server": "10.0.0-alpha.28"
70
+ "@trpc/server": "10.0.0-alpha.30"
71
71
  },
72
72
  "devDependencies": {
73
- "@trpc/server": "10.0.0-alpha.28"
73
+ "@trpc/server": "10.0.0-alpha.30"
74
74
  },
75
75
  "publishConfig": {
76
76
  "access": "public"
77
77
  },
78
- "gitHead": "9252bd0df8523fc90b56bdd4228b8662ad507198"
78
+ "gitHead": "31e28de6c0469b28a6f39378f931f35e469f17f4"
79
79
  }
@@ -1,3 +1,5 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
+
1
3
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
4
  import type { AnyRouter } from '@trpc/server';
3
5
  import {
@@ -5,12 +7,65 @@ import {
5
7
  CreateTRPCClientOptions,
6
8
  } from './internals/TRPCClient';
7
9
 
10
+ export type EnsureRecord<T> = T extends Record<string, any>
11
+ ? T
12
+ : Record<string, never>;
13
+
14
+ type FlattenRouter<TRouter extends AnyRouter> = {
15
+ [Key in keyof TRouter['_def']['procedures']]: TRouter['_def']['procedures'][Key] extends AnyRouter
16
+ ? FlattenRouter<TRouter['_def']['procedures'][Key]>
17
+ : TRouter['_def']['procedures'][Key];
18
+ };
19
+
20
+ function makeProxy<TRouter extends AnyRouter>(
21
+ client: Client<TRouter>,
22
+ ...path: string[]
23
+ ) {
24
+ const proxy: any = new Proxy(
25
+ function () {
26
+ // noop
27
+ },
28
+ {
29
+ get(_obj, name) {
30
+ if (name in client && !path.length) {
31
+ return client[name as keyof typeof client];
32
+ }
33
+ if (typeof name === 'string') {
34
+ return makeProxy(client, ...path, name);
35
+ }
36
+
37
+ return client;
38
+ },
39
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
40
+ apply(_1, _2, args) {
41
+ const pathCopy = [...path];
42
+ let type = pathCopy.pop()!;
43
+ if (type === 'mutate') {
44
+ type = 'mutation';
45
+ }
46
+ const fullPath = pathCopy.join('.');
47
+
48
+ if (type.startsWith('use')) {
49
+ throw new Error(`Invalid hook call`);
50
+ }
51
+
52
+ return (client as any)[type](fullPath, ...args);
53
+ },
54
+ },
55
+ );
56
+
57
+ return proxy as typeof client & FlattenRouter<TRouter>;
58
+ }
8
59
  export function createTRPCClient<TRouter extends AnyRouter>(
9
60
  opts: CreateTRPCClientOptions<TRouter>,
10
61
  ) {
11
- return new Client<TRouter>(opts);
62
+ const client = new Client<TRouter>(opts);
63
+ // Here we need to wrap the client in a Proxy to be able to call deep objects and translate them to `client.query`-calls
64
+ return makeProxy(client);
12
65
  }
13
66
 
67
+ // Also the client created above needs to somehow be like `TRPCClient<Router> & Omit<Router, 'createCaller' | 'createProcedure' | '_def' | 'transformer' | 'errorFormatter' | 'getErrorShape>`
68
+
14
69
  export type {
15
70
  TRPCRequestOptions,
16
71
  CreateTRPCClientOptions,
@@ -61,14 +61,6 @@ interface CreateTRPCClientBaseOptions {
61
61
  transformer?: ClientDataTransformerOptions;
62
62
  }
63
63
 
64
- function createRouterProxy(callback: (...args: [string, ...unknown[]]) => any) {
65
- return new Proxy({} as any, {
66
- get(_, path: string) {
67
- return (...args: unknown[]) => callback(path, ...args);
68
- },
69
- });
70
- }
71
-
72
64
  /** @internal */
73
65
  export interface CreateTRPCClientWithURLOptions
74
66
  extends CreateTRPCClientBaseOptions {
@@ -102,8 +94,6 @@ export type CreateTRPCClientOptions<TRouter extends AnyRouter> =
102
94
  export class TRPCClient<TRouter extends AnyRouter> {
103
95
  private readonly links: OperationLink<TRouter>[];
104
96
  public readonly runtime: TRPCClientRuntime;
105
- public readonly queries: TRouter['queries'];
106
- public readonly mutations: TRouter['mutations'];
107
97
 
108
98
  constructor(opts: CreateTRPCClientOptions<TRouter>) {
109
99
  const _fetch = getFetch(opts?.fetch);
@@ -145,13 +135,6 @@ export class TRPCClient<TRouter extends AnyRouter> {
145
135
  })(this.runtime),
146
136
  ];
147
137
  }
148
-
149
- this.queries = createRouterProxy((path, ...args) =>
150
- this.query(path, ...(args as any)),
151
- );
152
- this.mutations = createRouterProxy((path, ...args) =>
153
- this.mutation(path, ...(args as any)),
154
- );
155
138
  }
156
139
 
157
140
  private $request<TInput = unknown, TOutput = unknown>({