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