forked from nbd-wtf/nostr-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
references.ts
104 lines (98 loc) · 2.53 KB
/
references.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
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
import { decode, type AddressPointer, type ProfilePointer, type EventPointer } from './nip19.ts'
import type { Event } from './core.ts'
type Reference = {
text: string
profile?: ProfilePointer
event?: EventPointer
address?: AddressPointer
}
const mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g
export function parseReferences(evt: Event): Reference[] {
let references: Reference[] = []
for (let ref of evt.content.matchAll(mentionRegex)) {
if (ref[2]) {
// it's a NIP-27 mention
try {
let { type, data } = decode(ref[1])
switch (type) {
case 'npub': {
references.push({
text: ref[0],
profile: { pubkey: data as string, relays: [] },
})
break
}
case 'nprofile': {
references.push({
text: ref[0],
profile: data as ProfilePointer,
})
break
}
case 'note': {
references.push({
text: ref[0],
event: { id: data as string, relays: [] },
})
break
}
case 'nevent': {
references.push({
text: ref[0],
event: data as EventPointer,
})
break
}
case 'naddr': {
references.push({
text: ref[0],
address: data as AddressPointer,
})
break
}
}
} catch (err) {
/***/
}
} else if (ref[3]) {
// it's a NIP-10 mention
let idx = parseInt(ref[3], 10)
let tag = evt.tags[idx]
if (!tag) continue
switch (tag[0]) {
case 'p': {
references.push({
text: ref[0],
profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] },
})
break
}
case 'e': {
references.push({
text: ref[0],
event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] },
})
break
}
case 'a': {
try {
let [kind, pubkey, identifier] = tag[1].split(':')
references.push({
text: ref[0],
address: {
identifier,
pubkey,
kind: parseInt(kind, 10),
relays: tag[2] ? [tag[2]] : [],
},
})
} catch (err) {
/***/
}
break
}
}
}
}
return references
}