/
common.ts
459 lines (411 loc) · 11.6 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
*
* common
*
*/
import { GraphQLError } from 'graphql';
import { areGraphQLErrors, extendedTypeof, isObject } from './utils';
/**
* The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](/PROTOCOL.md).
*
* @category Common
*/
export const GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws';
/**
* The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws).
*
* @private
*/
export const DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws';
/**
* `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](/PROTOCOL.md).
*
* @category Common
*/
export enum CloseCode {
InternalServerError = 4500,
InternalClientError = 4005,
BadRequest = 4400,
BadResponse = 4004,
/** Tried subscribing before connect ack */
Unauthorized = 4401,
Forbidden = 4403,
SubprotocolNotAcceptable = 4406,
ConnectionInitialisationTimeout = 4408,
ConnectionAcknowledgementTimeout = 4504,
/** Subscriber distinction is very important */
SubscriberAlreadyExists = 4409,
TooManyInitialisationRequests = 4429,
}
/**
* ID is a string type alias representing
* the globally unique ID used for identifying
* subscriptions established by the client.
*
* @category Common
*/
export type ID = string;
/** @category Common */
export interface Disposable {
/** Dispose of the instance and clear up resources. */
dispose: () => void | Promise<void>;
}
/**
* A representation of any set of values over any amount of time.
*
* @category Common
*/
export interface Sink<T = unknown> {
/** Next value arriving. */
next(value: T): void;
/**
* An error that has occured. Calling this function "closes" the sink.
* Besides the errors being `Error` and `readonly GraphQLError[]`, it
* can also be a `CloseEvent`, but to avoid bundling DOM typings because
* the client can run in Node env too, you should assert the close event
* type during implementation.
*/
error(error: unknown): void;
/** The sink has completed. This function "closes" the sink. */
complete(): void;
}
/**
* Types of messages allowed to be sent by the client/server over the WS protocol.
*
* @category Common
*/
export enum MessageType {
ConnectionInit = 'connection_init', // Client -> Server
ConnectionAck = 'connection_ack', // Server -> Client
Ping = 'ping', // bidirectional
Pong = 'pong', /// bidirectional
Subscribe = 'subscribe', // Client -> Server
Next = 'next', // Server -> Client
Error = 'error', // Server -> Client
Complete = 'complete', // bidirectional
}
/** @category Common */
export interface ConnectionInitMessage {
readonly type: MessageType.ConnectionInit;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface ConnectionAckMessage {
readonly type: MessageType.ConnectionAck;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface PingMessage {
readonly type: MessageType.Ping;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface PongMessage {
readonly type: MessageType.Pong;
readonly payload?: Record<string, unknown>;
}
/** @category Common */
export interface SubscribeMessage {
readonly id: ID;
readonly type: MessageType.Subscribe;
readonly payload: SubscribePayload;
}
/** @category Common */
export interface SubscribePayload {
readonly operationName?: string | null;
readonly query: string;
readonly variables?: Record<string, unknown> | null;
readonly extensions?: Record<string, unknown> | null;
}
/** @category Common */
export interface ExecutionResult<
Data = Record<string, unknown>,
Extensions = Record<string, unknown>,
> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
hasNext?: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface ExecutionPatchResult<
Data = unknown,
Extensions = Record<string, unknown>,
> {
errors?: ReadonlyArray<GraphQLError>;
data?: Data | null;
path?: ReadonlyArray<string | number>;
label?: string;
hasNext: boolean;
extensions?: Extensions;
}
/** @category Common */
export interface NextMessage {
readonly id: ID;
readonly type: MessageType.Next;
readonly payload: ExecutionResult | ExecutionPatchResult;
}
/** @category Common */
export interface ErrorMessage {
readonly id: ID;
readonly type: MessageType.Error;
readonly payload: readonly GraphQLError[];
}
/** @category Common */
export interface CompleteMessage {
readonly id: ID;
readonly type: MessageType.Complete;
}
/** @category Common */
export type Message<T extends MessageType = MessageType> =
T extends MessageType.ConnectionAck
? ConnectionAckMessage
: T extends MessageType.ConnectionInit
? ConnectionInitMessage
: T extends MessageType.Ping
? PingMessage
: T extends MessageType.Pong
? PongMessage
: T extends MessageType.Subscribe
? SubscribeMessage
: T extends MessageType.Next
? NextMessage
: T extends MessageType.Error
? ErrorMessage
: T extends MessageType.Complete
? CompleteMessage
: never;
/**
* Validates the message against the GraphQL over WebSocket Protocol.
*
* Invalid messages will throw descriptive errors.
*
* @category Common
*/
export function validateMessage(val: unknown): Message {
if (!isObject(val)) {
throw new Error(
`Message is expected to be an object, but got ${extendedTypeof(val)}`,
);
}
if (!val.type) {
throw new Error(`Message is missing the 'type' property`);
}
if (typeof val.type !== 'string') {
throw new Error(
`Message is expects the 'type' property to be a string, but got ${extendedTypeof(
val.type,
)}`,
);
}
switch (val.type) {
case MessageType.ConnectionInit:
case MessageType.ConnectionAck:
case MessageType.Ping:
case MessageType.Pong: {
if ('payload' in val && !isObject(val.payload)) {
throw new Error(
`"${val.type}" message expects the 'payload' property to be an object or missing, but got "${val.payload}"`,
);
}
break;
}
case MessageType.Subscribe: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!isObject(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an object, but got ${extendedTypeof(
val.payload,
)}`,
);
}
if (typeof val.payload.query !== 'string') {
throw new Error(
`"${
val.type
}" message payload expects the 'query' property to be a string, but got ${extendedTypeof(
val.payload.query,
)}`,
);
}
if (val.payload.variables != null && !isObject(val.payload.variables)) {
throw new Error(
`"${
val.type
}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.variables,
)}`,
);
}
if (
val.payload.operationName != null &&
extendedTypeof(val.payload.operationName) !== 'string'
) {
throw new Error(
`"${
val.type
}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${extendedTypeof(
val.payload.operationName,
)}`,
);
}
if (val.payload.extensions != null && !isObject(val.payload.extensions)) {
throw new Error(
`"${
val.type
}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${extendedTypeof(
val.payload.extensions,
)}`,
);
}
break;
}
case MessageType.Next: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!isObject(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an object, but got ${extendedTypeof(
val.payload,
)}`,
);
}
break;
}
case MessageType.Error: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
if (!areGraphQLErrors(val.payload)) {
throw new Error(
`"${
val.type
}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(
val.payload,
)}`,
);
}
break;
}
case MessageType.Complete: {
if (typeof val.id !== 'string') {
throw new Error(
`"${
val.type
}" message expects the 'id' property to be a string, but got ${extendedTypeof(
val.id,
)}`,
);
}
if (!val.id) {
throw new Error(
`"${val.type}" message requires a non-empty 'id' property`,
);
}
break;
}
default:
throw new Error(`Invalid message 'type' property "${val.type}"`);
}
return val as unknown as Message;
}
/**
* Checks if the provided value is a valid GraphQL over WebSocket message.
*
* @deprecated Use `validateMessage` instead.
*
* @category Common
*/
export function isMessage(val: unknown): val is Message {
try {
validateMessage(val);
return true;
} catch {
return false;
}
}
/**
* Function for transforming values within a message during JSON parsing
* The values are produced by parsing the incoming raw JSON.
*
* Read more about using it:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter
*
* @category Common
*/
export type JSONMessageReviver = (this: any, key: string, value: any) => any;
/**
* Parses the raw websocket message data to a valid message.
*
* @category Common
*/
export function parseMessage(
data: unknown,
reviver?: JSONMessageReviver,
): Message {
return validateMessage(
typeof data === 'string' ? JSON.parse(data, reviver) : data,
);
}
/**
* Function that allows customization of the produced JSON string
* for the elements of an outgoing `Message` object.
*
* Read more about using it:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter
*
* @category Common
*/
export type JSONMessageReplacer = (this: any, key: string, value: any) => any;
/**
* Stringifies a valid message ready to be sent through the socket.
*
* @category Common
*/
export function stringifyMessage<T extends MessageType>(
msg: Message<T>,
replacer?: JSONMessageReplacer,
): string {
validateMessage(msg);
return JSON.stringify(msg, replacer);
}