This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
94 lines (77 loc) · 2.34 KB
/
util.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
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
const IsCanonicalBase64 = require('is-canonical-base64')
const { isFeedType, isMsgType, isBlobType } = require('ssb-ref')
const encryptedTypeRegex = IsCanonicalBase64('', '\\.box\\d*')
const sigTypeRegex = IsCanonicalBase64('', '\\.sig\\.[a-zA-Z0-9]+')
const isEncryptedType = (input) => encryptedTypeRegex.test(input)
const isSigType = (input) => sigTypeRegex.test(input)
function decorateBFE(types) {
const sigilSuffixRegexp = (type, format) => {
if (!format.sigil && !format.suffix) return
return IsCanonicalBase64(
format.sigil || '',
(format.suffix && format.suffix.replace('.', '\\.')) || '',
format.data_length
)
// NOTE this assumes all sigil / suffix encodings are base64
}
return types.map((type) => {
return {
...type,
code: Buffer.from([type.code]),
formats: type.formats.map((format) => {
return {
...format,
code: Buffer.from([format.code]),
// TFCode: Buffer.from([type.code, format.code]),
sigilSuffixRegexp: sigilSuffixRegexp(type, format),
}
}),
}
})
}
function findTypeFormatForSigilSuffix(input, types) {
// NOTE tests guarentee that sigil is unique across types
let type
let format
if (typeof input !== 'string') return { type, format }
if (isFeedType(input)) type = types[0]
else if (isMsgType(input)) type = types[1]
else if (isBlobType(input)) type = types[2]
else if (isEncryptedType(input)) type = types[5]
else if (isSigType(input)) type = types[4]
// first regexp match to narrow type
if (type) {
try {
format = type.formats.find((format) =>
format.sigilSuffixRegexp.test(input)
)
// second regexp check to be 100% sure of match
} catch {
format = undefined
}
return { type, format }
}
return { type, format }
}
function definitionsToDict(types) {
const NAMED_TYPES = {}
function convertFormats(type) {
const formats = {}
for (const format of type.formats) {
formats[format.format] = format
}
return { ...type, formats }
}
for (const type of types) {
NAMED_TYPES[type.type] = convertFormats(type)
}
return NAMED_TYPES
}
module.exports = {
decorateBFE,
findTypeFormatForSigilSuffix,
definitionsToDict,
}