@estiva-app/conversation 0.1.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +42 -0
  4. package/dist/builders.d.ts +73 -0
  5. package/dist/builders.d.ts.map +1 -0
  6. package/dist/builders.js +110 -0
  7. package/dist/builders.js.map +1 -0
  8. package/dist/decorations.d.ts +88 -0
  9. package/dist/decorations.d.ts.map +1 -0
  10. package/dist/decorations.js +133 -0
  11. package/dist/decorations.js.map +1 -0
  12. package/dist/drafts.d.ts +74 -0
  13. package/dist/drafts.d.ts.map +1 -0
  14. package/dist/drafts.js +111 -0
  15. package/dist/drafts.js.map +1 -0
  16. package/dist/edits.d.ts +76 -0
  17. package/dist/edits.d.ts.map +1 -0
  18. package/dist/edits.js +123 -0
  19. package/dist/edits.js.map +1 -0
  20. package/dist/index.d.ts +25 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +25 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/kinds.d.ts +17 -0
  25. package/dist/kinds.d.ts.map +1 -0
  26. package/dist/kinds.js +22 -0
  27. package/dist/kinds.js.map +1 -0
  28. package/dist/order.d.ts +24 -0
  29. package/dist/order.d.ts.map +1 -0
  30. package/dist/order.js +21 -0
  31. package/dist/order.js.map +1 -0
  32. package/dist/reactions.d.ts +93 -0
  33. package/dist/reactions.d.ts.map +1 -0
  34. package/dist/reactions.js +99 -0
  35. package/dist/reactions.js.map +1 -0
  36. package/dist/strength.d.ts +104 -0
  37. package/dist/strength.d.ts.map +1 -0
  38. package/dist/strength.js +166 -0
  39. package/dist/strength.js.map +1 -0
  40. package/dist/threads.d.ts +54 -0
  41. package/dist/threads.d.ts.map +1 -0
  42. package/dist/threads.js +70 -0
  43. package/dist/threads.js.map +1 -0
  44. package/package.json +56 -0
  45. package/src/builders.ts +133 -0
  46. package/src/decorations.ts +187 -0
  47. package/src/drafts.ts +135 -0
  48. package/src/edits.ts +139 -0
  49. package/src/index.ts +74 -0
  50. package/src/kinds.ts +24 -0
  51. package/src/order.ts +38 -0
  52. package/src/reactions.ts +151 -0
  53. package/src/strength.ts +170 -0
  54. package/src/threads.ts +104 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Writing a comment and a reply — SPEC §6.4 — and which controls to offer
