@estiva-app/protocol 0.36.0 → 0.38.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/src/embeds.ts CHANGED
@@ -8,15 +8,19 @@
8
8
  * name: `compact` is §7.5's closed `row` and `detailed` its closed `card`, so
9
9
  * a richer card can come later without changing the wire.
10
10
  *
11
- * A reference with no `embed` is drawn by the reader's default (a chip, §13.1).
12
- * An `embed` for a value overrides that default, which is why `none` exists:
13
- * it is the author saying "no card" in an edit that replaces the set (§6.8).
11
+ * A reference with no `embed` draws by where it sits: its chip in a sentence,
12
+ * its row alone on its line ({@link isOnlyReferenceLine}). A reader never adds
13
+ * a card; the default card is the writer's ({@link defaultCardOf}). An `embed`
14
+ * for a value overrides any default, which is why `none` exists: it is the
15
+ * author saying "no card" in an edit that replaces the set (§6.8).
14
16
  *
15
17
  * Like `part` (§13.6.1), the tags are only half the answer. A card is drawn
16
18
  * only while the body — as edited — still names its value, and there is no
17
19
  * `a`/`q` match: an edit carries no index tags (§6.8), and a value first named
18
20
  * in an edit can still carry a card (Miky, 2026-10-13, OPT-16 kickoff).
19
21
  * {@link cardsIn} applies that rule; {@link embedsOf} reads the tags alone.
22
+ *
23
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/where-a-link-sits-decides-how-it-draws.md
20
24
  */
21
25
  import { addrToNaddr, bech32Decode, convertBits, decodeNevent, encodeNevent, naddrToAddr } from './nip19.js'
22
26
  import type { PartPointer } from './anchors.js'
@@ -39,6 +43,24 @@ export function embedTag(value: string, layout: EmbedLayout): string[] {
39
43
  return [EMBED_TAG, value, layout]
40
44
  }
41
45
 
46
+ /**
47
+ * A whole `embed` set as tags, as a send or an edit writes it: each value
48
+ * normalised as {@link embedsOf} reads it, the first entry per value kept.
49
+ * Throws on a value that is neither an address nor an event id, or on a
50
+ * layout this writer does not know, rather than write a tag readers skip.
51
+ */
52
+ export function embedTagsOf(set: readonly Embed[]): string[][] {
53
+ const seen = new Set<string>()
54
+ return set.flatMap((e) => {
55
+ const value = normalise(e.value)
56
+ if (!value) throw new Error(`not an address or event id: ${e.value}`)
57
+ if (e.layout !== 'compact' && e.layout !== 'detailed' && e.layout !== 'none') throw new Error(`not an embed layout: ${String(e.layout)}`)
58
+ if (seen.has(value)) return []
59
+ seen.add(value)
60
+ return [embedTag(value, e.layout)]
61
+ })
62
+ }
63
+
42
64
  // `partsOf`'s shape: an empty `d` is a valid address (NIP-01).
43
65
  const ADDRESS = /^\d+:[0-9a-f]{64}:/
44
66
  const EVENT_ID = /^[0-9a-f]{64}$/
