Skip to content

Commit 7d284e4

Browse files
authoredApr 8, 2021
feat: add types (#189)
BREAKING CHANGES: entry point uses named exports
1 parent aac0144 commit 7d284e4

25 files changed

+1072
-1130
lines changed
 

‎.aegir.js

-7
This file was deleted.

‎.github/ISSUE_TEMPLATE/bug_report.md

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
name: Bug report
3+
about: Create a report to help us improve
4+
title: ''
5+
labels: ''
6+
assignees: ''
7+
8+
---
9+
10+
**Describe the bug**
11+
A clear and concise description of what the bug is.
12+
13+
**To Reproduce**
14+
Steps to reproduce the behavior:
15+
1. Go to '...'
16+
2. Click on '....'
17+
3. Scroll down to '....'
18+
4. See error
19+
20+
**Expected behavior**
21+
A clear and concise description of what you expected to happen.
22+
23+
**Screenshots**
24+
If applicable, add screenshots to help explain your problem.
25+
26+
**Desktop (please complete the following information):**
27+
- OS: [e.g. iOS]
28+
- Browser [e.g. chrome, safari]
29+
- Version [e.g. 22]
30+
31+
**Smartphone (please complete the following information):**
32+
- Device: [e.g. iPhone6]
33+
- OS: [e.g. iOS8.1]
34+
- Browser [e.g. stock browser, safari]
35+
- Version [e.g. 22]
36+
37+
**Additional context**
38+
Add any other context about the problem here.
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
name: Feature request
3+
about: Suggest an idea for this project
4+
title: ''
5+
labels: ''
6+
assignees: ''
7+
8+
---
9+
10+
**Is your feature request related to a problem? Please describe.**
11+
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12+
13+
**Describe the solution you'd like**
14+
A clear and concise description of what you want to happen.
15+
16+
**Describe alternatives you've considered**
17+
A clear and concise description of any alternative solutions or features you've considered.
18+
19+
**Additional context**
20+
Add any other context or screenshots about the feature request here.

‎.github/workflows/main.yml

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
name: ci
2+
on:
3+
push:
4+
branches:
5+
- master
6+
pull_request:
7+
branches:
8+
- master
9+
10+
jobs:
11+
check:
12+
runs-on: ubuntu-latest
13+
steps:
14+
- uses: actions/checkout@v2
15+
- run: npm install
16+
- run: npx aegir lint
17+
- run: npx aegir ts -p check
18+
- run: npx aegir build
19+
- run: npx aegir dep-check
20+
- uses: ipfs/aegir/actions/bundle-size@master
21+
with:
22+
github_token: ${{ secrets.GITHUB_TOKEN }}
23+
test-node:
24+
needs: check
25+
runs-on: ${{ matrix.os }}
26+
strategy:
27+
matrix:
28+
os: [windows-latest, ubuntu-latest, macos-latest]
29+
node: [14, 15]
30+
fail-fast: true
31+
steps:
32+
- uses: actions/checkout@v2
33+
- uses: actions/setup-node@v1
34+
with:
35+
node-version: ${{ matrix.node }}
36+
- run: npm install
37+
- run: npx aegir test -t node --bail --cov
38+
- uses: codecov/codecov-action@v1
39+
test-chrome:
40+
needs: check
41+
runs-on: ubuntu-latest
42+
steps:
43+
- uses: actions/checkout@v2
44+
- uses: microsoft/playwright-github-action@v1
45+
- run: npm install
46+
- run: npx aegir test -t browser --bail --cov
47+
- run: npx aegir test -t webworker --bail
48+
- uses: codecov/codecov-action@v1
49+
test-firefox:
50+
needs: check
51+
runs-on: ubuntu-latest
52+
steps:
53+
- uses: actions/checkout@v2
54+
- uses: microsoft/playwright-github-action@v1
55+
- run: npm install
56+
- run: npx aegir test -t browser -t webworker --bail -- --browser firefox
57+
test-webkit:
58+
needs: check
59+
runs-on: ubuntu-latest
60+
steps:
61+
- uses: actions/checkout@v2
62+
- uses: microsoft/playwright-github-action@v1
63+
- run: npm install
64+
- run: npx aegir test -t browser -t webworker --bail -- --browser webkit
65+
test-electron-main:
66+
needs: check
67+
runs-on: ubuntu-latest
68+
steps:
69+
- uses: actions/checkout@v2
70+
- run: npm install
71+
- run: npx xvfb-maybe aegir test -t electron-main --bail
72+
test-electron-renderer:
73+
needs: check
74+
runs-on: ubuntu-latest
75+
steps:
76+
- uses: actions/checkout@v2
77+
- run: npm install
78+
- run: npx xvfb-maybe aegir test -t electron-renderer --bail

‎.travis.yml

-44
This file was deleted.

‎README.md

+27-39
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,8 @@ js-multiaddr
2424
- [Background](#background)
2525
- [What is multiaddr?](#what-is-multiaddr)
2626
- [Install](#install)
27-
- [Setup](#setup)
28-
- [Node.js](#nodejs)
29-
- [Browser: Browserify, Webpack, other bundlers](#browser-browserify-webpack-other-bundlers)
30-
- [Browser: `<script>` Tag](#browser-script-tag)
27+
- [NPM](#npm)
28+
- [Browser: `<script>` Tag](#browser-script-tag)
3129
- [Usage](#usage)
3230
- [API](#api)
3331
- [Resolvers](#resolvers)
@@ -48,30 +46,12 @@ A standard way to represent addresses that
4846

4947
## Install
5048

49+
### NPM
5150
```sh
5251
npm i multiaddr
5352
```
5453

55-
### Setup
56-
57-
#### Node.js
58-
59-
```js
60-
const multiaddr = require('multiaddr')
61-
```
62-
63-
#### Browser: Browserify, Webpack, other bundlers
64-
65-
The code published to npm that gets loaded on require is in fact a ES5
66-
transpiled version with the right shims added. This means that you can require
67-
it and use with your favourite bundler without having to adjust asset management
68-
process.
69-
70-
```js
71-
const multiaddr = require('multiaddr')
72-
```
73-
74-
#### Browser: `<script>` Tag
54+
### Browser: `<script>` Tag
7555

7656
Loading this module through a script tag will make the `Multiaddr` obj available in
7757
the global namespace.
@@ -83,35 +63,43 @@ the global namespace.
8363
## Usage
8464

8565
```js
86-
$ node
66+
// if we are coming from <= 8.x you can use the factory function
67+
constmultiaddr } = require('multiaddr')
68+
const addr =  multiaddr("/ip4/127.0.0.1/udp/1234")
69+
// <Multiaddr /ip4/127.0.0.1/udp/1234>
8770

88-
> const multiaddr = require('multiaddr')
71+
// or just the class directly
72+
constMultiaddr } = require('multiaddr')
8973

90-
> const addr = multiaddr("/ip4/127.0.0.1/udp/1234")
91-
<Multiaddr /ip4/127.0.0.1/udp/1234>
74+
const addr = new Multiaddr("/ip4/127.0.0.1/udp/1234")
75+
// <Multiaddr /ip4/127.0.0.1/udp/1234>
9276

93-
> addr.bytes
94-
<Uint8Array 04 7f 00 00 01 11 04 d2>
77+
addr.bytes
78+
// <Uint8Array 04 7f 00 00 01 11 04 d2>
9579

96-
> addr.toString()
97-
'/ip4/127.0.0.1/udp/1234'
80+
addr.toString()
81+
// '/ip4/127.0.0.1/udp/1234'
9882

99-
> addr.protos()
83+
addr.protos()
84+
/*
10085
[
10186
{code: 4, name: 'ip4', size: 32},
10287
{code: 273, name: 'udp', size: 16}
10388
]
89+
*/
10490

10591
// gives you an object that is friendly with what Node.js core modules expect for addresses
106-
> addr.nodeAddress()
92+
addr.nodeAddress()
93+
/*
10794
{
108-
family: "4",
95+
family: 4,
10996
port: 1234,
11097
address: "127.0.0.1"
11198
}
99+
*/
112100

113-
> addr.encapsulate('/sctp/5678')
114-
<Multiaddr /ip4/127.0.0.1/udp/1234/sctp/5678>
101+
addr.encapsulate('/sctp/5678')
102+
// <Multiaddr /ip4/127.0.0.1/udp/1234/sctp/5678>
115103
```
116104

117105
## API
@@ -124,10 +112,10 @@ https://multiformats.github.io/js-multiaddr/
124112
To provide multiaddr resolvers you can do:
125113

126114
```js
127-
const multiaddr = require('multiaddr')
115+
const { Multiaddr } = require('multiaddr')
128116
const resolvers = require('multiaddr/src/resolvers')
129117

130-
multiaddr.resolvers.set('dnsaddr', resolvers.dnsaddrResolver)
118+
Multiaddr.resolvers.set('dnsaddr', resolvers.dnsaddrResolver)
131119
```
132120

133121
The available resolvers are:

‎documentation.yml

-3
This file was deleted.

‎examples/try.js

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,29 @@
11
'use strict'
22

3-
var multiaddr = require('../src')
4-
var log = console.log
3+
const { Multiaddr } = require('../src')
4+
// eslint-disable-next-line no-console
5+
const log = console.log
56

6-
var addr = multiaddr('/ip4/127.0.0.1/udp/1234')
7+
const addr = new Multiaddr('/ip4/127.0.0.1/udp/1234')
78
log(addr)
89
log(addr.bytes)
910
log(addr.toString())
10-
log(multiaddr(addr.bytes))
11+
log(new Multiaddr(addr.bytes))
1112

1213
log(addr.protoCodes())
1314
log(addr.protoNames())
1415
log(addr.protos())
1516

1617
log(addr.nodeAddress())
17-
log(multiaddr.fromNodeAddress(addr.nodeAddress(), 'udp'))
18+
log(Multiaddr.fromNodeAddress(addr.nodeAddress(), 'udp'))
1819

1920
log(addr.encapsulate('/sctp/5678'))
2021
log(addr.decapsulate('/udp'))
2122

22-
var printer = multiaddr('/ip4/192.168.0.13/tcp/80')
23-
var proxy = multiaddr('/ip4/10.20.30.40/tcp/443')
24-
var printerOverProxy = proxy.encapsulate(printer)
23+
const printer = new Multiaddr('/ip4/192.168.0.13/tcp/80')
24+
const proxy = new Multiaddr('/ip4/10.20.30.40/tcp/443')
25+
const printerOverProxy = proxy.encapsulate(printer)
2526
log(printerOverProxy)
2627

27-
var proxyAgain = printerOverProxy.decapsulate('/ip4')
28+
const proxyAgain = printerOverProxy.decapsulate('/ip4')
2829
log(proxyAgain)

‎intro.md

-84
This file was deleted.

‎package.json

+17-14
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
"test": "npm run test:node && npm run test:browser",
1111
"test:node": "aegir test --ts -t node",
1212
"test:browser": "aegir test -t browser",
13-
"test:types": "npx tsc",
1413
"build": "aegir build",
1514
"release": "aegir release",
1615
"release-minor": "aegir release --type minor",
@@ -32,26 +31,30 @@
3231
"bugs": "https://github.com/multiformats/js-multiaddr/issues",
3332
"homepage": "https://github.com/multiformats/js-multiaddr",
3433
"browser": {
35-
"dns": false
34+
"./src/resolvers/dns.js": "./src/resolvers/dns.browser.js"
3635
},
3736
"dependencies": {
3837
"cids": "^1.0.0",
39-
"class-is": "^1.1.0",
4038
"dns-over-http-resolver": "^1.0.0",
41-
"err-code": "^2.0.3",
39+
"err-code": "^3.0.1",
4240
"is-ip": "^3.1.0",
43-
"multibase": "^3.0.0",
44-
"uint8arrays": "^1.1.0",
45-
"varint": "^5.0.0"
41+
"multibase": "^4.0.2",
42+
"uint8arrays": "^2.1.3",
43+
"varint": "^6.0.0"
4644
},
4745
"devDependencies": {
48-
"@types/chai": "^4.2.8",
49-
"@types/dirty-chai": "^2.0.2",
50-
"@types/mocha": "^8.0.1",
51-
"@types/node": "^14.0.11",
52-
"aegir": "^29.0.1",
53-
"sinon": "^9.2.0",
54-
"typescript": "^3.9.5"
46+
"@types/varint": "^6.0.0",
47+
"aegir": "^33.0.0",
48+
"sinon": "^10.0.0",
49+
"util": "^0.12.3"
50+
},
51+
"aegir": {
52+
"build": {
53+
"bundlesizeMax": "22kB"
54+
}
55+
},
56+
"eslintConfig": {
57+
"extends": "ipfs"
5558
},
5659
"contributors": [
5760
"David Dias <daviddias.p@gmail.com>",

‎src/codec.js

+66-7
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ module.exports = {
3333
}
3434

3535
// string -> [[str name, str addr]... ]
36+
/**
37+
* @param {string} str
38+
*/
3639
function stringToStringTuples (str) {
3740
const tuples = []
3841
const parts = str.split('/').slice(1) // skip first empty elem
@@ -73,22 +76,31 @@ function stringToStringTuples (str) {
7376
}
7477

7578
// [[str name, str addr]... ] -> string
79+
/**
80+
* @param {[number, string?][]} tuples
81+
*/
7682
function stringTuplesToString (tuples) {
83+
/** @type {Array<string | undefined>} */
7784
const parts = []
78-
tuples.map(tup => {
85+
tuples.map((tup) => {
7986
const proto = protoFromTuple(tup)
8087
parts.push(proto.name)
8188
if (tup.length > 1) {
8289
parts.push(tup[1])
8390
}
91+
return null
8492
})
8593

8694
return cleanPath(parts.join('/'))
8795
}
8896

8997
// [[str name, str addr]... ] -> [[int code, Uint8Array]... ]
98+
/**
99+
* @param {Array<string[] | string >} tuples
100+
* @returns {[number , Uint8Array?][]}
101+
*/
90102
function stringTuplesToTuples (tuples) {
91-
return tuples.map(tup => {
103+
return tuples.map((tup) => {
92104
if (!Array.isArray(tup)) {
93105
tup = [tup]
94106
}
@@ -100,20 +112,31 @@ function stringTuplesToTuples (tuples) {
100112
})
101113
}
102114

103-
// [[int code, Uint8Array]... ] -> [[str name, str addr]... ]
115+
/**
116+
* Convert tuples to string tuples
117+
*
118+
* [[int code, Uint8Array]... ] -> [[int code, str addr]... ]
119+
*
120+
* @param {Array<[number, Uint8Array?]>} tuples
121+
* @returns {Array<[number, string?]>}
122+
*/
123+
104124
function tuplesToStringTuples (tuples) {
105125
return tuples.map(tup => {
106126
const proto = protoFromTuple(tup)
107-
if (tup.length > 1) {
127+
if (tup[1]) {
108128
return [proto.code, convert.toString(proto.code, tup[1])]
109129
}
110130
return [proto.code]
111131
})
112132
}
113133

114134
// [[int code, Uint8Array ]... ] -> Uint8Array
135+
/**
136+
* @param {[number, Uint8Array?][]} tuples
137+
*/
115138
function tuplesToBytes (tuples) {
116-
return fromBytes(uint8ArrayConcat(tuples.map(tup => {
139+
return fromBytes(uint8ArrayConcat(tuples.map((/** @type {any[]} */ tup) => {
117140
const proto = protoFromTuple(tup)
118141
let buf = Uint8Array.from(varint.encode(proto.code))
119142

@@ -125,6 +148,10 @@ function tuplesToBytes (tuples) {
125148
})))
126149
}
127150

151+
/**
152+
* @param {import("./types").Protocol} p
153+
* @param {Uint8Array | number[]} addr
154+
*/
128155
function sizeForAddr (p, addr) {
129156
if (p.size > 0) {
130157
return p.size / 8
@@ -136,8 +163,13 @@ function sizeForAddr (p, addr) {
136163
}
137164
}
138165

139-
// Uint8Array -> [[int code, Uint8Array ]... ]
166+
/**
167+
*
168+
* @param {Uint8Array} buf
169+
* @returns {Array<[number, Uint8Array?]>}
170+
*/
140171
function bytesToTuples (buf) {
172+
/** @type {Array<[number, Uint8Array?]>} */
141173
const tuples = []
142174
let i = 0
143175
while (i < buf.length) {
@@ -170,13 +202,19 @@ function bytesToTuples (buf) {
170202
}
171203

172204
// Uint8Array -> String
205+
/**
206+
* @param {Uint8Array} buf
207+
*/
173208
function bytesToString (buf) {
174209
const a = bytesToTuples(buf)
175210
const b = tuplesToStringTuples(a)
176211
return stringTuplesToString(b)
177212
}
178213

179214
// String -> Uint8Array
215+
/**
216+
* @param {string} str
217+
*/
180218
function stringToBytes (str) {
181219
str = cleanPath(str)
182220
const a = stringToStringTuples(str)
@@ -186,17 +224,26 @@ function stringToBytes (str) {
186224
}
187225

188226
// String -> Uint8Array
227+
/**
228+
* @param {string} str
229+
*/
189230
function fromString (str) {
190231
return stringToBytes(str)
191232
}
192233

193234
// Uint8Array -> Uint8Array
235+
/**
236+
* @param {Uint8Array} buf
237+
*/
194238
function fromBytes (buf) {
195239
const err = validateBytes(buf)
196240
if (err) throw err
197241
return Uint8Array.from(buf) // copy
198242
}
199243

244+
/**
245+
* @param {Uint8Array} buf
246+
*/
200247
function validateBytes (buf) {
201248
try {
202249
bytesToTuples(buf) // try to parse. will throw if breaks
@@ -205,18 +252,30 @@ function validateBytes (buf) {
205252
}
206253
}
207254

255+
/**
256+
* @param {Uint8Array} buf
257+
*/
208258
function isValidBytes (buf) {
209259
return validateBytes(buf) === undefined
210260
}
211261

262+
/**
263+
* @param {string} str
264+
*/
212265
function cleanPath (str) {
213-
return '/' + str.trim().split('/').filter(a => a).join('/')
266+
return '/' + str.trim().split('/').filter((/** @type {any} */ a) => a).join('/')
214267
}
215268

269+
/**
270+
* @param {string} str
271+
*/
216272
function ParseError (str) {
217273
return new Error('Error parsing address: ' + str)
218274
}
219275

276+
/**
277+
* @param {any[]} tup
278+
*/
220279
function protoFromTuple (tup) {
221280
const proto = protocols(tup[0])
222281
return proto

‎src/convert.js

+53-6
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ const uint8ArrayConcat = require('uint8arrays/concat')
1212
module.exports = Convert
1313

1414
// converts (serializes) addresses
15+
/**
16+
* @param {string} proto
17+
* @param {string | Uint8Array} a
18+
*/
1519
function Convert (proto, a) {
1620
if (a instanceof Uint8Array) {
1721
return Convert.toString(proto, a)
@@ -20,9 +24,16 @@ function Convert (proto, a) {
2024
}
2125
}
2226

27+
/**
28+
* Convert [code,Uint8Array] to string
29+
*
30+
* @param {number|string} proto
31+
* @param {Uint8Array} buf
32+
* @returns {string}
33+
*/
2334
Convert.toString = function convertToString (proto, buf) {
24-
proto = protocols(proto)
25-
switch (proto.code) {
35+
const protocol = protocols(proto)
36+
switch (protocol.code) {
2637
case 4: // ipv4
2738
case 41: // ipv6
2839
return bytes2ip(buf)
@@ -31,7 +42,7 @@ Convert.toString = function convertToString (proto, buf) {
3142
case 273: // udp
3243
case 33: // dccp
3344
case 132: // sctp
34-
return bytes2port(buf)
45+
return bytes2port(buf).toString()
3546

3647
case 53: // dns
3748
case 54: // dns4
@@ -52,9 +63,9 @@ Convert.toString = function convertToString (proto, buf) {
5263
}
5364
}
5465

55-
Convert.toBytes = function convertToBytes (proto, str) {
56-
proto = protocols(proto)
57-
switch (proto.code) {
66+
Convert.toBytes = function convertToBytes (/** @type {string | number } */ proto, /** @type {string} */ str) {
67+
const protocol = protocols(proto)
68+
switch (protocol.code) {
5869
case 4: // ipv4
5970
return ip2bytes(str)
6071
case 41: // ipv6
@@ -85,13 +96,19 @@ Convert.toBytes = function convertToBytes (proto, str) {
8596
}
8697
}
8798

99+
/**
100+
* @param {string} ipString
101+
*/
88102
function ip2bytes (ipString) {
89103
if (!ip.isIP(ipString)) {
90104
throw new Error('invalid ip address')
91105
}
92106
return ip.toBytes(ipString)
93107
}
94108

109+
/**
110+
* @param {Uint8Array} ipBuff
111+
*/
95112
function bytes2ip (ipBuff) {
96113
const ipString = ip.toString(ipBuff)
97114
if (!ipString || !ip.isIP(ipString)) {
@@ -100,6 +117,9 @@ function bytes2ip (ipBuff) {
100117
return ipString
101118
}
102119

120+
/**
121+
* @param {number} port
122+
*/
103123
function port2bytes (port) {
104124
const buf = new ArrayBuffer(2)
105125
const view = new DataView(buf)
@@ -108,17 +128,26 @@ function port2bytes (port) {
108128
return new Uint8Array(buf)
109129
}
110130

131+
/**
132+
* @param {Uint8Array} buf
133+
*/
111134
function bytes2port (buf) {
112135
const view = new DataView(buf.buffer)
113136
return view.getUint16(0)
114137
}
115138

139+
/**
140+
* @param {string} str
141+
*/
116142
function str2bytes (str) {
117143
const buf = uint8ArrayFromString(str)
118144
const size = Uint8Array.from(varint.encode(buf.length))
119145
return uint8ArrayConcat([size, buf], size.length + buf.length)
120146
}
121147

148+
/**
149+
* @param {Uint8Array} buf
150+
*/
122151
function bytes2str (buf) {
123152
const size = varint.decode(buf)
124153
buf = buf.slice(varint.decode.bytes)
@@ -130,13 +159,22 @@ function bytes2str (buf) {
130159
return uint8ArrayToString(buf)
131160
}
132161

162+
/**
163+
* @param {string | Uint8Array | CID} hash
164+
*/
133165
function mh2bytes (hash) {
134166
// the address is a varint prefixed multihash string representation
135167
const mh = new CID(hash).multihash
136168
const size = Uint8Array.from(varint.encode(mh.length))
137169
return uint8ArrayConcat([size, mh], size.length + mh.length)
138170
}
139171

172+
/**
173+
* Converts bytes to bas58btc string
174+
*
175+
* @param {Uint8Array} buf
176+
* @returns {string} bas58btc string
177+
*/
140178
function bytes2mh (buf) {
141179
const size = varint.decode(buf)
142180
const address = buf.slice(varint.decode.bytes)
@@ -148,6 +186,9 @@ function bytes2mh (buf) {
148186
return uint8ArrayToString(address, 'base58btc')
149187
}
150188

189+
/**
190+
* @param {string} str
191+
*/
151192
function onion2bytes (str) {
152193
const addr = str.split(':')
153194
if (addr.length !== 2) {
@@ -169,6 +210,9 @@ function onion2bytes (str) {
169210
return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)
170211
}
171212

213+
/**
214+
* @param {string} str
215+
*/
172216
function onion32bytes (str) {
173217
const addr = str.split(':')
174218
if (addr.length !== 2) {
@@ -189,6 +233,9 @@ function onion32bytes (str) {
189233
return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)
190234
}
191235

236+
/**
237+
* @param {Uint8Array} buf
238+
*/
192239
function bytes2onion (buf) {
193240
const addrBytes = buf.slice(0, buf.length - 2)
194241
const portBytes = buf.slice(buf.length - 2)

‎src/index.d.ts

-204
This file was deleted.

‎src/index.js

+532-476
Large diffs are not rendered by default.

‎src/ip.js

+12-8
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,25 @@ const isV4 = isIp.v4
88
const isV6 = isIp.v6
99

1010
// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7
11+
// @ts-ignore - this is copied from the link above better to keep it the same
1112
const toBytes = function (ip, buff, offset) {
1213
offset = ~~offset
1314

14-
var result
15+
let result
1516

1617
if (isV4(ip)) {
1718
result = buff || new Uint8Array(offset + 4)
19+
// @ts-ignore
20+
// eslint-disable-next-line array-callback-return
1821
ip.split(/\./g).map(function (byte) {
1922
result[offset++] = parseInt(byte, 10) & 0xff
2023
})
2124
} else if (isV6(ip)) {
22-
var sections = ip.split(':', 8)
25+
const sections = ip.split(':', 8)
2326

24-
var i
27+
let i
2528
for (i = 0; i < sections.length; i++) {
26-
var isv4 = isV4(sections[i])
29+
const isv4 = isV4(sections[i])
2730
var v4Buffer
2831

2932
if (isv4) {
@@ -42,7 +45,7 @@ const toBytes = function (ip, buff, offset) {
4245
while (sections.length < 8) sections.push('0')
4346
} else if (sections.length < 8) {
4447
for (i = 0; i < sections.length && sections[i] !== ''; i++);
45-
var argv = [i, '1']
48+
const argv = [i, '1']
4649
for (i = 9 - sections.length; i > 0; i--) {
4750
argv.push('0')
4851
}
@@ -51,7 +54,7 @@ const toBytes = function (ip, buff, offset) {
5154

5255
result = buff || new Uint8Array(offset + 16)
5356
for (i = 0; i < sections.length; i++) {
54-
var word = parseInt(sections[i], 16)
57+
const word = parseInt(sections[i], 16)
5558
result[offset++] = (word >> 8) & 0xff
5659
result[offset++] = word & 0xff
5760
}
@@ -65,12 +68,13 @@ const toBytes = function (ip, buff, offset) {
6568
}
6669

6770
// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
71+
// @ts-ignore - this is copied from the link above better to keep it the same
6872
const toString = function (buff, offset, length) {
6973
offset = ~~offset
7074
length = length || (buff.length - offset)
7175

72-
var result = []
73-
var string
76+
const result = []
77+
let string
7478
const view = new DataView(buff.buffer)
7579
if (length === 4) {
7680
// IPv4

‎src/protocols-table.js

+23-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
'use strict'
2+
/** @typedef {import("./types").Protocol} Protocol */
23

4+
/**
5+
* Protocols
6+
*
7+
* @param {number | string} proto
8+
* @returns {Protocol}
9+
*/
310
function Protocols (proto) {
411
if (typeof (proto) === 'number') {
512
if (Protocols.codes[proto]) {
613
return Protocols.codes[proto]
714
}
815

916
throw new Error('no protocol with code: ' + proto)
10-
} else if (typeof (proto) === 'string' || proto instanceof String) {
17+
} else if (typeof (proto) === 'string') {
1118
if (Protocols.names[proto]) {
1219
return Protocols.names[proto]
1320
}
@@ -22,6 +29,7 @@ const V = -1
2229
Protocols.lengthPrefixedVarSize = V
2330
Protocols.V = V
2431

32+
/** @type {Array<[number, number, string, (string|boolean)?, string?]>} */
2533
Protocols.table = [
2634
[4, 32, 'ip4'],
2735
[6, 16, 'tcp'],
@@ -58,19 +66,32 @@ Protocols.table = [
5866
[480, 0, 'http'],
5967
[777, V, 'memory']
6068
]
61-
69+
/** @type {Record<string,Protocol>} */
6270
Protocols.names = {}
71+
/** @type {Record<number,Protocol>} */
6372
Protocols.codes = {}
6473

6574
// populate tables
6675
Protocols.table.map(row => {
6776
const proto = p.apply(null, row)
6877
Protocols.codes[proto.code] = proto
6978
Protocols.names[proto.name] = proto
79+
return null
7080
})
7181

7282
Protocols.object = p
7383

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+
*/
7495
function p (code, size, name, resolvable, path) {
7596
return {
7697
code,

‎src/resolvers/dns.browser.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
'use strict'
2+
3+
/** @type {import('dns').promises.Resolver} */
4+
// @ts-ignore - has no types
5+
const dns = require('dns-over-http-resolver')
6+
7+
module.exports = dns

‎src/resolvers/dns.js

+1-12
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,3 @@
11
'use strict'
22

3-
let dns
4-
5-
try {
6-
dns = require('dns').promises
7-
if (!dns) {
8-
throw new Error('no dns available')
9-
}
10-
} catch (err) {
11-
dns = require('dns-over-http-resolver')
12-
}
13-
14-
module.exports = dns
3+
module.exports = require('dns').promises.Resolver

‎src/resolvers/index.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
'use strict'
22

3-
const Multiaddr = require('..') // eslint-disable-line no-unused-vars
43
const protocols = require('../protocols-table')
54

65
const { code: dnsaddrCode } = protocols('dnsaddr')
76

7+
/**
8+
* @typedef {import('..').Multiaddr} Multiaddr
9+
*/
10+
811
/**
912
* Resolver for dnsaddr addresses.
1013
*
1114
* @param {Multiaddr} addr
12-
* @returns {Promise<Array<string>>}
15+
* @returns {Promise<string[]>}
1316
*/
1417
async function dnsaddrResolver (addr) {
15-
const { Resolver } = require('./dns')
18+
const Resolver = require('./dns')
1619
const resolver = new Resolver()
1720

1821
const peerId = addr.getPeerId()
1922
const [, hostname] = addr.stringTuples().find(([proto]) => proto === dnsaddrCode) || []
2023

2124
const records = await resolver.resolveTxt(`_dnsaddr.${hostname}`)
22-
// @ts-ignore
2325
let addresses = records.flat().map((a) => a.split('=')[1])
2426

2527
if (peerId) {

‎src/types.d.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export interface Protocol {
2+
code: number
3+
size: number
4+
name: string
5+
resolvable?: boolean | undefined
6+
path?: boolean | undefined
7+
}
8+
9+
export interface MultiaddrObject {
10+
family: 4 | 6
11+
host: string
12+
transport: string
13+
port: number
14+
}

‎test/index.spec.js

+148-163
Large diffs are not rendered by default.

‎test/protocols.spec.js

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ describe('protocols', () => {
2424

2525
it('else', () => {
2626
expect(
27+
// @ts-expect-error
2728
() => protocols({ hi: 34 })
2829
).to.throw(
2930
/invalid protocol id type/

‎test/resolvers.spec.js

+12-11
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
const { expect } = require('aegir/utils/chai')
55
const sinon = require('sinon')
66

7-
const multiaddr = require('../src')
7+
const { Multiaddr } = require('../src')
88
const resolvers = require('../src/resolvers')
9-
const { Resolver } = require('../src/resolvers/dns')
9+
const Resolver = require('../src/resolvers/dns')
1010

1111
const dnsaddrStub1 = [
1212
['dnsaddr=/dnsaddr/ams-1.bootstrap.libp2p.io/p2p/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd'],
@@ -28,7 +28,7 @@ const dnsaddrStub2 = [
2828

2929
describe('multiaddr resolve', () => {
3030
it('should throw if no resolver is available', async () => {
31-
const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
31+
const ma = new Multiaddr('/dnsaddr/bootstrap.libp2p.io')
3232

3333
// Resolve
3434
await expect(ma.resolve()).to.eventually.be.rejected()
@@ -38,15 +38,15 @@ describe('multiaddr resolve', () => {
3838
describe('dnsaddr', () => {
3939
before(() => {
4040
// Set resolvers
41-
multiaddr.resolvers.set('dnsaddr', resolvers.dnsaddrResolver)
41+
Multiaddr.resolvers.set('dnsaddr', resolvers.dnsaddrResolver)
4242
})
4343

4444
afterEach(() => {
4545
sinon.restore()
4646
})
4747

4848
it('can resolve dnsaddr without no peerId', async () => {
49-
const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
49+
const ma = new Multiaddr('/dnsaddr/bootstrap.libp2p.io')
5050

5151
const stub = sinon.stub(Resolver.prototype, 'resolveTxt')
5252
stub.onCall(0).returns(Promise.resolve(dnsaddrStub1))
@@ -58,12 +58,12 @@ describe('multiaddr resolve', () => {
5858
resolvedMas.forEach((ma, index) => {
5959
const stubAddr = dnsaddrStub1[index][0].split('=')[1]
6060

61-
expect(ma.equals(multiaddr(stubAddr))).to.equal(true)
61+
expect(ma.equals(new Multiaddr(stubAddr))).to.equal(true)
6262
})
6363
})
6464

6565
it('can resolve dnsaddr with peerId', async () => {
66-
const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')
66+
const ma = new Multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')
6767

6868
const stub = sinon.stub(Resolver.prototype, 'resolveTxt')
6969
stub.onCall(0).returns(Promise.resolve(dnsaddrStub1))
@@ -73,11 +73,11 @@ describe('multiaddr resolve', () => {
7373
const resolvedMas = await ma.resolve()
7474

7575
expect(resolvedMas).to.have.length(1)
76-
expect(resolvedMas[0].equals(multiaddr('/dnsaddr/ams-2.bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb'))).to.eql(true)
76+
expect(resolvedMas[0].equals(new Multiaddr('/dnsaddr/ams-2.bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb'))).to.eql(true)
7777
})
7878

7979
it('can resolve dnsaddr with peerId two levels', async () => {
80-
const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')
80+
const ma = new Multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb')
8181

8282
const stub = sinon.stub(Resolver.prototype, 'resolveTxt')
8383
stub.onCall(0).returns(Promise.resolve(dnsaddrStub1))
@@ -93,10 +93,11 @@ describe('multiaddr resolve', () => {
9393
const resolvedMas = resolvedSecondMas.flat()
9494

9595
expect(resolvedMas).to.have.length(dnsaddrStub2.length)
96-
resolvedMas.forEach((ma, index) => {
96+
97+
resolvedMas.forEach((/** @type {Multiaddr} */ma, /** @type {number} */ index) => {
9798
const stubAddr = dnsaddrStub2[index][0].split('=')[1]
9899

99-
expect(ma.equals(multiaddr(stubAddr))).to.equal(true)
100+
expect(ma.equals(new Multiaddr(stubAddr))).to.equal(true)
100101
})
101102
})
102103
})

‎test/types.spec.ts

-22
This file was deleted.

‎tsconfig.json

+7-15
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
11
{
2+
"extends": "aegir/src/config/tsconfig.aegir.json",
23
"compilerOptions": {
3-
"module": "commonjs",
4-
"lib": ["es6"],
5-
"target": "ES5",
6-
"noImplicitAny": false,
7-
"noImplicitThis": true,
8-
"strictFunctionTypes": true,
9-
"strictNullChecks": true,
10-
"esModuleInterop": true,
11-
"resolveJsonModule": true,
12-
"allowJs": true,
13-
"checkJs": true,
14-
"noEmit": true,
15-
"forceConsistentCasingInFileNames": true
4+
"outDir": "dist"
165
},
17-
"include": ["src/index.d.ts", "test/**/*.spec.js", "test/**/*.spec.ts"]
18-
}
6+
"include": [
7+
"test",
8+
"src"
9+
]
10+
}

0 commit comments

Comments
 (0)
Please sign in to comment.