3
+ * on a message, §6.5.
4
+ *
5
+ * Chat, an edit, a reaction and a deletion are `@estiva-app/protocol`'s
6
+ * `buildMessage`, `buildEdit`, `buildReaction` and `buildDeletion`, which are
7
+ * already Buzz-shaped and byte-pinned. What is conversation-specific is the
8
+ * NIP-22 pair below, whose shape the SPEC decided rather than Buzz.
9
+ */
10
+ import { imetaTag, toNostrSeconds, type Imeta, type NostrTag, type UnsignedEvent } from '@estiva-app/protocol'
11
+ import { KIND_COMMENT } from './kinds.js'
12
+
13
+ const FOLDER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
14
+
15
+ /**
16
+ * A `kind:1111` is channel-scoped when it carries an `h` and **global when it
17
+ * does not**, and the relay accepts both — so a comment without one is stored
18
+ * world-readable however private its object. Refused here, loudly.
19
+ */
20
+ function assertFolder(folder: string): void {
21
+ if (!FOLDER_ID.test(folder)) throw new Error(`not a Folder id (lowercase UUID v4): ${JSON.stringify(folder)}`)
22
+ }
23
+
24
+ /** `<kind>:<pubkey>:<d>` → the `K` and `P` it already carries. */
25
+ function kindAndAuthor(address: string): [string, string] {
26
+ const [kind, author] = address.split(':')
27
+ if (!kind || !author) throw new Error(`not an address: ${JSON.stringify(address)}`)
28
+ return [kind, author]
29
+ }
30
+
31
+ /**
32
+ * A top-level comment on an object. Tag order: `A`, `K`, `P`, `a`, `k`, `p`,
33
+ * `[block]`, `h`, `ts`, `[imeta…]`, then `tags`.
34
+ *
35
+ * Uppercase and lowercase name the same object, as NIP-22 says for a
36
+ * top-level comment. `K` and `P` come from the address, so a caller cannot
37
+ * state a kind that contradicts its own `A`. `block` is SPEC §13.6: which part
38
+ * of the object, when the author was looking at one. `tags` is for what the
39
+ * body earns — {@link referenceTagsFor} and {@link mentionTagsFor} — and
40
+ * nothing else: an `a` there that the body does not name breaks §6.4.
41
+ */
42
+ export function buildComment(
43
+ pubkey: string,
44
+ createdAtMs: number,
45
+ args: { about: string; folder: string; body: string; blockId?: string; files?: readonly Imeta[]; tags?: readonly NostrTag[] },
46
+ ): UnsignedEvent {
47
+ assertFolder(args.folder)
48
+ const [kind, author] = kindAndAuthor(args.about)
49
+ return {
50
+ pubkey,
51
+ created_at: toNostrSeconds(createdAtMs),
52
+ kind: KIND_COMMENT,
53
+ tags: [
54
+ ['A', args.about],
55
+ ['K', kind],
56
+ ['P', author],
57
+ ['a', args.about],
58
+ ['k', kind],
59
+ ['p', author],
60
+ ...(args.blockId ? [['block', args.blockId]] : []),
61
+ ['h', args.folder],
62
+ ['ts', String(Math.floor(createdAtMs))],
63
+ ...(args.files ?? []).map(imetaTag),
64
+ ...(args.tags ?? []),
65
+ ],
66
+ content: args.body,
67
+ }
68
+ }
69
+
70
+ /** The top-level comment a reply answers. */
71
+ export interface CommentRef {
72
+ /** Its event id. */
73
+ id: string
74
+ /** The object its thread is about: its `A`. */
75
+ anchor: string
76
+ /**
77
+ * Its author. Undefined when the comment is outside the read; the reply
78
+ * then carries no `p`, because a wrong one notifies the wrong person.
79
+ */
80
+ author?: string
81
+ }
82
+
83
+ /**
84
+ * A reply to a comment — §6.4 *Replies*, C16. Tag order: `A`, `K`, `P`, `e`,
85
+ * `k`, `[p]`, `h`, `ts`, `[imeta…]`, then `tags`.
86
+ *
87
+ * **Flat, one level deep**: `e` names the thread's top-level comment, never
88
+ * another reply. **No lowercase `a`** for the object: NIP-22 reads it as the
89
+ * parent, so it would claim the reply is itself a top-level comment. The reply
90
+ * is found by `#e` on the comment.
91
+ */
92
+ export function buildReply(
93
+ pubkey: string,
94
+ createdAtMs: number,
95
+ args: { comment: CommentRef; folder: string; body: string; files?: readonly Imeta[]; tags?: readonly NostrTag[] },
96
+ ): UnsignedEvent {
97
+ assertFolder(args.folder)
98
+ const [kind, author] = kindAndAuthor(args.comment.anchor)
99
+ const earned = (args.tags ?? []).filter((t) => !(t[0] === 'a' && t[1] === args.comment.anchor))
100
+ return {
101
+ pubkey,
102
+ created_at: toNostrSeconds(createdAtMs),
103
+ kind: KIND_COMMENT,
104
+ tags: [
105
+ ['A', args.comment.anchor],
106
+ ['K', kind],
107
+ ['P', author],
108
+ ['e', args.comment.id],
109
+ ['k', String(KIND_COMMENT)],
110
+ ...(args.comment.author ? [['p', args.comment.author]] : []),
111
+ ['h', args.folder],
112
+ ['ts', String(Math.floor(createdAtMs))],
113
+ ...(args.files ?? []).map(imetaTag),
114
+ ...earned,
115
+ ],
116
+ content: args.body,
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Whether to offer Edit and Delete on a message — §6.5, decided 2026-09-29
122
+ * (C14). Offered on the viewer's own message, and on one whose author's
123
+ * profile declares `bot: true` (the viewer may be its NIP-OA owner, whom the
124
+ * relay accepts). Not on another human's: the relay refuses that every time.
125
+ *
126
+ * `authorIsBot` is the author's `kind:0` `bot` field: `undefined` when the
127
+ * profile could not be read, which offers the control — never wrong, since
128
+ * the relay adjudicates and the app surfaces a refusal in its words.
129
+ */
130
+ export function offersEditAndDelete(args: { viewer: string | null | undefined; author: string; authorIsBot: boolean | undefined }): boolean {
131
+ if (args.viewer && args.viewer === args.author) return true
132
+ return args.authorIsBot !== false
133
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * What has been done to a set of messages since they were written — edits,
3
+ * reactions, resolutions — in one request, read by `#e`.
4
+ *
5
+ * Moved here from `@estiva-app/interop` (CON-5), where it was
6
+ * `commentDecorationsOf` since CON-8. It is a second round trip by nature:
7
+ * an edit, a reaction and a resolution name the *message* by `e`, never the
8
+ * file or the channel, so they cannot be asked for until the message ids are
9
+ * known.
10
+ */
11
+ import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, type SignedEvent } from '@estiva-app/protocol'
12
+ import { editTargetOf, foldEdits, type EditFold } from './edits.js'
13
+ import { KIND_ASSERTION, KIND_EDIT, KIND_REACTION } from './kinds.js'
14
+ import { reactionEventsOf, reactionHorizon, reactionTargetOf, type ReactionEvent } from './reactions.js'
15
+
16
+ /**
17
+ * How a caller reads the relay: filters in, events out. The environment's
18
+ * one touch, injected — this package opens no socket and holds no credential.
19
+ * Structurally the same as `@estiva-app/interop`'s `QueryFn`.
20
+ */
21
+ export type QueryFn = (filters: Record<string, unknown>[]) => Promise<SignedEvent[]>
22
+
23
+ /** A `kind:9101` resolution assertion on a message (PEEK-128). */
24
+ export interface Resolution {
25
+ id: string
26
+ action: 'resolved' | 'reopened'
27
+ by: string
28
+ at: number
29
+ /** The assertion's free text, when it carried one. */
30
+ message?: string
31
+ /** The reply that carried the resolution, when the writer named one. */
32
+ supportingEventId?: string
33
+ }
34
+
35
+ /** What has been done to one message since it was written. */
36
+ export interface Decoration {
37
+ /** Its edits, folded (§6.8). Absent when nobody edited it. */
38
+ edit?: EditFold
39
+ /** Its reactions, one per `(pubkey, emoji)`, oldest first. Empty inside the horizon means none. */
40
+ reactions: ReactionEvent[]
41
+ /** Oldest first; the last one is the current state. Empty means never resolved. */
42
+ resolutions: Resolution[]
43
+ }
44
+
45
+ /** The answer of {@link decorationsOf}. */
46
+ export interface Decorations {
47
+ /** Keyed by message id. A target nothing happened to is present, with nothing in it. */
48
+ byId: Record<string, Decoration>
49
+ /**
50
+ * How many targets were **not** asked about reactions, because they fell
51
+ * outside the horizon. §6.6 makes reporting this a MUST: a cap nobody can
52
+ * see is indistinguishable from "nobody reacted".
53
+ */
54
+ reactionTargetsOmitted: number
55
+ /**
56
+ * Whether a reaction read came back at the relay's page ceiling, so some
57
+ * reaction *events* may be missing. §6.6: a reader that caps events MUST
58
+ * report the cut as it reports the target cut.
59
+ */
60
+ reactionEventsCut: boolean
61
+ /**
62
+ * Whether an edit and resolution read came back at the page ceiling, so a
63
+ * message may show an older body or state than the relay holds.
64
+ */
65
+ editEventsCut: boolean
66
+ }
67
+
68
+ /** Ids per `#e` filter. A comfortable fraction of the relay's page, so one filter's answer is rarely cut. */
69
+ const TARGETS_PER_FILTER = 100
70
+
71
+ const chunked = (list: readonly string[]) => {
72
+ const out: string[][] = []
73
+ for (let i = 0; i < list.length; i += TARGETS_PER_FILTER) out.push(list.slice(i, i + TARGETS_PER_FILTER))
74
+ return out
75
+ }
76
+
77
+ const tagValue = (event: SignedEvent, name: string) => event.tags.find((t) => t[0] === name)?.[1]
78
+
79
+ /**
80
+ * Edits, reactions and resolutions for `targets`, in as few requests as the
81
+ * relay allows.
82
+ *
83
+ * - **Edits** fold by §6.8 ({@link foldEdits}): the target is the first 64-hex
84
+ * `e` and no other. Pass each target's `body` so "edited" means the body
85
+ * changed; without it the first edit counts as a change.
86
+ * - **Reactions** have a horizon ({@link reactionHorizon}): the newest 100
87
+ * targets by `at`, one budget across whatever id spaces the caller mixes,
88
+ * the number left out reported. Target is the last 64-hex `e`, empty is `+`,
89
+ * one per `(target, pubkey, emoji)`.
90
+ * - **Resolutions** are `kind:9101` carrying `t=resolution`; the `action` tag
91
+ * is the state, the content the rationale, and an `e` marked `support` names
92
+ * the reply that carried it. The target is the first unmarked `e` naming a
93
+ * target.
94
+ *
95
+ * Edits and resolutions have no horizon: they are one event per change, not
96
+ * one per reader. A refused read is whatever `query` does with one.
97
+ */
98
+ export async function decorationsOf(
99
+ /** `at` is the target's `created_at`, seconds. */
100
+ targets: readonly { id: string; at: number; body?: string }[],
101
+ query: QueryFn,
102
+ ): Promise<Decorations> {
103
+ // Keyed lowercase: every target this reads off a tag is lowercased (`editTargetOf`, `reactionTargetOf`).
104
+ const byId: Record<string, Decoration> = {}
105
+ const unique: { id: string; at: number }[] = []
106
+ for (const t of targets) {
107
+ const id = t.id.toLowerCase()
108
+ if (Object.hasOwn(byId, id)) continue
109
+ byId[id] = { reactions: [], resolutions: [] }
110
+ unique.push({ id, at: t.at })
111
+ }
112
+ if (unique.length === 0) return { byId, reactionTargetsOmitted: 0, reactionEventsCut: false, editEventsCut: false }
113
+
114
+ const { asked, omitted } = reactionHorizon(unique)
115
+ const reactionChunks = chunked(asked)
116
+ const editChunks = chunked(unique.map((t) => t.id))
117
+ const filters: Record<string, unknown>[] = []
118
+ for (const chunk of editChunks) {
119
+ filters.push({ kinds: [KIND_EDIT, KIND_ASSERTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
120
+ }
121
+ for (const chunk of reactionChunks) filters.push({ kinds: [KIND_REACTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
122
+
123
+ const seen = new Set<string>()
124
+ const events: SignedEvent[] = []
125
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
126
+ for (const event of await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))) {
127
+ if (seen.has(event.id)) continue
128
+ seen.add(event.id)
129
+ events.push(event)
130
+ }
131
+ }
132
+
133
+ // `hasOwn`, not `in`: an `e` of `constructor` is anybody's to write.
134
+ const ours = (id: string | undefined): id is string => id !== undefined && Object.hasOwn(byId, id)
135
+
136
+ const bodies = targets.flatMap((t) => (t.body === undefined ? [] : [{ id: t.id, body: t.body }]))
137
+ for (const [target, fold] of Object.entries(foldEdits(events, bodies))) {
138
+ if (ours(target)) byId[target].edit = fold
139
+ }
140
+
141
+ /*
142
+ A filter answered at its limit may have been cut. Counted per filter by
143
+ which chunk each event's target sits in: one pass, each target read once.
144
+ */
145
+ const cut = (chunks: string[][], kinds: readonly number[], targetOf: (e: SignedEvent) => string | undefined) => {
146
+ const chunkOf = new Map<string, number>()
147
+ chunks.forEach((chunk, i) => chunk.forEach((id) => chunkOf.set(id, i)))
148
+ const answered = new Array<number>(chunks.length).fill(0)
149
+ for (const event of events) {
150
+ if (!kinds.includes(event.kind)) continue
151
+ const i = chunkOf.get(targetOf(event) ?? '')
152
+ if (i !== undefined) answered[i] += 1
153
+ }
154
+ return answered.some((n) => n >= RELAY_PAGE_CEILING)
155
+ }
156
+ const reactionEventsCut = cut(reactionChunks, [KIND_REACTION], reactionTargetOf)
157
+ const editEventsCut = cut(editChunks, [KIND_EDIT, KIND_ASSERTION], (e) =>
158
+ e.kind === KIND_EDIT ? editTargetOf(e) : e.tags.find((t) => t[0] === 'e' && ours(t[1]) && !t[3])?.[1],
159
+ )
160
+
161
+ const inHorizon = new Set(asked)
162
+ const reactions = events.filter((e) => e.kind === KIND_REACTION)
163
+ for (const reaction of reactionEventsOf(reactions)) {
164
+ if (ours(reaction.target) && inHorizon.has(reaction.target)) byId[reaction.target].reactions.push(reaction)
165
+ }
166
+
167
+ for (const event of events) {
168
+ if (event.kind !== KIND_ASSERTION || tagValue(event, 't') !== 'resolution') continue
169
+ const action = tagValue(event, 'action')
170
+ if (action !== 'resolved' && action !== 'reopened') continue
171
+ const target = event.tags.find((t) => t[0] === 'e' && ours(t[1]) && !t[3])?.[1]
172
+ if (!ours(target)) continue
173
+ const support = event.tags.find((t) => t[0] === 'e' && t[3] === 'support')?.[1]
174
+ byId[target].resolutions.push({
175
+ id: event.id,
176
+ action,
177
+ by: event.pubkey,
178
+ at: event.created_at,
179
+ ...(event.content ? { message: event.content } : {}),
180
+ ...(support ? { supportingEventId: support } : {}),
181
+ })
182
+ }
183
+ const oldestFirst = (a: { at: number; id: string }, b: { at: number; id: string }) => a.at - b.at || (a.id < b.id ? -1 : 1)
184
+ for (const decoration of Object.values(byId)) decoration.resolutions.sort(oldestFirst)
185
+
186
+ return { byId, reactionTargetsOmitted: omitted, reactionEventsCut, editEventsCut }
187
+ }
package/src/drafts.ts ADDED
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Drafts — CON-10.
3
+ *
4
+ * A message you started and did not send is still there when you come back, in
5
+ * the composer you were typing in and in no other. Moved here from Peek's and
6
+ * Ship's `src/lib/drafts.ts`, which were one file copied (CON-5); Peek's
7
+ * `container` key comes with it.
8
+ *
9
+ * ## Local, and never on the relay
10
+ *
11
+ * A draft is **unsent**. Publishing one — even to SPEC §12's app-private
12
+ * layer — turns something a person chose not to say into something the
13
+ * workspace holds, and a `kind:5` is a request rather than a reversal. The
14
+ * cost is the right way round: drafts do not follow you to another device.
15
+ *
16
+ * ## The key is the whole feature
17
+ *
18
+ * PEE-7's two symptoms — text appearing in a topic it was not written for, and
19
+ * text lost on returning to the thread it *was* written for — are one bug: the
20
+ * composer's text was not keyed by **destination**. {@link draftKeys} is the
21
+ * only place that decides, and two apps using it cannot disagree about where
22
+ * a draft belongs.
23
+ *
24
+ * ## Injected storage
25
+ *
26
+ * Everything takes its storage rather than reaching for `localStorage`, which
27
+ * is what lets it run with no browser and makes "storage is unavailable" a
28
+ * case rather than a crash. {@link DraftStorage} is the three methods of the
29
+ * Web Storage API this uses, declared here so no DOM type is published.
30
+ */
31
+
32
+ /** How long a draft survives. A draft from months ago reappearing surprises more than it helps. */
33
+ export const DRAFT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
34
+
35
+ /**
36
+ * The longest draft that is kept. `localStorage` is a shared ~5 MB budget and a
37
+ * runaway paste should not evict everything else; beyond this the draft is not
38
+ * stored, and the text stays in the field in front of the person.
39
+ */
40
+ export const DRAFT_MAX_CHARS = 8000
41
+
42
+ /** Namespaced and versioned, so a shape change can be ignored rather than mis-read. */
43
+ const PREFIX = 'estiva.draft.v1:'
44
+
45
+ /**
46
+ * Where a draft belongs. **A thread is keyed by its own root event, not by the
47
+ * surface showing it**: a reply half-written on an issue page and the same
48
+ * thread seen from a project's Activity are one destination, so one draft.
49
+ */
50
+ export const draftKeys = {
51
+ /** Starting a conversation about an object — its address. */
52
+ object: (addr: string) => `object:${addr}`,
53
+ /** Replying in a thread — the thread's root event id. */
54
+ thread: (rootEventId: string) => `thread:${rootEventId}`,
55
+ /** Writing into a container itself — a Peek topic, a DM — by the id a person navigates between. */
56
+ container: (id: string) => `container:${id}`,
57
+ }
58
+
59
+ /** The part of the Web Storage API a draft store uses. `window.localStorage` is one. */
60
+ export interface DraftStorage {
61
+ getItem(key: string): string | null
62
+ setItem(key: string, value: string): void
63
+ removeItem(key: string): void
64
+ }
65
+
66
+ interface StoredDraft {
67
+ text: string
68
+ /** When it was last typed, for the age cap. */
69
+ at: number
70
+ }
71
+
72
+ export interface DraftStore {
73
+ /** The draft for this key, or `undefined` — including when storage is unusable. */
74
+ read(key: string): string | undefined
75
+ /** Keep this text. An empty or whitespace-only draft is a cleared one. */
76
+ write(key: string, text: string): void
77
+ /** Forget it — what a successful send calls. */
78
+ clear(key: string): void
79
+ }
80
+
81
+ /** A store that keeps nothing, for when there is no storage to use. */
82
+ export const NO_DRAFTS: DraftStore = { read: () => undefined, write: () => {}, clear: () => {} }
83
+
84
+ /**
85
+ * A draft store over some storage. **Every operation is guarded**: a private
86
+ * window, cleared site data, blocked storage or a full quota all surface as
87
+ * "no draft" rather than a broken composer.
88
+ */
89
+ export function createDraftStore(storage: DraftStorage | undefined, now: () => number = Date.now): DraftStore {
90
+ if (!storage) return NO_DRAFTS
91
+
92
+ const remove = (key: string) => {
93
+ try {
94
+ storage.removeItem(PREFIX + key)
95
+ } catch {
96
+ // The draft is already unreachable as far as anybody reading it is concerned.
97
+ }
98
+ }
99
+
100
+ return {
101
+ read(key) {
102
+ try {
103
+ const raw = storage.getItem(PREFIX + key)
104
+ if (!raw) return undefined
105
+ const draft = JSON.parse(raw) as Partial<StoredDraft>
106
+ if (typeof draft?.text !== 'string' || typeof draft?.at !== 'number') {
107
+ // Another version's shape, or corrupted: better dropped than shown.
108
+ remove(key)
109
+ return undefined
110
+ }
111
+ if (now() - draft.at > DRAFT_MAX_AGE_MS) {
112
+ remove(key)
113
+ return undefined
114
+ }
115
+ return draft.text
116
+ } catch {
117
+ return undefined
118
+ }
119
+ },
120
+
121
+ write(key, text) {
122
+ // Whitespace is not a draft: emptying the field forgets it.
123
+ if (!text.trim()) return remove(key)
124
+ if (text.length > DRAFT_MAX_CHARS) return remove(key)
125
+ try {
126
+ const draft: StoredDraft = { text, at: now() }
127
+ storage.setItem(PREFIX + key, JSON.stringify(draft))
128
+ } catch {
129
+ // Quota, or storage refused. The text is still in the field.
130
+ }
131
+ },
132
+
133
+ clear: remove,
134
+ }
135
+ }
package/src/edits.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Edits — SPEC §6.8.
3
+ *
4
+ * An edit is a new `kind:40003`, never a rewrite, and what an app shows as
5
+ * "edited" is a fold over the message and its edits. The latest edit wins, by
6
+ * §6.3's ordering ({@link byOrder}). An edit whose target the reader cannot see
7
+ * is held, not dropped: the target may arrive later, and the caller looks
8
+ * edits up by id.
9
+ *
10
+ * An edit changes the body and the attachments, and nothing else. Attachments
11
+ * fold separately: the set is the `imeta` of the latest edit carrying at least
12
+ * one, and a set replaces rather than appends. The "edited" mark is about the
13
+ * **body**: an edit byte-identical to the body it replaces, judged against the
14
+ * body as it then stood, does not mark the message edited.
15
+ *
16
+ * Nothing here checks who wrote an edit against who wrote the message. The
17
+ * relay adjudicates writes; a `40003` it stored is one it accepted — **for
18
+ * the `e` it checked**, which is why an edit lands only on {@link editTargetOf}.
19
+ */
20
+ import { imetaOf, type Imeta, type SignedEvent } from '@estiva-app/protocol'
21
+ import { isConversationKind, isEventId, KIND_EDIT } from './kinds.js'
22
+ import { byOrder, orderingMs } from './order.js'
23
+
24
+ /**
25
+ * The message a `kind:40003` edits: **the first `e` whose value is 64 hex,
26
+ * marker ignored**, lowercased (SPEC §6.8, PEE-38). That is exactly the event
27
+ * whose ownership the relay checked (`validate_edit_ownership`), and a reader
28
+ * MUST NOT apply an edit to any other `e` — an edit carrying
29
+ * `['e', <own>, '', 'mention'], ['e', <victim>]` was accepted on the writer's
30
+ * own message before CON-21, and must not be drawn on the victim's.
31
+ *
32
+ * Undefined when there is none, which the relay refuses; a reader holding one
33
+ * anyway applies it nowhere.
34
+ */
35
+ export function editTargetOf(event: Pick<SignedEvent, 'tags'>): string | undefined {
36
+ const tag = event.tags.find((t) => t[0] === 'e' && isEventId(t[1]))
37
+ return tag?.[1].toLowerCase()
38
+ }
39
+
40
+ /** One message's edits, folded. */
41
+ export interface EditFold {
42
+ /** The body to show: the latest edit's content. */
43
+ body: string
44
+ /**
45
+ * Whether any edit changed the body — what a reader MUST mark. With the
46
+ * target's body unknown the first edit counts as a change: the mark errs
47
+ * towards showing, and settles on the next read that holds the target.
48
+ */
49
+ edited: boolean
50
+ /** When the body last changed, epoch milliseconds (`ts` when trusted). Absent unless `edited`. */
51
+ editedAt?: number
52
+ /** Who wrote the edit that last changed the body. Absent unless `edited`. */
53
+ editedBy?: string
54
+ /**
55
+ * The `imeta` set of the latest edit carrying at least one. Absent when no
56
+ * edit carries one: the message's own attachments stand, because an edit
57
+ * with no `imeta` means "unchanged", never "none".
58
+ */
59
+ attachments?: Imeta[]
60
+ }
61
+
62
+ /**
63
+ * Every `kind:40003` in `events`, grouped by {@link editTargetOf}, oldest first
64
+ * by §6.3. Other kinds are ignored and a repeated id is read once.
65
+ */
66
+ export function editsByTarget(events: readonly SignedEvent[]): Map<string, SignedEvent[]> {
67
+ const out = new Map<string, SignedEvent[]>()
68
+ const seen = new Set<string>()
69
+ for (const event of events) {
70
+ if (event.kind !== KIND_EDIT || seen.has(event.id)) continue
71
+ seen.add(event.id)
72
+ const target = editTargetOf(event)
73
+ if (!target) continue
74
+ const list = out.get(target)
75
+ if (list) list.push(event)
76
+ else out.set(target, [event])
77
+ }
78
+ for (const list of out.values()) list.sort(byOrder)
79
+ return out
80
+ }
81
+
82
+ /**
83
+ * Fold every edit in `events` onto its target (C12, C15).
84
+ *
85
+ * The body each edit replaces comes from `targets` when given, else from a
86
+ * `kind:9` or `kind:1111` with the target's id in `events` itself — so a
87
+ * caller holding the whole stream passes it once, and one holding only the
88
+ * edits passes the bodies beside them. A target nobody edited is absent.
89
+ */
90
+ export function foldEdits(
91
+ events: readonly SignedEvent[],
92
+ targets: readonly { id: string; body: string }[] = [],
93
+ ): Record<string, EditFold> {
94
+ const bodies = new Map<string, string>()
95
+ for (const event of events) if (isConversationKind(event.kind)) bodies.set(event.id.toLowerCase(), event.content)
96
+ for (const t of targets) bodies.set(t.id.toLowerCase(), t.body)
97
+
98
+ const out: Record<string, EditFold> = {}
99
+ for (const [target, list] of editsByTarget(events)) {
100
+ let body = bodies.get(target)
101
+ let changed: SignedEvent | undefined
102
+ let attachments: Imeta[] | undefined
103
+ for (const edit of list) {
104
+ if (body === undefined || edit.content !== body) changed = edit
105
+ body = edit.content
106
+ const files = imetaOf(edit)
107
+ if (files.length > 0) attachments = files
108
+ }
109
+ out[target] = {
110
+ body: list[list.length - 1].content,
111
+ edited: changed !== undefined,
112
+ ...(changed ? { editedAt: orderingMs(changed), editedBy: changed.pubkey } : {}),
113
+ ...(attachments ? { attachments } : {}),
114
+ }
115
+ }
116
+ return out
117
+ }
118
+
119
+ /**
120
+ * Every message's current attachment set: its own `imeta`, replaced by the
121
+ * latest edit carrying any (§6.8, C15). Messages with none are absent.
122
+ */
123
+ export function foldAttachments(events: readonly SignedEvent[]): Record<string, Imeta[]> {
124
+ const out: Record<string, Imeta[]> = {}
125
+ for (const event of events) {
126
+ if (!isConversationKind(event.kind)) continue
127
+ const files = imetaOf(event)
128
+ if (files.length > 0) out[event.id.toLowerCase()] = files
129
+ }
130
+ for (const [target, list] of editsByTarget(events)) {
131
+ for (let i = list.length - 1; i >= 0; i--) {
132
+ const files = imetaOf(list[i])
133
+ if (files.length === 0) continue
134
+ out[target] = files
135
+ break
136
+ }
137
+ }
138
+ return out
139
+ }
package/src/index.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * `@estiva-app/conversation` — the conversation rules of SPEC §6.2–§6.8, for
3
+ * an app that would rather not implement them itself.
4
+ *
5
+ * **A convenience, never a requirement.** SPEC §9's C10–C16 are written so an
6
+ * app can build conversations from the specification alone, and this
7
+ * package's tests are those checks. If this package became the only place
8
+ * that knows how commenting works, a defect in its fold would be a defect in
9
+ * every app at once and invisible from all of them.
10
+ *
11
+ * It sits above `@estiva-app/protocol`, which carries no fold, and below the
12
+ * apps: it imports no app's data layer, opens no socket, and takes every
13
+ * environment touch — the relay read, the clock, storage — as a parameter.
14
+ */
15
+ export const CONVERSATION_VERSION = '0.1.0'
16
+
17
+ export {
18
+ KIND_MESSAGE,
19
+ KIND_COMMENT,
20
+ KIND_EDIT,
21
+ KIND_REACTION,
22
+ KIND_DELETION,
23
+ KIND_ASSERTION,
24
+ isConversationKind,
25
+ isEventId,
26
+ } from './kinds.js'
27
+
28
+ export { trustedTs, orderingMs, byOrder } from './order.js'
29
+
30
+ export {
31
+ namedInBody,
32
+ isReply,
33
+ anchorsOf,
34
+ isCommentOn,
35
+ referencesAddress,
36
+ strengthOn,
37
+ threadStrength,
38
+ referenceTagsFor,
39
+ mentionTagsFor,
40
+ MAX_MENTIONED_PEOPLE,
41
+ type Strength,
42
+ } from './strength.js'
43
+
44
+ export { parentOf, groupThreads, type Threaded } from './threads.js'
45
+
46
+ export { editTargetOf, editsByTarget, foldEdits, foldAttachments, type EditFold } from './edits.js'
47
+
48
+ export {
49
+ REACTION_HORIZON,
50
+ REACTION_EMOJI,
51
+ reactionTargetOf,
52
+ reactionEmojiOf,
53
+ reactionHorizon,
54
+ reactionEventsOf,
55
+ foldReactions,
56
+ groupReactions,
57
+ type ReactionHorizon,
58
+ type ReactionEvent,
59
+ type Reaction,
60
+ } from './reactions.js'
61
+
62
+ export { decorationsOf, type Decoration, type Decorations, type Resolution, type QueryFn } from './decorations.js'
63
+
64
+ export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from './builders.js'
65
+
66
+ export {
67
+ createDraftStore,
68
+ draftKeys,
69
+ NO_DRAFTS,
70
+ DRAFT_MAX_AGE_MS,
71
+ DRAFT_MAX_CHARS,
72
+ type DraftStore,
73
+ type DraftStorage,
74
+ } from './drafts.js'