deno.land / x / deno@v1.28.2 / ext / websocket / 02_websocketstream.js

02_websocketstream.js
نووسراو ببینە
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license."use strict";
/// <reference path="../../core/internal.d.ts" />
((window) => { const core = window.Deno.core; const ops = core.ops; const webidl = window.__bootstrap.webidl; const { writableStreamClose, Deferred } = window.__bootstrap.streams; const { DOMException } = window.__bootstrap.domException; const { add, remove } = window.__bootstrap.abortSignal; const { headersFromHeaderList, headerListFromHeaders, fillHeaders } = window.__bootstrap.headers;
const { ArrayPrototypeJoin, ArrayPrototypeMap, Error, ObjectPrototypeIsPrototypeOf, PromisePrototypeCatch, PromisePrototypeThen, Set, StringPrototypeEndsWith, StringPrototypeToLowerCase, Symbol, SymbolFor, TypeError, Uint8ArrayPrototype, } = window.__bootstrap.primordials;
webidl.converters.WebSocketStreamOptions = webidl.createDictionaryConverter( "WebSocketStreamOptions", [ { key: "protocols", converter: webidl.converters["sequence<USVString>"], get defaultValue() { return []; }, }, { key: "signal", converter: webidl.converters.AbortSignal, }, { key: "headers", converter: webidl.converters.HeadersInit, }, ], ); webidl.converters.WebSocketCloseInfo = webidl.createDictionaryConverter( "WebSocketCloseInfo", [ { key: "code", converter: webidl.converters["unsigned short"], }, { key: "reason", converter: webidl.converters.USVString, defaultValue: "", }, ], );
const CLOSE_RESPONSE_TIMEOUT = 5000;
const _rid = Symbol("[[rid]]"); const _url = Symbol("[[url]]"); const _connection = Symbol("[[connection]]"); const _closed = Symbol("[[closed]]"); const _earlyClose = Symbol("[[earlyClose]]"); const _closeSent = Symbol("[[closeSent]]"); class WebSocketStream { [_rid];
[_url]; get url() { webidl.assertBranded(this, WebSocketStreamPrototype); return this[_url]; }
constructor(url, options) { this[webidl.brand] = webidl.brand; const prefix = "Failed to construct 'WebSocketStream'"; webidl.requiredArguments(arguments.length, 1, { prefix }); url = webidl.converters.USVString(url, { prefix, context: "Argument 1", }); options = webidl.converters.WebSocketStreamOptions(options, { prefix, context: "Argument 2", });
const wsURL = new URL(url);
if (wsURL.protocol !== "ws:" && wsURL.protocol !== "wss:") { throw new DOMException( "Only ws & wss schemes are allowed in a WebSocket URL.", "SyntaxError", ); }
if (wsURL.hash !== "" || StringPrototypeEndsWith(wsURL.href, "#")) { throw new DOMException( "Fragments are not allowed in a WebSocket URL.", "SyntaxError", ); }
this[_url] = wsURL.href;
if ( options.protocols.length !== new Set( ArrayPrototypeMap( options.protocols, (p) => StringPrototypeToLowerCase(p), ), ).size ) { throw new DOMException( "Can't supply multiple times the same protocol.", "SyntaxError", ); }
const headers = headersFromHeaderList([], "request"); if (options.headers !== undefined) { fillHeaders(headers, options.headers); }
const cancelRid = ops.op_ws_check_permission_and_cancel_handle( "WebSocketStream.abort()", this[_url], true, );
if (options.signal?.aborted) { core.close(cancelRid); const err = options.signal.reason; this[_connection].reject(err); this[_closed].reject(err); } else { const abort = () => { core.close(cancelRid); }; options.signal?.[add](abort); PromisePrototypeThen( core.opAsync( "op_ws_create", "new WebSocketStream()", this[_url], options.protocols ? ArrayPrototypeJoin(options.protocols, ", ") : "", cancelRid, headerListFromHeaders(headers), ), (create) => { options.signal?.[remove](abort); if (this[_earlyClose]) { PromisePrototypeThen( core.opAsync("op_ws_close", create.rid), () => { PromisePrototypeThen( (async () => { while (true) { const { kind } = await core.opAsync( "op_ws_next_event", create.rid, );
if (kind === "close") { break; } } })(), () => { const err = new DOMException( "Closed while connecting", "NetworkError", ); this[_connection].reject(err); this[_closed].reject(err); }, ); }, () => { const err = new DOMException( "Closed while connecting", "NetworkError", ); this[_connection].reject(err); this[_closed].reject(err); }, ); } else { this[_rid] = create.rid;
const writable = new WritableStream({ write: async (chunk) => { if (typeof chunk === "string") { await core.opAsync("op_ws_send", this[_rid], { kind: "text", value: chunk, }); } else if ( ObjectPrototypeIsPrototypeOf(Uint8ArrayPrototype, chunk) ) { await core.opAsync("op_ws_send", this[_rid], { kind: "binary", value: chunk, }, chunk); } else { throw new TypeError( "A chunk may only be either a string or an Uint8Array", ); } }, close: async (reason) => { try { this.close(reason?.code !== undefined ? reason : {}); } catch (_) { this.close(); } await this.closed; }, abort: async (reason) => { try { this.close(reason?.code !== undefined ? reason : {}); } catch (_) { this.close(); } await this.closed; }, }); const pull = async (controller) => { const { kind, value } = await core.opAsync( "op_ws_next_event", this[_rid], );
switch (kind) { case "string": { controller.enqueue(value); break; } case "binary": { controller.enqueue(value); break; } case "ping": { await core.opAsync("op_ws_send", this[_rid], { kind: "pong", }); await pull(controller); break; } case "closed": case "close": { this[_closed].resolve(value); core.tryClose(this[_rid]); break; } case "error": { const err = new Error(value); this[_closed].reject(err); controller.error(err); core.tryClose(this[_rid]); break; } }
if ( this[_closeSent].state === "fulfilled" && this[_closed].state === "pending" ) { if ( new Date().getTime() - await this[_closeSent].promise <= CLOSE_RESPONSE_TIMEOUT ) { return pull(controller); }
this[_closed].resolve(value); core.tryClose(this[_rid]); } }; const readable = new ReadableStream({ start: (controller) => { PromisePrototypeThen(this.closed, () => { try { controller.close(); } catch (_) { // needed to ignore warnings & assertions } try { PromisePrototypeCatch( writableStreamClose(writable), () => {}, ); } catch (_) { // needed to ignore warnings & assertions } });
PromisePrototypeThen(this[_closeSent].promise, () => { if (this[_closed].state === "pending") { return pull(controller); } }); }, pull, cancel: async (reason) => { try { this.close(reason?.code !== undefined ? reason : {}); } catch (_) { this.close(); } await this.closed; }, });
this[_connection].resolve({ readable, writable, extensions: create.extensions ?? "", protocol: create.protocol ?? "", }); } }, (err) => { if (ObjectPrototypeIsPrototypeOf(core.InterruptedPrototype, err)) { // The signal was aborted. err = options.signal.reason; } else { core.tryClose(cancelRid); } this[_connection].reject(err); this[_closed].reject(err); }, ); } }
[_connection] = new Deferred(); get connection() { webidl.assertBranded(this, WebSocketStreamPrototype); return this[_connection].promise; }
[_earlyClose] = false; [_closed] = new Deferred(); [_closeSent] = new Deferred(); get closed() { webidl.assertBranded(this, WebSocketStreamPrototype); return this[_closed].promise; }
close(closeInfo) { webidl.assertBranded(this, WebSocketStreamPrototype); closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo, { prefix: "Failed to execute 'close' on 'WebSocketStream'", context: "Argument 1", });
if ( closeInfo.code && !(closeInfo.code === 1000 || (3000 <= closeInfo.code && closeInfo.code < 5000)) ) { throw new DOMException( "The close code must be either 1000 or in the range of 3000 to 4999.", "InvalidAccessError", ); }
const encoder = new TextEncoder(); if ( closeInfo.reason && encoder.encode(closeInfo.reason).byteLength > 123 ) { throw new DOMException( "The close reason may not be longer than 123 bytes.", "SyntaxError", ); }
let code = closeInfo.code; if (closeInfo.reason && code === undefined) { code = 1000; }
if (this[_connection].state === "pending") { this[_earlyClose] = true; } else if (this[_closed].state === "pending") { PromisePrototypeThen( core.opAsync("op_ws_close", this[_rid], code, closeInfo.reason), () => { setTimeout(() => { this[_closeSent].resolve(new Date().getTime()); }, 0); }, (err) => { this[_rid] && core.tryClose(this[_rid]); this[_closed].reject(err); }, ); } }
[SymbolFor("Deno.customInspect")](inspect) { return `${this.constructor.name} ${ inspect({ url: this.url, }) }`; } }
const WebSocketStreamPrototype = WebSocketStream.prototype;
window.__bootstrap.webSocket.WebSocketStream = WebSocketStream;})(this);
deno

Version Info

Tagged at
a year ago