@@ -90,7 +112,6 @@ function normalise(value: string): string | undefined {
90
112
  export type LinkResolver = (url: string) => string | undefined
91
113
 
92
114
  const TRAILING = new Set(['.', ',', ';', ':', '!', '?', ')', ']'])
93
- const URL_RUN = /https?:\/\/[^\s<>"'`]+/g
94
115
 
95
116
  /** A URL run without the sentence's trailing punctuation; stripped by a loop, which stays linear on a hostile run of dots. */
96
117
  function trimUrl(url: string): string {
@@ -99,13 +120,16 @@ function trimUrl(url: string): string {
99
120
  return url.slice(0, end)
100
121
  }
101
122
 
102
- /** The http(s) links in a text. Trailing punctuation is the sentence's, not the link's. */
103
- function urlsIn(text: string): string[] {
104
- return (text.match(URL_RUN) ?? []).map(trimUrl)
123
+ /** A URL stuck to the end of a word (`seehttps://…`) is the word's, not a link. */
124
+ function stuckToWord(text: string, start: number): boolean {
125
+ return start > 0 && /[\p{L}\p{N}]/u.test(text[start - 1])
105
126
  }
106
127
 
107
- /** The address or event id a `nostr:` reference names, or undefined for a person or something unreadable. */
108
- function valueOfReference(reference: string): string | undefined {
128
+ /**
129
+ * The address or event id a `nostr:` reference names — what an `a`, `q` or
130
+ * `embed` carries for it — or undefined for a person or something unreadable.
131
+ */
132
+ export function valueOfReference(reference: string): string | undefined {
109
133
  const bare = reference.replace(/^nostr:/i, '').toLowerCase()
110
134
  try {
111
135
  if (bare.startsWith('naddr1')) return normalise(naddrToAddr(bare))
@@ -140,35 +164,38 @@ export function cardsIn(embeds: readonly Embed[], blocks: readonly RenderBlock[]
140
164
  if (embeds.length === 0) return []
141
165
  const byValue = new Map(embeds.map((e) => [e.value, e]))
142
166
  const withPart = new Set(parts.map((p) => normalise(p.address)).filter((v): v is string => !!v))
143
- const out: Embed[] = []
167
+ return valuesIn(blocks, resolveLink).flatMap((value) => {
168
+ const embed = withPart.has(value) ? undefined : byValue.get(value)
169
+ return embed ? [embed] : []
170
+ })
171
+ }
172
+
173
+ /**
174
+ * Every address and event id a message's body names, once each, in the order
175
+ * it first names them: by a `nostr:` reference, or by an app link that
176
+ * `resolveLink` resolves (§7.7). A person names no value. Text in a code span
177
+ * names nothing (§13.1). What {@link cardsIn} and {@link defaultCardOf} count.
178
+ */
179
+ export function valuesIn(blocks: readonly RenderBlock[], resolveLink?: LinkResolver): string[] {
180
+ const out: string[] = []
144
181
  const seen = new Set<string>()
145
182
  const take = (value: string | undefined) => {
146
- if (!value || seen.has(value) || withPart.has(value)) return
147
- const embed = byValue.get(value)
148
- if (!embed) return
183
+ if (!value || seen.has(value)) return
149
184
  seen.add(value)
150
- out.push(embed)
151
- }
152
- // Adjacent plain runs are read as one text, so a link a mark splits in two is still one link.
153
- const scan = (text: string) => {
154
- if (!resolveLink || !text.includes('://')) return
155
- for (const url of urlsIn(text)) {
156
- const value = resolveLink(url)
157
- if (value) take(normalise(value))
158
- }
185
+ out.push(value)
159
186
  }
187
+ const resolve = (url: string) => resolveLink && take(normalise(resolveLink(url) ?? ''))
188
+ // Run by run, by the rules {@link linksAsReferences} turns links by, so a URL names a value exactly where it draws as a reference.
160
189
  const walk = (bs: readonly RenderBlock[]) => {
161
190
  for (const block of bs) {
162
191
  if (block.type !== 'codeBlock') {
163
- let text = ''
164
192
  for (const run of block.inline ?? []) {
165
- if (run.reference || run.marks.includes('code')) {
166
- scan(text)
167
- text = ''
168
- if (run.reference) take(valueOfReference(run.reference))
169
- } else text += run.text
193
+ if (run.reference) take(valueOfReference(run.reference))
194
+ else if (run.marks.includes('code')) continue
195
+ else if (run.href !== undefined) {
196
+ if (run.text === run.href) resolve(run.href)
197
+ } else for (const { url } of urlRunsIn(run.text)) resolve(url)
170
198
  }
171
- scan(text)
172
199
  }
173
200
  if (block.children) walk(block.children)
174
201
  }
@@ -177,6 +204,150 @@ export function cardsIn(embeds: readonly Embed[], blocks: readonly RenderBlock[]
177
204
  return out
178
205
  }
179
206
 
207
+ /**
208
+ * A block's lines: its inline runs split at each `\n`, the line break both
209
+ * content models use (§13.2). A run that holds a break is cut in two, marks
210
+ * kept; a reference never holds one.
211
+ */
212
+ export function linesOf(block: Pick<RenderBlock, 'inline'>): RenderInline[][] {
213
+ const lines: RenderInline[][] = [[]]
214
+ for (const run of block.inline ?? []) {
215
+ const pieces = run.reference ? [run.text] : run.text.split('\n')
216
+ pieces.forEach((text, i) => {
217
+ if (i > 0) lines.push([])
218
+ if (text) lines[lines.length - 1].push(pieces.length === 1 ? run : { ...run, text })
219
+ })
220
+ }
221
+ return lines
222
+ }
223
+
224
+ const LONE_URL = /^https?:\/\/[^\s<>"'`]+$/
225
+ const PERSON = /^nostr:(npub1|nprofile1)/i
226
+
227
+ /**
228
+ * What a line of a message is only, by §13.2, or undefined when it is a
229
+ * sentence: the `nostr:` reference, or the bare URL, that §13.6.2 draws in its
230
+ * place. `block` is the block the line is in: only a paragraph's and a list
231
+ * item's lines count, never a quote's, a heading's or code's.
232
+ *
233
+ * Whitespace around it is trimmed. Anything else makes it a sentence: other
234
+ * words or punctuation (trailing `.` included), a second reference, a marker
235
+ * around it, a code span, or `[words](url)`. A person (`npub`, `nprofile`)
236
+ * alone on a line stays a chip, so it is not returned. A Folder stays a chip
237
+ * too, but whether a URL names one is known only once it resolves: the reader
238
+ * checks the value ({@link isFolderValue}). A URL returned here still has to
239
+ * resolve by §7.7; one that resolves to nothing, or to something the reader
240
+ * cannot read, stays the URL as written.
241
+ */
242
+ export function isOnlyReferenceLine(line: readonly RenderInline[], block: Pick<RenderBlock, 'type'>): string | undefined {
243
+ if (block.type !== 'paragraph' && block.type !== 'listItem') return undefined
244
+ const runs = line.filter((run) => run.reference || run.text.trim() !== '')
245
+ if (runs.length !== 1 || runs[0].marks.length > 0 || runs[0].href !== undefined) return undefined
246
+ const [run] = runs
247
+ if (run.reference) return PERSON.test(run.reference) ? undefined : run.reference
248
+ const text = run.text.trim()
249
+ return LONE_URL.test(text) && trimUrl(text) === text ? text : undefined
250
+ }
251
+
252
+ /** A Folder's address (`39000:…`): alone on its line it stays a chip, and it never takes the default card (§13.6.2). */
253
+ export function isFolderValue(value: string): boolean {
254
+ return value.startsWith('39000:')
255
+ }
256
+
257
+ /**
258
+ * What one line of a message draws (§13.2, §13.6.2):
259
+ * - `sentence` — its runs as they are, each reference its chip;
260
+ * - `row` — the line is only a reference to `value`, drawn as its row;
261
+ * - `nothing` — the same, but `value` has a card or a part under the message,
262
+ * which stands for it (C26);
263
+ * - `url` — a lone URL that names nothing (no app claims it, or the answer has
264
+ * not come back), drawn as the URL as written;
265
+ * - `unreadable` — a lone `nostr:` reference that names no address or event
266
+ * id, drawn as the unreadable row.
267
+ */
268
+ export type LineDraw =
269
+ | { draw: 'sentence' }
270
+ | { draw: 'row' | 'nothing'; value: string }
271
+ | { draw: 'url'; url: string }
272
+ | { draw: 'unreadable'; reference: string }
273
+
274
+ /**
275
+ * How a reader draws one of a message's lines ({@link linesOf}) in `block`:
276
+ * {@link isOnlyReferenceLine}, then the value it names, then whether a card
277
+ * stands for it. `cards` is {@link cardsIn}'s answer (its `none` entries draw
278
+ * no card), `parts` the message's `part` pointers. A Folder alone on its line
279
+ * stays a chip, so its line is a sentence. Whether the reader can read a
280
+ * `row`'s object is its own business: one it cannot draws the unreadable row.
281
+ */
282
+ export function lineDrawOf(
283
+ line: readonly RenderInline[],
284
+ block: Pick<RenderBlock, 'type'>,
285
+ context: { cards?: readonly Embed[]; parts?: readonly PartPointer[]; resolveLink?: LinkResolver } = {},
286
+ ): LineDraw {
287
+ const only = isOnlyReferenceLine(line, block)
288
+ if (!only) return { draw: 'sentence' }
289
+ const isReference = /^nostr:/i.test(only)
290
+ const value = isReference ? valueOfReference(only) : normalise(context.resolveLink?.(only) ?? '')
291
+ if (!value) return isReference ? { draw: 'unreadable', reference: only } : { draw: 'url', url: only }
292
+ if (isFolderValue(value)) return { draw: 'sentence' }
293
+ const carded =
294
+ (context.cards ?? []).some((e) => e.value === value && e.layout !== 'none') ||
295
+ (context.parts ?? []).some((p) => normalise(p.address) === value)
296
+ return { draw: carded ? 'nothing' : 'row', value }
297
+ }
298
+
299
+ /**
300
+ * The value a writer gives the default card, `["embed", V, "detailed"]`, as
301
+ * it sends or edits a message (§13.6.2), or undefined.
302
+ *
303
+ * `values` is what the body names, resolved ({@link valuesIn}), and `parts`
304
+ * its `part` pointers. A file counts, except a Folder and `here`, the object
305
+ * whose conversation the message is in (Miky, 2026-10-16: the issue a
306
+ * message is about plus one other file gives the other its card); a part's
307
+ * file counts too. A message (an event id) does not. When exactly one file
308
+ * counts, it gets the card, unless a part names it (the part wins, and draws
309
+ * under the message already).
310
+ *
311
+ * On an edit, pass the values the previous folded body named as `previous`,
312
+ * and the folded `embed` set as `embeds`: the default is only for a file the
313
+ * edit names first, so a card its author removed with ✕ before sending, which
314
+ * left no tag, does not come back, and a value that has an entry keeps it, so
315
+ * a ✕ after sending (`none`) holds even when the link is removed and named
316
+ * again. The edit then carries the whole folded set plus this one
317
+ * ({@link withCard}).
318
+ */
319
+ export function defaultCardOf(
320
+ values: readonly string[],
321
+ parts: readonly PartPointer[] = [],
322
+ options: { here?: string; previous?: readonly string[]; embeds?: readonly Embed[] } = {},
323
+ ): string | undefined {
324
+ const here = normalise(options.here ?? '')
325
+ const withPart = new Set(parts.map((p) => normalise(p.address)).filter((v): v is string => !!v))
326
+ const isFile = (v: string | undefined): v is string => !!v && ADDRESS.test(v) && !isFolderValue(v) && v !== here
327
+ const files = new Set([...values.map(normalise), ...withPart].filter(isFile))
328
+ if (files.size !== 1) return undefined
329
+ const [file] = files
330
+ if (withPart.has(file)) return undefined
331
+ if (options.previous?.some((v) => normalise(v) === file)) return undefined
332
+ if (options.embeds?.some((e) => normalise(e.value) === file)) return undefined
333
+ return file
334
+ }
335
+
336
+ /**
337
+ * A folded `embed` set with `value` set to `layout`, the rest kept as they
338
+ * are: what an edit carries, since a set replaces (§13.6.2). ✕ on a sent card
339
+ * is `withCard(set, V, 'none')`; adding an edit's default card is
340
+ * `withCard(set, V, 'detailed')`.
341
+ */
342
+ export function withCard(set: readonly Embed[], value: string, layout: EmbedLayout): Embed[] {
343
+ const v = normalise(value)
344
+ if (!v) throw new Error(`not an address or event id: ${value}`)
345
+ const out = set.filter((e) => e.value !== v)
346
+ const at = set.findIndex((e) => e.value === v)
347
+ out.splice(at === -1 ? out.length : at, 0, { value: v, layout })
348
+ return out
349
+ }
350
+
180
351
  /**
181
352
  * The `nostr:` reference an app link names, by what `resolveLink` answered for
182
353
  * it (§7.7), or undefined: nothing claims it, the answer has not come back, or
@@ -204,7 +375,7 @@ export function urlRunsIn(text: string): { url: string; from: number; to: number
204
375
  if (!text.includes('://')) return []
205
376
  const out: { url: string; from: number; to: number }[] = []
206
377
  for (const m of text.matchAll(LINK_OR_URL)) {
207
- if (m[1]) continue
378
+ if (m[1] || stuckToWord(text, m.index)) continue
208
379
  const start = m.index
209
380
  if (text.slice(Math.max(0, start - 2), start) === '](' || text[start - 1] === '[') continue
210
381
  const url = trimUrl(m[0])
@@ -226,9 +397,10 @@ const LINK_OR_URL = /(\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\))|(https?:\
226
397
 
227
398
  /**
228
399
  * A message's tree with each bare app link turned into the reference it names,
229
- * so a reader draws it as that object's chip (SPEC §13.6.2, OPT-18).
400
+ * so a reader draws it as a reference to that object (SPEC §13.6.2, OPT-18):
401
+ * its chip in a sentence, its row alone on its line.
230
402
  *
231
- * A reference reads as a chip wherever it sits (§13.1), and a link some app
403
+ * A link some app
232
404
  * claims (§7.7) is a reference written as a URL — the form a message has when
233
405
  * it was written before the composer turned pasted links into chips, or by a
234
406
  * client that does not. Without this, the two would read differently for no
@@ -260,7 +432,7 @@ export function linksAsReferences(blocks: readonly RenderBlock[], resolveLink: L
260
432
  let at = 0
261
433
  for (const m of run.text.matchAll(LINK_OR_URL)) {
262
434
  // A link on words: neither its target nor a URL in its words is taken.
263
- if (m[1]) continue
435
+ if (m[1] || stuckToWord(run.text, m.index)) continue
264
436
  const start = m.index
265
437
  // A link on words whose words carry a mark arrives split across runs: its target follows `](`, and a URL as its words follows `[`.
266
438
  if (run.text.slice(Math.max(0, start - 2), start) === '](' || run.text[start - 1] === '[') continue
package/src/events.ts CHANGED
@@ -35,6 +35,7 @@
35
35
  import { sha256 } from '@noble/hashes/sha256'
36
36
  import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils'
37
37
  import { type BlockDocument, serializeBlockDocument } from './blocks.js'
38
+ import { type Embed, embedTagsOf } from './embeds.js'
38
39
 
39
40
  /** A Nostr tag: an array of strings whose first element is the tag name. */
40
41
  export type NostrTag = string[]
@@ -125,6 +126,8 @@ export const KIND = {
125
126
  * owns an issue; Leaf is the first owner. The bare file's shape, but owned:
126
127
  * a document is written and opened in its owner's app, where a topic
127
128
  * (`FILE`) is a conversation nobody owns (SPEC, Miky 2026-10-14).
129
+ *
130
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-document-is-its-own-type-of-file.md
128
131
  */
129
132
  DOCUMENT: 30842,
130
133
  /**
@@ -714,6 +717,15 @@ export function buildEdit(
714
717
  targetEventId: string
715
718
  /** The new body, in the target's own format. */
716
719
  body: string
720
+ /**
721
+ * The message's whole `embed` set after this edit, when the edit changes it
722
+ * (SPEC §13.6.2): a set replaces, so every card it keeps is listed, and
723
+ * `none` for each it removes (`withCard`). Omitted or empty, the edit
724
+ * carries none and leaves the set as it was.
725
+ */
726
+ embeds?: readonly Embed[]
727
+ /** The whole `imeta` set after this edit, when it changes it; it folds the same way (§6.8). */
728
+ mediaTags?: NostrTag[]
717
729
  },
718
730
  ): UnsignedEvent {
719
731
  assertHex64(pubkey, 'pubkey')
@@ -733,6 +745,8 @@ export function buildEdit(
733
745
  // and a rounded `ts` could land in the next second and be discarded by
734
746
  // its own agreement rule.
735
747
  ['ts', String(Math.floor(createdAtMs))],
748
+ ...embedTagsOf(args.embeds ?? []),
749
+ ...(args.mediaTags ?? []),
736
750
  ],
737
751
  content: args.body,
738
752
  }
package/src/index.ts CHANGED
@@ -47,7 +47,7 @@
47
47
  /** Bumped by hand with the version in package.json — `test/version.test.ts`
48
48
  * pins the two together. It exists so "the upgrade reached the app" can be
49
49
  * checked by grepping a built bundle rather than by trusting a lockfile. */
50
- export const PROTOCOL_VERSION = '0.36.0'
50
+ export const PROTOCOL_VERSION = '0.38.0'
51
51
 
52
52
  export {
53
53
  // types
@@ -265,7 +265,47 @@ export {
265
265
  resolveBlockAnchor,
266
266
  resolvePart,
267
267
  } from './anchors.js'
268
- export { type Embed, type EmbedLayout, type LinkResolver, EMBED_TAG, cardsIn, embedTag, embedsOf, linksAsReferences, referenceOfLink, urlRunsIn } from './embeds.js'
268
+ export {
269
+ type CommentAnchor,
270
+ type Quote,
271
+ type TextPoint,
272
+ MAX_RUN_ENTRIES_READ,
273
+ MAX_RUN_IDS,
274
+ QUOTE_CONTEXT_LENGTH,
275
+ QUOTE_END_LENGTH,
276
+ QUOTE_TAG,
277
+ QUOTE_WHOLE_MAX,
278
+ blockRunOf,
279
+ blockRunTag,
280
+ quoteOf,
281
+ quoteTag,
282
+ readRunIds,
283
+ resolveBlockRun,
284
+ resolveCommentAnchor,
285
+ selectionAnchorTags,
286
+ } from './comment-anchor.js'
287
+ export {
288
+ type Embed,
289
+ type EmbedLayout,
290
+ type LineDraw,
291
+ type LinkResolver,
292
+ EMBED_TAG,
293
+ cardsIn,
294
+ defaultCardOf,
295
+ embedTag,
296
+ embedTagsOf,
297
+ embedsOf,
298
+ isFolderValue,
299
+ isOnlyReferenceLine,
300
+ lineDrawOf,
301
+ linesOf,
302
+ linksAsReferences,
303
+ referenceOfLink,
304
+ urlRunsIn,
305
+ valueOfReference,
306
+ valuesIn,
307
+ withCard,
308
+ } from './embeds.js'
269
309
  export {
270
310
  type BlossomVerb,
271
311
  type Imeta,
package/src/render.ts CHANGED
@@ -349,11 +349,11 @@ export function renderTreeText(blocks: readonly RenderBlock[]): string {
349
349
  * on its line is alone on its line whether or not somebody left a space after
350
350
  * it.
351
351
  *
352
- * @deprecated Since 0.33.0 a reference reads as its chip wherever it sits, in a
353
- * message (§13.6.2) and in a block document (§13.3, "A reference's card"); a
354
- * card comes only from what its writer chose. Use {@link blockCards} for a
355
- * document and `cardsIn` for a message. Kept for one release so a reader on it
356
- * still builds.
352
+ * @deprecated A whole paragraph is not the unit: since 0.38.0 a message's line
353
+ * that is only a reference draws its row (§13.2, §13.6.2), which
354
+ * `isOnlyReferenceLine` decides per line, list items and app URLs included. A
355
+ * block document reads a reference as its chip (§13.3); use {@link blockCards}
356
+ * for its cards.
357
357
  */
358
358
  export function standaloneReference(block: RenderBlock): string | undefined {
359
359
  if (block.type !== 'paragraph' || block.children?.length) return undefined