UNPKG

2.38 kBJavaScriptView Raw
1'use strict'
2/** @typedef {import("./types").Protocol} Protocol */
3
4/**
5 * Protocols
6 *
7 * @param {number | string} proto
8 * @returns {Protocol}
9 */
10function Protocols (proto) {
11 if (typeof (proto) === 'number') {
12 if (Protocols.codes[proto]) {
13 return Protocols.codes[proto]
14 }
15
16 throw new Error('no protocol with code: ' + proto)
17 } else if (typeof (proto) === 'string') {
18 if (Protocols.names[proto]) {
19 return Protocols.names[proto]
20 }
21
22 throw new Error('no protocol with name: ' + proto)
23 }
24
25 throw new Error('invalid protocol id type: ' + proto)
26}
27
28const V = -1
29Protocols.lengthPrefixedVarSize = V
30Protocols.V = V
31
32/** @type {Array<[number, number, string, (string|boolean)?, string?]>} */
33Protocols.table = [
34 [4, 32, 'ip4'],
35 [6, 16, 'tcp'],
36 [33, 16, 'dccp'],
37 [41, 128, 'ip6'],
38 [42, V, 'ip6zone'],
39 [53, V, 'dns', 'resolvable'],
40 [54, V, 'dns4', 'resolvable'],
41 [55, V, 'dns6', 'resolvable'],
42 [56, V, 'dnsaddr', 'resolvable'],
43 [132, 16, 'sctp'],
44 [273, 16, 'udp'],
45 [275, 0, 'p2p-webrtc-star'],
46 [276, 0, 'p2p-webrtc-direct'],
47 [277, 0, 'p2p-stardust'],
48 [290, 0, 'p2p-circuit'],
49 [301, 0, 'udt'],
50 [302, 0, 'utp'],
51 [400, V, 'unix', false, 'path'],
52 // `ipfs` is added before `p2p` for legacy support.
53 // All text representations will default to `p2p`, but `ipfs` will
54 // still be supported
55 [421, V, 'ipfs'],
56 // `p2p` is the preferred name for 421, and is now the default
57 [421, V, 'p2p'],
58 [443, 0, 'https'],
59 [444, 96, 'onion'],
60 [445, 296, 'onion3'],
61 [446, V, 'garlic64'],
62 [460, 0, 'quic'],
63 [477, 0, 'ws'],
64 [478, 0, 'wss'],
65 [479, 0, 'p2p-websocket-star'],
66 [480, 0, 'http'],
67 [777, V, 'memory']
68]
69/** @type {Record<string,Protocol>} */
70Protocols.names = {}
71/** @type {Record<number,Protocol>} */
72Protocols.codes = {}
73
74// populate tables
75Protocols.table.map(row => {
76 const proto = p.apply(null, row)
77 Protocols.codes[proto.code] = proto
78 Protocols.names[proto.name] = proto
79 return null
80})
81
82Protocols.object = p
83
84/**
85 *
86 * Create a protocol
87 *
88 * @param {number} code
89 * @param {number} size
90 * @param {string} name
91 * @param {any} [resolvable]
92 * @param {any} [path]
93 * @returns {Protocol}
94 */
95function p (code, size, name, resolvable, path) {
96 return {
97 code,
98 size,
99 name,
100 resolvable: Boolean(resolvable),
101 path: Boolean(path)
102 }
103}
104
105module.exports = Protocols