forked from ipfs/public-gateway-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrustless.ts
60 lines (48 loc) · 1.72 KB
/
Trustless.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
import fetchPonyfill from 'fetch-ponyfill'
import { CheckBase } from './CheckBase'
import { HASH_TO_TEST, TRUSTLESS_RESPONSE_TYPES } from './constants'
import type { GatewayNode } from './GatewayNode'
import { Log } from './Log'
const { fetch } = fetchPonyfill()
const log = new Log('Trustless')
class Trustless extends CheckBase implements Checkable {
_className = 'Trustless'
_tagName = 'div'
constructor (protected parent: GatewayNode) {
super(parent, 'div', 'Trustless')
}
async check (): Promise<void> {
const now = Date.now()
const gatewayAndHash = this.parent.gateway.replace(':hash', HASH_TO_TEST)
this.parent.tag.classList.add('trustless')
try {
const trustlessResponseTypesTests = await Promise.all(TRUSTLESS_RESPONSE_TYPES.map(
async (trustlessTypes): Promise<boolean> => {
const testUrl = `${gatewayAndHash}?format=${trustlessTypes}&now=${now}#x-ipfs-companion-no-redirect`
const response = await fetch(testUrl)
return Boolean(response.headers.get('Content-Type')?.includes(`application/vnd.ipld.${trustlessTypes}`))
}
))
const failedTests = TRUSTLESS_RESPONSE_TYPES.filter((_result, idx) => !trustlessResponseTypesTests[idx])
if (failedTests.length === 0) {
this.tag.win()
} else {
const errorMsg = `URL '${gatewayAndHash} does not support the following Trustless response types: [` +
`${failedTests.join(', ')}]`
log.debug(errorMsg)
throw new Error(errorMsg)
}
} catch (err) {
log.error(err)
this.onerror()
throw err
}
}
checked (): void {
log.warn('Not implemented yet')
}
onerror (): void {
this.tag.err()
}
}
export { Trustless }