@estiva-app/conversation 0.26.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +1 -0
- package/dist/builders.d.ts +12 -4
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +19 -6
- package/dist/builders.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/membership.d.ts +11 -3
- package/dist/membership.d.ts.map +1 -1
- package/dist/membership.js +54 -7
- package/dist/membership.js.map +1 -1
- package/dist/places.d.ts +168 -0
- package/dist/places.d.ts.map +1 -0
- package/dist/places.js +448 -0
- package/dist/places.js.map +1 -0
- package/dist/readState.d.ts +11 -0
- package/dist/readState.d.ts.map +1 -1
- package/dist/readState.js +18 -1
- package/dist/readState.js.map +1 -1
- package/dist/strength.d.ts +4 -1
- package/dist/strength.d.ts.map +1 -1
- package/dist/strength.js +9 -3
- package/dist/strength.js.map +1 -1
- package/package.json +3 -3
- package/src/builders.ts +41 -8
- package/src/index.ts +27 -1
- package/src/membership.ts +28 -9
- package/src/places.ts +521 -0
- package/src/readState.ts +18 -1
- package/src/strength.ts +9 -3
package/src/places.ts
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Places and following — SPEC §11.8 *Places and following*.
|
|
3
|
+
*
|
|
4
|
+
* A **place** is one of a team's three kinds (§3): its chat, a space, or a
|
|
5
|
+
* topic it leads. A person `P` is **in** a place at a level, All or
|
|
6
|
+
* Important, or not in it, and that, not file membership, decides what on the
|
|
7
|
+
* place is unread for `P`.
|
|
8
|
+
*
|
|
9
|
+
* | way in | the events |
|
|
10
|
+
* | --- | --- |
|
|
11
|
+
* | 1. chose a level | a `follow:<P>` change on the place, signed by `P`, value `all` or `important` |
|
|
12
|
+
* | 2. joined, or was added | a `member:<P>` = `true` on the place, by anyone |
|
|
13
|
+
* | 3. made it | `P` wrote the topic's or space's first record |
|
|
14
|
+
* | 4. a team's default | a space of a team `P` is a member or follower of, or the chat of a team `P` is a member of, not in `P`'s private `off` list |
|
|
15
|
+
*
|
|
16
|
+
* `P`'s own acts read in one order: `P`'s `member:<P>` = `false` ends ways 1
|
|
17
|
+
* to 3 and every level chosen before it; a level, a join or an Add after it
|
|
18
|
+
* puts `P` back in. Only the `off` list turns a default off. An archived
|
|
19
|
+
* team's places hold nobody. A mute already kept for a place still wins: it
|
|
20
|
+
* lights only what mentions `P`.
|
|
21
|
+
*
|
|
22
|
+
* Everything here is worked out from events the caller read with
|
|
23
|
+
* {@link placeFilters}; nothing is stored and no default is ever written.
|
|
24
|
+
*
|
|
25
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-team-has-members-and-followers-and-a-place-is-followed-at-a-level.md
|
|
26
|
+
*/
|
|
27
|
+
import { fileIdOf, KIND, type SignedEvent, type UnsignedEvent } from '@estiva-app/protocol'
|
|
28
|
+
import { FILE_ADDRESS, FOLDER_ID, KIND_APP_DATA, KIND_CHANGE } from './kinds.js'
|
|
29
|
+
import { APPDATA_TAG, FOLLOW_FIELD_PREFIX, memberOfField } from './membership.js'
|
|
30
|
+
import { byOrder } from './order.js'
|
|
31
|
+
import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
|
|
32
|
+
import { peopleNamedInBody } from './strength.js'
|
|
33
|
+
import { groupThreads } from './threads.js'
|
|
34
|
+
|
|
35
|
+
/** A team's own address kind: on it, a level or a member change is about the team's chat. */
|
|
36
|
+
const KIND_TEAM = 39000
|
|
37
|
+
/** The relay's list of a team's members (NIP-29). */
|
|
38
|
+
const KIND_ROSTER = 39002
|
|
39
|
+
/** Put a person on a team, and take one off (NIP-29). */
|
|
40
|
+
const KIND_PUT_USER = KIND.NIP29_PUT_USER
|
|
41
|
+
const KIND_REMOVE_USER = 9001
|
|
42
|
+
/** A person's own join and leave (NIP-29). */
|
|
43
|
+
const KIND_JOIN = 9021
|
|
44
|
+
const KIND_LEAVE = 9022
|
|
45
|
+
const KIND_CREATE_TEAM = KIND.NIP29_CREATE_GROUP
|
|
46
|
+
/** A team's relay-signed list, and the command that changes it (§3.3). */
|
|
47
|
+
const KIND_FOLDER_STATE = 30890
|
|
48
|
+
const KIND_FOLDER_COMMAND = KIND.FOLDER_COMMAND
|
|
49
|
+
/** The role on a team list's entry that marks a topic one of the team's spaces (§3.3). */
|
|
50
|
+
const SPACE_ROLE = 'space'
|
|
51
|
+
|
|
52
|
+
const PUBKEY = /^[0-9a-f]{64}$/
|
|
53
|
+
|
|
54
|
+
type Event = Pick<SignedEvent, 'id' | 'pubkey' | 'kind' | 'created_at' | 'tags' | 'content'>
|
|
55
|
+
|
|
56
|
+
/** A relay filter, as `QueryFn` takes one. */
|
|
57
|
+
type Filter = Record<string, unknown>
|
|
58
|
+
|
|
59
|
+
const tag = (event: Pick<SignedEvent, 'tags'>, name: string): string | undefined => event.tags.find((t) => t[0] === name)?.[1]
|
|
60
|
+
const dOf = (address: string): string => address.split(':').slice(2).join(':')
|
|
61
|
+
|
|
62
|
+
/** A level on a place. Every default is Important. */
|
|
63
|
+
export type Level = 'all' | 'important'
|
|
64
|
+
|
|
65
|
+
/** The three kinds of place a team holds (§3). */
|
|
66
|
+
export type PlaceKind = 'chat' | 'space' | 'topic'
|
|
67
|
+
|
|
68
|
+
/** A place, as the caller knows it. */
|
|
69
|
+
export interface Place {
|
|
70
|
+
/** A topic's or space's address, or the team's own `39000:…` address for its chat. */
|
|
71
|
+
address: string
|
|
72
|
+
/** The uuid of the team the place is in: the one whose list names the topic, or the team itself for its chat. */
|
|
73
|
+
team: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** What the caller read for one place, with {@link placeFilters}. */
|
|
77
|
+
export interface PlaceFacts {
|
|
78
|
+
/** The place's own events: its first record's versions (a topic or space) and its `kind:1851` changes. */
|
|
79
|
+
events: readonly Event[]
|
|
80
|
+
/** The team's `kind:39002` and its stored `kind:9000`, `9001`, `9021`, `9022` and `9007`. */
|
|
81
|
+
roster?: readonly Event[]
|
|
82
|
+
/** The team's `kind:30890` and the `kind:1852` commands naming the place — what makes it a space, and since when. */
|
|
83
|
+
listing?: readonly Event[]
|
|
84
|
+
/** The person's private teams list ({@link parseTeamsBlob}); undefined when they keep none. */
|
|
85
|
+
teams?: TeamsList
|
|
86
|
+
/** Whether the team is archived (§3.2): its places then hold nobody. */
|
|
87
|
+
archived?: boolean
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** How `P` is in a place: way 1 to 4 of §11.8. */
|
|
91
|
+
export type WayIn = 'level' | 'added' | 'author' | 'team'
|
|
92
|
+
|
|
93
|
+
/** Whether a person is in a place, at what level, and since when. */
|
|
94
|
+
export interface Following {
|
|
95
|
+
kind: PlaceKind
|
|
96
|
+
in: boolean
|
|
97
|
+
/** The level that lights for them: the one they chose, else Important. Undefined when not in. */
|
|
98
|
+
level?: Level
|
|
99
|
+
/** Unix seconds: the earliest start among the ways that hold. Undefined when not in, or no way's start is known. */
|
|
100
|
+
since?: number
|
|
101
|
+
/**
|
|
102
|
+
* Unix seconds the person chose All: what All lights beyond Important counts
|
|
103
|
+
* from then, so choosing it never brings back older replies (Miky,
|
|
104
|
+
* 2026-11-03). Undefined unless the level is All.
|
|
105
|
+
*/
|
|
106
|
+
allSince?: number
|
|
107
|
+
/** Every way in that holds now. */
|
|
108
|
+
ways: WayIn[]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
type Act = { event: Event; act: 'creation' | 'level' | 'clear' | 'join' | 'leave'; level?: Level }
|
|
112
|
+
|
|
113
|
+
/** The person's own acts on the place, in §6.3's order: the first record first, a leave before a join in a tie. */
|
|
114
|
+
function actsOf(place: Place, person: string, events: readonly Event[]): Act[] {
|
|
115
|
+
const id = fileIdOf(place.address) ?? dOf(place.address)
|
|
116
|
+
const acts: Act[] = []
|
|
117
|
+
const versions = place.address.startsWith(`${KIND_TEAM}:`) ? [] : events.filter((e) => addressOf(e) === place.address).sort(byOrder)
|
|
118
|
+
if (versions[0]?.pubkey === person) acts.push({ event: { ...versions[0], created_at: Math.min(...versions.map((v) => v.created_at)) }, act: 'creation' })
|
|
119
|
+
// A change filed in another Folder is ignored (§6.2): the place's own Folder is the team for its chat, else its root's `h`.
|
|
120
|
+
const folder = versions.length ? (tag(versions[versions.length - 1], 'h') ?? place.team) : place.team
|
|
121
|
+
for (const change of events) {
|
|
122
|
+
if (change.kind !== KIND_CHANGE || tag(change, 'a') !== place.address || tag(change, 'h') !== folder) continue
|
|
123
|
+
const O = tag(change, 'O')
|
|
124
|
+
if (O !== undefined && O !== id) continue
|
|
125
|
+
// A level or a membership change is never in a `set` (§11.8): one there is not read.
|
|
126
|
+
if (change.tags.some((t) => t[0] === 'set')) continue
|
|
127
|
+
const field = tag(change, 'field')
|
|
128
|
+
const value = tag(change, 'value')
|
|
129
|
+
if (field === `${FOLLOW_FIELD_PREFIX}${person}`) {
|
|
130
|
+
// Only `P` sets `P`'s level; one signed by anybody else is ignored.
|
|
131
|
+
if (change.pubkey !== person) continue
|
|
132
|
+
if (value === 'all' || value === 'important') acts.push({ event: change, act: 'level', level: value })
|
|
133
|
+
else if (value === '') acts.push({ event: change, act: 'clear' })
|
|
134
|
+
} else if (memberOfField(field) === person) {
|
|
135
|
+
if (value === 'true') acts.push({ event: change, act: 'join' })
|
|
136
|
+
else if (value === 'false' && change.pubkey === person) acts.push({ event: change, act: 'leave' })
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const rank = (a: Act) => (a.act === 'creation' ? 0 : 1)
|
|
140
|
+
return acts.sort((a, b) => rank(a) - rank(b) || byOrder(a.event, b.event) || Number(a.act !== 'leave') - Number(b.act !== 'leave'))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function addressOf(event: Pick<SignedEvent, 'kind' | 'pubkey' | 'tags'>): string | undefined {
|
|
144
|
+
if (event.kind < 30000 || event.kind > 39999) return undefined
|
|
145
|
+
return `${event.kind}:${event.pubkey}:${tag(event, 'd') ?? ''}`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const latest = (events: readonly Event[]): Event | undefined => [...events].sort(byOrder).at(-1)
|
|
149
|
+
|
|
150
|
+
/** Whether the entry names the place: its address, or its id in the `o` form. */
|
|
151
|
+
const names = (entry: readonly string[], address: string): boolean =>
|
|
152
|
+
(entry[0] === 'a' && entry[1] === address) || (entry[0] === 'o' && entry[1] === (fileIdOf(address) ?? dOf(address)))
|
|
153
|
+
|
|
154
|
+
/** Whether a list's or a command's entries mark the place a space: named, the role after an empty third element. */
|
|
155
|
+
function markOf(event: Event, address: string): 'space' | 'plain' | undefined {
|
|
156
|
+
let mark: 'space' | 'plain' | undefined
|
|
157
|
+
for (const entry of event.tags) {
|
|
158
|
+
if (!names(entry, address)) continue
|
|
159
|
+
if (entry[3] === SPACE_ROLE && !entry[2]) mark ??= 'space'
|
|
160
|
+
else mark = 'plain'
|
|
161
|
+
}
|
|
162
|
+
return mark
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Whether the team's current list marks the place one of its spaces (§3.3). A list naming it without the role too keeps it plain. */
|
|
166
|
+
function isSpace(place: Place, listing: readonly Event[]): boolean {
|
|
167
|
+
const state = latest(listing.filter((e) => e.kind === KIND_FOLDER_STATE && tag(e, 'd') === place.team))
|
|
168
|
+
return !!state && markOf(state, place.address) === 'space'
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Which of a team's three kinds the place is. */
|
|
172
|
+
export function placeKindOf(place: Place, listing: readonly Event[] = []): PlaceKind {
|
|
173
|
+
if (place.address.startsWith(`${KIND_TEAM}:`)) return 'chat'
|
|
174
|
+
return isSpace(place, listing) ? 'space' : 'topic'
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* When the place became one of the team's spaces: the earliest `kind:1852`
|
|
179
|
+
* `add` or `move` into the team naming it with the `space` role, since the
|
|
180
|
+
* last command that unmarked it, removed it or moved it out. A list marking
|
|
181
|
+
* it with no such command held falls back to the list's own time, which is
|
|
182
|
+
* no earlier than the mark.
|
|
183
|
+
*/
|
|
184
|
+
function spaceStartOf(place: Place, listing: readonly Event[]): number | undefined {
|
|
185
|
+
let start: number | undefined
|
|
186
|
+
const commands = listing.filter((e) => e.kind === KIND_FOLDER_COMMAND).sort(byOrder)
|
|
187
|
+
for (const command of commands) {
|
|
188
|
+
const op = tag(command, 'op')
|
|
189
|
+
const into = tag(command, 'h') === place.team
|
|
190
|
+
const mark = markOf(command, place.address)
|
|
191
|
+
if (!into) {
|
|
192
|
+
// A move out of the team takes the mark with it.
|
|
193
|
+
if (op === 'move' && tag(command, 'from') === place.team && mark) start = undefined
|
|
194
|
+
continue
|
|
195
|
+
}
|
|
196
|
+
if (op === 'remove' && mark) start = undefined
|
|
197
|
+
else if (op === 'set' && !mark) start = undefined
|
|
198
|
+
else if ((op === 'add' || op === 'move' || op === 'set') && mark) {
|
|
199
|
+
if (mark === 'plain') start = undefined
|
|
200
|
+
else start ??= command.created_at
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (start !== undefined) return start
|
|
204
|
+
return latest(listing.filter((e) => e.kind === KIND_FOLDER_STATE && tag(e, 'd') === place.team))?.created_at
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Whether the team's current roster lists the person. */
|
|
208
|
+
function onRoster(team: string, person: string, roster: readonly Event[]): Event | undefined {
|
|
209
|
+
const list = latest(roster.filter((e) => e.kind === KIND_ROSTER && tag(e, 'd') === team))
|
|
210
|
+
return list?.tags.some((t) => t[0] === 'p' && t[1] === person) ? list : undefined
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* When the team reached a person its roster lists: the earliest stored
|
|
215
|
+
* `kind:9000` or `kind:9021` naming them on the team since their last
|
|
216
|
+
* `kind:9001` or `kind:9022` (a later `kind:9000` changing their role is not
|
|
217
|
+
* a join), or the `kind:9007` when they made the team. A roster keeps no time
|
|
218
|
+
* per person, so with none of those held the roster's own time stands in: no
|
|
219
|
+
* earlier than their join, so nothing older lights.
|
|
220
|
+
*/
|
|
221
|
+
function joinedTeamAt(team: string, person: string, roster: readonly Event[], list: Event): number {
|
|
222
|
+
const onTeam = roster.filter((e) => tag(e, 'h') === team).sort(byOrder)
|
|
223
|
+
const namesPerson = (e: Event) => e.tags.some((t) => t[0] === 'p' && t[1] === person)
|
|
224
|
+
let since: number | undefined
|
|
225
|
+
for (const e of onTeam) {
|
|
226
|
+
const left = (e.kind === KIND_REMOVE_USER && namesPerson(e)) || (e.kind === KIND_LEAVE && e.pubkey === person)
|
|
227
|
+
const joined =
|
|
228
|
+
(e.kind === KIND_PUT_USER && namesPerson(e)) || (e.kind === KIND_JOIN && e.pubkey === person) || (e.kind === KIND_CREATE_TEAM && e.pubkey === person)
|
|
229
|
+
if (left) since = undefined
|
|
230
|
+
else if (joined) since ??= e.created_at
|
|
231
|
+
}
|
|
232
|
+
return since ?? list.created_at
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The team's own start: its `kind:9007`, when held. */
|
|
236
|
+
function teamStartOf(team: string, roster: readonly Event[]): number | undefined {
|
|
237
|
+
return roster.find((e) => e.kind === KIND_CREATE_TEAM && tag(e, 'h') === team)?.created_at
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Whether a person is in a place, at what level and since when (§11.8
|
|
242
|
+
* *Places and following*). Pure: `facts` are the events {@link placeFilters}
|
|
243
|
+
* returned, and the person's private teams list.
|
|
244
|
+
*/
|
|
245
|
+
export function followingOf(place: Place, person: string, facts: PlaceFacts): Following {
|
|
246
|
+
if (!PUBKEY.test(person)) throw new Error(`not a lowercase hex pubkey: ${JSON.stringify(person)}`)
|
|
247
|
+
const kind = placeKindOf(place, facts.listing)
|
|
248
|
+
const out: Following = { kind, in: false, ways: [] }
|
|
249
|
+
if (facts.archived) return out
|
|
250
|
+
|
|
251
|
+
const starts: number[] = []
|
|
252
|
+
const acts = actsOf(place, person, facts.events)
|
|
253
|
+
const lastLeave = acts.map((a) => a.act).lastIndexOf('leave')
|
|
254
|
+
// An Add after a leave names it with `prev`, so the relay's order holds whatever the two clocks said (§11.8).
|
|
255
|
+
const leaveId = acts[lastLeave]?.event.id
|
|
256
|
+
const named = acts.slice(0, Math.max(lastLeave, 0)).filter((a) => a.act === 'join' && leaveId !== undefined && tag(a.event, 'prev') === leaveId)
|
|
257
|
+
const after = [...named, ...acts.slice(lastLeave + 1)]
|
|
258
|
+
// 1. A level chosen since the last leave, and not cleared since; changing it keeps its start.
|
|
259
|
+
let chosen: { level: Level; since: number; allSince?: number } | undefined
|
|
260
|
+
for (const a of after) {
|
|
261
|
+
if (a.act === 'level') {
|
|
262
|
+
const allSince = a.level === 'all' ? (chosen?.allSince ?? a.event.created_at) : undefined
|
|
263
|
+
chosen = { level: a.level!, since: chosen?.since ?? a.event.created_at, ...(allSince !== undefined ? { allSince } : {}) }
|
|
264
|
+
} else if (a.act === 'clear') chosen = undefined
|
|
265
|
+
}
|
|
266
|
+
if (chosen) {
|
|
267
|
+
out.ways.push('level')
|
|
268
|
+
starts.push(chosen.since)
|
|
269
|
+
}
|
|
270
|
+
// 2. Joined, or added, since the last leave. An Add chooses no level.
|
|
271
|
+
const joined = after.find((a) => a.act === 'join')
|
|
272
|
+
if (joined) {
|
|
273
|
+
out.ways.push('added')
|
|
274
|
+
starts.push(joined.event.created_at)
|
|
275
|
+
}
|
|
276
|
+
// 3. Made it: the first record orders before everything, so any leave ends it.
|
|
277
|
+
const made = after.find((a) => a.act === 'creation')
|
|
278
|
+
if (made) {
|
|
279
|
+
out.ways.push('author')
|
|
280
|
+
starts.push(made.event.created_at)
|
|
281
|
+
}
|
|
282
|
+
// 4. A team's default, unless the person's private list turned it off. A topic a team leads reaches nobody.
|
|
283
|
+
const off = new Set(facts.teams?.off ?? [])
|
|
284
|
+
const id = dOf(place.address)
|
|
285
|
+
if (kind !== 'topic' && !off.has(id)) {
|
|
286
|
+
const roster = facts.roster ?? []
|
|
287
|
+
const list = onRoster(place.team, person, roster)
|
|
288
|
+
const followed = facts.teams?.teams[place.team]
|
|
289
|
+
let reached: number | undefined
|
|
290
|
+
if (list) reached = joinedTeamAt(place.team, person, roster, list)
|
|
291
|
+
else if (kind === 'space' && followed !== undefined) reached = Math.floor(followed / 1000)
|
|
292
|
+
if (reached !== undefined) {
|
|
293
|
+
const cameIn = kind === 'space' ? spaceStartOf(place, facts.listing ?? []) : teamStartOf(place.team, roster)
|
|
294
|
+
out.ways.push('team')
|
|
295
|
+
starts.push(Math.max(reached, cameIn ?? reached))
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
if (out.ways.length === 0) return out
|
|
300
|
+
return { ...out, in: true, level: chosen?.level ?? 'important', since: Math.min(...starts), ...(chosen?.allSince !== undefined ? { allSince: chosen.allSince } : {}) }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* The filters that read what {@link followingOf} needs for one place: its
|
|
305
|
+
* root and changes, the team's roster, the team's list and the commands
|
|
306
|
+
* naming the place, and the person's teams list. A topic's or space's
|
|
307
|
+
* conversation is the app's own read (see `streamOf`); a team's chat is its
|
|
308
|
+
* general stream.
|
|
309
|
+
*/
|
|
310
|
+
export function placeFilters(place: Place, person: string): Filter[] {
|
|
311
|
+
if (!PUBKEY.test(person)) throw new Error(`not a lowercase hex pubkey: ${JSON.stringify(person)}`)
|
|
312
|
+
if (!FILE_ADDRESS.test(place.address)) throw new Error(`not a place address: ${JSON.stringify(place.address)}`)
|
|
313
|
+
if (!FOLDER_ID.test(place.team)) throw new Error(`not a team id (lowercase UUID v4): ${JSON.stringify(place.team)}`)
|
|
314
|
+
const [kind, author, d] = [Number(place.address.split(':')[0]), place.address.split(':')[1], dOf(place.address)]
|
|
315
|
+
const id = fileIdOf(place.address)
|
|
316
|
+
return [
|
|
317
|
+
{ kinds: [KIND_CHANGE], '#a': [place.address] },
|
|
318
|
+
...(kind === KIND_TEAM ? [] : [{ kinds: [kind], authors: [author], '#d': [d] }]),
|
|
319
|
+
{ kinds: [KIND_PUT_USER, KIND_REMOVE_USER, KIND_JOIN, KIND_LEAVE, KIND_CREATE_TEAM], '#h': [place.team] },
|
|
320
|
+
{ kinds: [KIND_ROSTER], '#d': [place.team] },
|
|
321
|
+
...(kind === KIND_TEAM
|
|
322
|
+
? []
|
|
323
|
+
: [
|
|
324
|
+
{ kinds: [KIND_FOLDER_STATE], '#d': [place.team] },
|
|
325
|
+
{ kinds: [KIND_FOLDER_COMMAND], '#a': [place.address] },
|
|
326
|
+
...(id !== undefined ? [{ kinds: [KIND_FOLDER_COMMAND], '#o': [id] }] : []),
|
|
327
|
+
]),
|
|
328
|
+
teamsFilter(person),
|
|
329
|
+
]
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ── What is unread on a place ───────────────────────────────────────────────
|
|
333
|
+
|
|
334
|
+
type Message = Pick<SignedEvent, 'id' | 'pubkey' | 'kind' | 'created_at' | 'tags' | 'content'>
|
|
335
|
+
|
|
336
|
+
/** Who is judging a place's stream, and on what terms. */
|
|
337
|
+
export interface PlaceJudge {
|
|
338
|
+
/** The stream's context (§11.1): the topic's or space's address, or the team's uuid for its chat. */
|
|
339
|
+
stream: string
|
|
340
|
+
/** The person reading. */
|
|
341
|
+
me: string
|
|
342
|
+
/** {@link followingOf} for `me` on the place. */
|
|
343
|
+
following: Following
|
|
344
|
+
/** Whether `me` muted the place (`estiva:muted:v1`): a mute already kept still lights only mentions. */
|
|
345
|
+
muted?: boolean
|
|
346
|
+
/** For a message with no marker and no start to bound it, the earliest `created_at` that counts (§11.6). */
|
|
347
|
+
floor?: number
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The unread messages on a place, oldest first per conversation (§11.8 *What
|
|
352
|
+
* is unread on a place*). `messages` is the place's stream: `streamOf` for a
|
|
353
|
+
* topic or space, the team's general stream for its chat.
|
|
354
|
+
*
|
|
355
|
+
* At **Important** a new conversation lights, and a reply in a conversation
|
|
356
|
+
* `me` is in — wrote its root or a reply, or was mentioned in it — from the
|
|
357
|
+
* moment they were. At **All** every message lights from the moment they
|
|
358
|
+
* chose All (`allSince`), and Important's rule before it. A mention of `me` lights
|
|
359
|
+
* at any level, and when they are not in. A file the place lists is judged
|
|
360
|
+
* at All the same way, by passing its own stream and context with this
|
|
361
|
+
* following.
|
|
362
|
+
*/
|
|
363
|
+
export function unreadOnPlace<E extends Message>(messages: readonly E[], merged: Readonly<Record<string, number>>, judge: PlaceJudge): E[] {
|
|
364
|
+
const { roots, replies } = groupThreads(messages)
|
|
365
|
+
const out: E[] = []
|
|
366
|
+
const conversation = (root: E | undefined, list: readonly E[], rootId: string) => {
|
|
367
|
+
const all = root ? [root, ...list] : [...list]
|
|
368
|
+
const inSince = all.find((m) => m.pubkey === judge.me || peopleNamedInBody(m.content).has(judge.me))?.created_at
|
|
369
|
+
if (root && isUnreadOnPlace(root, undefined, merged, judge, inSince)) out.push(root)
|
|
370
|
+
for (const reply of list) if (isUnreadOnPlace(reply, rootId, merged, judge, inSince)) out.push(reply)
|
|
371
|
+
}
|
|
372
|
+
for (const root of roots) conversation(root, replies[root.id] ?? [], root.id)
|
|
373
|
+
const held = new Set(roots.map((r) => r.id))
|
|
374
|
+
for (const [root, list] of Object.entries(replies)) if (!held.has(root)) conversation(undefined, list, root)
|
|
375
|
+
return out
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Whether one message on a place is unread. `root` is its conversation's root
|
|
380
|
+
* id when it is a reply; `inConversationSince`, the second `me` came into
|
|
381
|
+
* that conversation (wrote in it or was mentioned there), or undefined when
|
|
382
|
+
* they never did — then a reply lights at Important only by a mention.
|
|
383
|
+
*/
|
|
384
|
+
export function isUnreadOnPlace(
|
|
385
|
+
message: Message,
|
|
386
|
+
root: string | undefined,
|
|
387
|
+
merged: Readonly<Record<string, number>>,
|
|
388
|
+
judge: PlaceJudge,
|
|
389
|
+
inConversationSince: number | undefined,
|
|
390
|
+
): boolean {
|
|
391
|
+
if (message.pubkey === judge.me) return false
|
|
392
|
+
const { following } = judge
|
|
393
|
+
const mentioned = peopleNamedInBody(message.content).has(judge.me)
|
|
394
|
+
const started = following.in && (following.since === undefined || message.created_at >= following.since)
|
|
395
|
+
const levelLights =
|
|
396
|
+
(following.level === 'all' && message.created_at >= (following.allSince ?? following.since ?? 0)) ||
|
|
397
|
+
root === undefined ||
|
|
398
|
+
(inConversationSince !== undefined && message.created_at >= inConversationSince)
|
|
399
|
+
if (!mentioned && (judge.muted || !started || !levelLights)) return false
|
|
400
|
+
const thread = root === undefined ? undefined : threadContext(root)
|
|
401
|
+
const marker = thread === undefined ? streamMarkerOf(merged, judge.stream) : effectiveReadAt(merged, thread, judge.stream)
|
|
402
|
+
if (marker !== undefined) return message.created_at > marker
|
|
403
|
+
if (thread !== undefined && belowReplyFloor(message.created_at, merged[REPLY_FLOOR_CONTEXT])) return false
|
|
404
|
+
if (started && following.since !== undefined) return true
|
|
405
|
+
return judge.floor === undefined || message.created_at >= judge.floor
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ── A level: `follow:<P>`, signed by `P` alone ──────────────────────────────
|
|
409
|
+
|
|
410
|
+
/** The level field for a person: `follow:<pubkey>`. */
|
|
411
|
+
export function followField(pubkey: string): string {
|
|
412
|
+
if (!PUBKEY.test(pubkey)) throw new Error(`not a lowercase hex pubkey: ${JSON.stringify(pubkey)}`)
|
|
413
|
+
return `${FOLLOW_FIELD_PREFIX}${pubkey}`
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* The level change (§11.8 *The level change*): `P` chooses All or Important
|
|
418
|
+
* on a place, or `''` to go back to the default. Signed by `P`, for `P`: the
|
|
419
|
+
* relay refuses, and every reader ignores, one signed by anybody else. Never
|
|
420
|
+
* in a `set`, no `prev`. Tag order: `a`, `[O]`, `field`, `value`, `h`, `ts`,
|
|
421
|
+
* `p`.
|
|
422
|
+
*
|
|
423
|
+
* Not following is never public: turning a team's default off goes in the
|
|
424
|
+
* private teams list ({@link serializeTeamsBlob}), and leaving a place one
|
|
425
|
+
* joined is {@link buildMembershipChange}'s leave.
|
|
426
|
+
*/
|
|
427
|
+
export function buildLevelChange(
|
|
428
|
+
pubkey: string,
|
|
429
|
+
createdAtMs: number,
|
|
430
|
+
args: { place: string; folder: string; level: Level | ''; note?: string },
|
|
431
|
+
): UnsignedEvent {
|
|
432
|
+
const field = followField(pubkey)
|
|
433
|
+
if (!FILE_ADDRESS.test(args.place)) throw new Error(`not a place address: ${JSON.stringify(args.place)}`)
|
|
434
|
+
if (!FOLDER_ID.test(args.folder)) throw new Error(`not a Folder id (lowercase UUID v4): ${JSON.stringify(args.folder)}`)
|
|
435
|
+
if (args.level !== 'all' && args.level !== 'important' && args.level !== '') throw new Error(`not a level: ${JSON.stringify(args.level)}`)
|
|
436
|
+
if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new Error(`not epoch milliseconds: ${createdAtMs}`)
|
|
437
|
+
const id = fileIdOf(args.place)
|
|
438
|
+
return {
|
|
439
|
+
pubkey,
|
|
440
|
+
created_at: Math.floor(createdAtMs / 1000),
|
|
441
|
+
kind: KIND_CHANGE,
|
|
442
|
+
tags: [
|
|
443
|
+
['a', args.place],
|
|
444
|
+
...(id !== undefined ? [['O', id]] : []),
|
|
445
|
+
['field', field],
|
|
446
|
+
['value', args.level],
|
|
447
|
+
['h', args.folder],
|
|
448
|
+
['ts', String(createdAtMs)],
|
|
449
|
+
['p', pubkey],
|
|
450
|
+
],
|
|
451
|
+
content: args.note ?? (args.level === 'all' ? 'All' : args.level === 'important' ? 'Important' : 'Default'),
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ── The teams a person follows, and their opt-outs: private (§11.8, §12) ────
|
|
456
|
+
|
|
457
|
+
/** The `d` of the person's teams list. */
|
|
458
|
+
export const TEAMS_D_TAG = 'estiva:teams:v1'
|
|
459
|
+
|
|
460
|
+
/** The decrypted teams list: the teams followed, each from when, and the places whose default is off. */
|
|
461
|
+
export interface TeamsList {
|
|
462
|
+
v: 1
|
|
463
|
+
updatedAt: number
|
|
464
|
+
/** Team uuid → epoch ms the person follows it from. */
|
|
465
|
+
teams: Record<string, number>
|
|
466
|
+
/** Places whose team default is off: a topic or space by its `d`, a team's chat by the team's uuid. */
|
|
467
|
+
off: string[]
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const isPlaceId = (id: unknown): id is string => typeof id === 'string' && id.length > 0 && id.length <= 256 && !/\s/.test(id)
|
|
471
|
+
const isEpochMs = (ms: unknown): ms is number => typeof ms === 'number' && Number.isSafeInteger(ms) && ms >= 0
|
|
472
|
+
|
|
473
|
+
/** The teams list from its decrypted content, or undefined when it is not a v1 list. Entries that are not well formed are dropped. */
|
|
474
|
+
export function parseTeamsBlob(plaintext: string): TeamsList | undefined {
|
|
475
|
+
let value: unknown
|
|
476
|
+
try {
|
|
477
|
+
value = JSON.parse(plaintext)
|
|
478
|
+
} catch {
|
|
479
|
+
return undefined
|
|
480
|
+
}
|
|
481
|
+
if (!value || typeof value !== 'object') return undefined
|
|
482
|
+
const { v, updatedAt, teams, off } = value as Record<string, unknown>
|
|
483
|
+
if (v !== 1 || !isEpochMs(updatedAt)) return undefined
|
|
484
|
+
if (!teams || typeof teams !== 'object' || Array.isArray(teams) || !Array.isArray(off)) return undefined
|
|
485
|
+
const kept = Object.entries(teams as Record<string, unknown>).filter((e): e is [string, number] => FOLDER_ID.test(e[0]) && isEpochMs(e[1]))
|
|
486
|
+
return { v: 1, updatedAt, teams: Object.fromEntries(kept.sort(([a], [b]) => (a < b ? -1 : 1))), off: [...new Set(off.filter(isPlaceId))].sort() }
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** The plaintext to encrypt to self: teams and opt-outs sorted, so equal lists are equal bytes. */
|
|
490
|
+
export function serializeTeamsBlob(list: Pick<TeamsList, 'teams' | 'off'>, updatedAt: number): string {
|
|
491
|
+
const teams = Object.entries(list.teams).filter(([team, since]) => FOLDER_ID.test(team) && isEpochMs(since))
|
|
492
|
+
return JSON.stringify({
|
|
493
|
+
v: 1,
|
|
494
|
+
updatedAt,
|
|
495
|
+
teams: Object.fromEntries(teams.sort(([a], [b]) => (a < b ? -1 : 1))),
|
|
496
|
+
off: [...new Set(list.off.filter(isPlaceId))].sort(),
|
|
497
|
+
})
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* The unsigned `kind:30078` holding the encrypted teams list. Whole blob, last
|
|
502
|
+
* write wins (§12.3): a writer reads the current list, changes it, and writes
|
|
503
|
+
* all of it.
|
|
504
|
+
*/
|
|
505
|
+
export function buildTeamsEvent(pubkey: string, createdAtMs: number, ciphertext: string): UnsignedEvent {
|
|
506
|
+
return {
|
|
507
|
+
pubkey,
|
|
508
|
+
created_at: Math.floor(createdAtMs / 1000),
|
|
509
|
+
kind: KIND_APP_DATA,
|
|
510
|
+
tags: [
|
|
511
|
+
['d', TEAMS_D_TAG],
|
|
512
|
+
['t', APPDATA_TAG],
|
|
513
|
+
],
|
|
514
|
+
content: ciphertext,
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** The filter for the person's teams list. */
|
|
519
|
+
export function teamsFilter(pubkey: string): Filter {
|
|
520
|
+
return { kinds: [KIND_APP_DATA], authors: [pubkey], '#d': [TEAMS_D_TAG], limit: 1 }
|
|
521
|
+
}
|
package/src/readState.ts
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
*/
|
|
25
25
|
import type { SignedEvent, UnsignedEvent } from '@estiva-app/protocol'
|
|
26
26
|
import { FILE_ADDRESS as ADDRESS_RE, FOLDER_ID as UUID_RE, KIND_APP_DATA } from './kinds.js'
|
|
27
|
-
import { fileIdOf, isFileId } from '@estiva-app/protocol'
|
|
27
|
+
import { fileIdFormOf, fileIdOf, isFileId } from '@estiva-app/protocol'
|
|
28
28
|
import type { QueryFn } from './decorations.js'
|
|
29
29
|
|
|
30
30
|
/** NIP-RS's own `t` tag. */
|
|
@@ -119,6 +119,23 @@ export function fileIdContext(id: string | null | undefined): string | undefined
|
|
|
119
119
|
|
|
120
120
|
const FILE_ID_PREFIX = 'file:'
|
|
121
121
|
|
|
122
|
+
/**
|
|
123
|
+
* The markers a read of a file writes, for `advanceContexts`: under
|
|
124
|
+
* `file:<d>` once the relay keeps the file's type in order (`inOrder`,
|
|
125
|
+
* `RelayFileReads.inOrder`), and under its address too, while an app that
|
|
126
|
+
* reads only the address key remains (§11.6, *added 2026-11-02*). Before the
|
|
127
|
+
* switch, under its address alone. Empty for anything that is not a file's
|
|
128
|
+
* address.
|
|
129
|
+
*
|
|
130
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-files-unread-state-is-keyed-file-and-its-id.md
|
|
131
|
+
*/
|
|
132
|
+
export function fileReadMarkers(address: string, at: number, inOrder: readonly string[] = []): Record<string, number> {
|
|
133
|
+
const byAddress = fileContext(address)
|
|
134
|
+
if (byAddress === undefined) return {}
|
|
135
|
+
const byId = fileIdContext(fileIdFormOf(inOrder, address)?.id)
|
|
136
|
+
return byId === undefined ? { [byAddress]: at } : { [byId]: at, [byAddress]: at }
|
|
137
|
+
}
|
|
138
|
+
|
|
122
139
|
/**
|
|
123
140
|
* A stream's marker. For a file, the later of its address key and its
|
|
124
141
|
* `file:<d>` key (§11.1, §11.6, *added 2026-11-02*): either one is a marker,
|
package/src/strength.ts
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
* reply `e` — a `kind:9` with any `e`, a `kind:1111` with a lowercase `e` that
|
|
28
28
|
* differs from its `E` — is not a comment of its own, whatever `a` it carries.
|
|
29
29
|
*/
|
|
30
|
-
import { decodeNaddr, decodeNpub, findNaddrs, findNostrUris, FILE_KINDS, fileIdOf, pointerToAddress, type NostrTag, type SignedEvent } from '@estiva-app/protocol'
|
|
30
|
+
import { decodeNaddr, decodeNpub, findNaddrs, findNostrUris, FILE_KINDS, fileIdFormOf, fileIdOf, pointerToAddress, type NostrTag, type SignedEvent } from '@estiva-app/protocol'
|
|
31
31
|
import { KIND_COMMENT } from './kinds.js'
|
|
32
32
|
|
|
33
33
|
type Tagged = Pick<SignedEvent, 'kind' | 'tags'>
|
|
@@ -219,11 +219,17 @@ export function threadStrength(root: Readable | undefined, replies: readonly Rea
|
|
|
219
219
|
* §6.4: a writer MUST NOT put an address in a `kind:1111`'s `a` that the body
|
|
220
220
|
* does not name, unless it is the `A` — which is what keeps the mention row
|
|
221
221
|
* readable without decoding the body.
|
|
222
|
+
*
|
|
223
|
+
* A file whose type the relay keeps in order (`inOrder`) earns an `o` with
|
|
224
|
+
* its id after its `a` (§6.4).
|
|
222
225
|
*/
|
|
223
|
-
export function referenceTagsFor(body: string, own = ''): NostrTag[] {
|
|
226
|
+
export function referenceTagsFor(body: string, own = '', inOrder: readonly string[] = []): NostrTag[] {
|
|
224
227
|
const addresses = namedInBody(body)
|
|
225
228
|
addresses.delete(own)
|
|
226
|
-
return [...addresses].
|
|
229
|
+
return [...addresses].flatMap((a) => {
|
|
230
|
+
const byId = fileIdFormOf(inOrder, a)
|
|
231
|
+
return byId ? [['a', a], ['o', byId.id]] : [['a', a]]
|
|
232
|
+
})
|
|
227
233
|
}
|
|
228
234
|
|
|
229
235
|
/** The most `p` tags a message carries — Buzz's cap, and `buildMessage`'s. */
|