@estiva-app/protocol 0.32.0 → 0.34.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/editor.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  type BlockDocument,
9
9
  } from './blocks.js'
10
10
  import { markerTextToBlockDocument } from './bridge-content.js'
11
- import type { InlineMarkNode, InlineTextNode } from './content.js'
11
+ import { targetMark, type InlineMarkNode, type InlineTextNode } from './content.js'
12
12
  import { BLOCK_DOCUMENT_FORMAT, type ContentFormat } from './render.js'
13
13
 
14
14
  /**
@@ -160,10 +160,23 @@ function textNodes(text: string, marks: EditorNode['marks']): EditorNode[] {
160
160
  return out
161
161
  }
162
162
 
163
+ /**
164
+ * A mark's `embed` as the editor node holds it: a layout string goes on the
165
+ * node, and anything else a later version may have put there rides in `extra`
166
+ * with the other unknown keys, so a save writes it back untouched. `none` and
167
+ * `""` are no card, which a writer omits (§13.3).
168
+ */
169
+ function cardAndExtra(embed: unknown, rest: Record<string, unknown>): { card: { embed?: string }; extra: Record<string, unknown> } {
170
+ if (typeof embed === 'string') return { card: embed && embed !== 'none' ? { embed } : {}, extra: rest }
171
+ return { card: {}, extra: embed === undefined ? rest : { ...rest, embed } }
172
+ }
173
+
163
174
  function inlineToEditor(runs: readonly InlineTextNode[]): EditorNode[] {
164
175
  return runs.flatMap((run) => {
165
176
  const marks = run.marks ?? []
166
- const reference = marks.find((m): m is Extract<InlineMarkNode, { type: 'reference' }> => m.type === 'reference')
177
+ // The marks a run keeps as marks; `reference` and `link` become the chip, or nothing when malformed.
178
+ const carried = marks.filter((m) => m.type !== 'reference' && m.type !== 'link').map((m) => m.type)
179
+ const reference = targetMark(marks, 'reference')
167
180
  if (reference) {
168
181
  /*
169
182
  An atom rather than a mark, and the difference is what a person sees.
@@ -173,18 +186,47 @@ function inlineToEditor(runs: readonly InlineTextNode[]): EditorNode[] {
173
186
  while reading, which is the mode difference this ticket is about.
174
187
 
175
188
  The run's other marks ride along so a bold reference comes back bold.
189
+ So does its card (`embed`, §13.3), and every key a later version adds
190
+ rides in `extra`: a mark has no id, so a key dropped on save would be
191
+ lost with nothing to say so.
176
192
  */
193
+ const { uri, embed, ...rest } = reference
194
+ const { card, extra } = cardAndExtra(embed, rest)
177
195
  return [
178
196
  {
179
197
  type: REFERENCE_NODE,
180
198
  attrs: {
181
- uri: reference.attrs.uri,
182
- marks: marks.filter((m) => m.type !== 'reference').map((m) => m.type),
199
+ uri,
200
+ marks: carried,
201
+ ...card,
202
+ ...(Object.keys(extra).length ? { extra } : {}),
183
203
  },
184
204
  },
185
205
  ]
186
206
  }
187
- return textNodes(run.text, marks.map((m) => ({ type: m.type })))
207
+ const link = targetMark(marks, 'link')
208
+ if (link && run.text === link.href) {
209
+ /*
210
+ A URL whose card its writer chose (§13.3): the chip it reads as, which
211
+ keeps the URL in `href` and writes it back as the same run. `uri` is
212
+ what it names, filled in by the editor's `LinkChips` once the app has
213
+ resolved it; until then the chip draws as the URL.
214
+
215
+ `extra` is always an object here, empty or not: it says the URL came
216
+ with a `link` mark, so a save writes the mark back even with no card,
217
+ and a description somebody else wrote that way saves the same bytes.
218
+ */
219
+ const { href, embed, ...rest } = link
220
+ const { card, extra } = cardAndExtra(embed, rest)
221
+ return [
222
+ {
223
+ type: REFERENCE_NODE,
224
+ attrs: { uri: '', href, marks: carried, ...card, extra },
225
+ },
226
+ ]
227
+ }
228
+ // A link on other words is not one these editors write or draw: its words stay, the link does not.
229
+ return textNodes(run.text, carried.map((type) => ({ type })))
188
230
  })
189
231
  }
190
232
 
@@ -373,13 +415,49 @@ function idFor(node: EditorNode, claims: IdClaims): string {
373
415
 
374
416
  function inlineFromEditor(nodes: readonly EditorNode[]): InlineTextNode[] {
375
417
  const out: InlineTextNode[] = []
376
- for (const node of nodes) {
418
+ for (const [i, node] of nodes.entries()) {
419
+ if (node.type === REFERENCE_NODE && typeof node.attrs?.href === 'string' && node.attrs.href) {
420
+ /*
421
+ A URL chip is its URL on the wire, never rewritten into the reference
422
+ it names (§13.3). With no card it is plain text, merged with the text
423
+ around it, so a description an editor only opened saves the same bytes.
424
+ A `link` mark holds it when it has a card, when it came with one
425
+ (`extra` set), or when what follows would read as more of the URL — a
426
+ word typed right after the chip, or another URL chip — so its end stays
427
+ where it was.
428
+ */
429
+ const href = node.attrs.href
430
+ const carried = Array.isArray(node.attrs.marks) ? (node.attrs.marks as string[]) : []
431
+ const embed = node.attrs.embed
432
+ const extra = node.attrs.extra && typeof node.attrs.extra === 'object' && !Array.isArray(node.attrs.extra) ? (node.attrs.extra as Record<string, unknown>) : undefined
433
+ const card = typeof embed === 'string' && embed !== '' && embed !== 'none'
434
+ const marks: InlineMarkNode[] = carried.map((type) => ({ type }) as InlineMarkNode)
435
+ if (card || extra || continuesUrl(nodes[i + 1])) {
436
+ // `href` first, as writers put it, so an untouched mark keeps its bytes; `extra` never holds it.
437
+ marks.push({ type: 'link', attrs: { href, ...extra, ...(card ? { embed } : {}) } })
438
+ }
439
+ const last = out[out.length - 1]
440
+ if (last && sameMarks(last.marks ?? [], marks)) last.text += href
441
+ else out.push({ type: 'text', text: href, ...(marks.length ? { marks } : {}) })
442
+ continue
443
+ }
377
444
  if (node.type === REFERENCE_NODE) {
378
445
  const uri = String(node.attrs?.uri ?? '')
379
446
  const carried = Array.isArray(node.attrs?.marks) ? (node.attrs.marks as string[]) : []
447
+ const embed = node.attrs?.embed
448
+ const extra = node.attrs?.extra
380
449
  const marks: InlineMarkNode[] = [
381
450
  ...carried.map((type) => ({ type }) as InlineMarkNode),
382
- { type: 'reference', attrs: { uri } },
451
+ {
452
+ type: 'reference',
453
+ attrs: {
454
+ // `extra` first, so a key it carries can never overwrite the two this code owns.
455
+ ...(extra && typeof extra === 'object' && !Array.isArray(extra) ? (extra as Record<string, unknown>) : {}),
456
+ uri,
457
+ // `none` is no attribute (§13.3): a writer omits it.
458
+ ...(typeof embed === 'string' && embed !== '' && embed !== 'none' ? { embed } : {}),
459
+ },
460
+ },
383
461
  ]
384
462
  out.push({ type: 'text', text: uri, marks })
385
463
  continue
@@ -388,7 +466,7 @@ function inlineFromEditor(nodes: readonly EditorNode[]): InlineTextNode[] {
388
466
  // Rejoin onto the previous run where there is one, so a paragraph is not
389
467
  // split into three runs by one break.
390
468
  const last = out[out.length - 1]
391
- if (last && !last.marks?.some((m) => m.type === 'reference')) last.text += '\n'
469
+ if (last && !last.marks?.some(holdsTarget)) last.text += '\n'
392
470
  else out.push({ type: 'text', text: '\n' })
393
471
  continue
394
472
  }
@@ -407,9 +485,24 @@ function inlineFromEditor(nodes: readonly EditorNode[]): InlineTextNode[] {
407
485
  return out
408
486
  }
409
487
 
488
+ /**
489
+ * Whether this node, written right after a URL as plain text, would be read
490
+ * as more of the URL: another chip (its text is a URL or a `nostr:` URI), or
491
+ * text that does not start with a space or a sentence's closing punctuation.
492
+ */
493
+ function continuesUrl(next: EditorNode | undefined): boolean {
494
+ if (!next) return false
495
+ if (next.type === REFERENCE_NODE) return true
496
+ if (next.type !== 'text' || !next.text) return false
497
+ return !/^(\s|[.,;:!?)\]]+(\s|$))/.test(next.text) && !/^[<>"'`]/.test(next.text)
498
+ }
499
+
500
+ /** A run that points somewhere is its own run: its text is what it points at, never merged into the next. */
501
+ const holdsTarget = (m: InlineMarkNode) => m.type === 'reference' || m.type === 'link'
502
+
410
503
  function sameMarks(a: readonly InlineMarkNode[], b: readonly InlineMarkNode[]): boolean {
411
504
  if (a.length !== b.length) return false
412
- if (a.some((m) => m.type === 'reference') || b.some((m) => m.type === 'reference')) return false
505
+ if (a.some(holdsTarget) || b.some(holdsTarget)) return false
413
506
  return a.every((m, i) => m.type === b[i].type)
414
507
  }
415
508
 
package/src/embeds.ts CHANGED
@@ -177,6 +177,42 @@ export function cardsIn(embeds: readonly Embed[], blocks: readonly RenderBlock[]
177
177
  return out
178
178
  }
179
179
 
180
+ /**
181
+ * The `nostr:` reference an app link names, by what `resolveLink` answered for
182
+ * it (§7.7), or undefined: nothing claims it, the answer has not come back, or
183
+ * the address is one no naddr can hold (a `d` over 255 bytes), which stays a
184
+ * link rather than taking the text down with it. What an editor's URL chip
185
+ * draws as (`@estiva-app/ui/editor`'s `LinkChips`).
186
+ */
187
+ export function referenceOfLink(url: string, resolveLink: LinkResolver): string | undefined {
188
+ const value = normalise(resolveLink(url) ?? '')
189
+ if (!value) return undefined
190
+ try {
191
+ return `nostr:${EVENT_ID.test(value) ? encodeNevent({ id: value, relays: [] }) : addrToNaddr(value)}`
192
+ } catch {
193
+ return undefined
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The app links an editor may turn into chips in one text, where each sits:
199
+ * bare http(s) URLs, trailing punctuation left to the sentence. A
200
+ * `[words](https://…)` is the marker format's link on words and is skipped, as
201
+ * {@link linksAsReferences} skips it.
202
+ */
203
+ export function urlRunsIn(text: string): { url: string; from: number; to: number }[] {
204
+ if (!text.includes('://')) return []
205
+ const out: { url: string; from: number; to: number }[] = []
206
+ for (const m of text.matchAll(LINK_OR_URL)) {
207
+ if (m[1]) continue
208
+ const start = m.index
209
+ if (text.slice(Math.max(0, start - 2), start) === '](' || text[start - 1] === '[') continue
210
+ const url = trimUrl(m[0])
211
+ out.push({ url, from: start, to: start + url.length })
212
+ }
213
+ return out
214
+ }
215
+
180
216
  /**
181
217
  * One pass over a run: a link on words, `[words](https://…)` as the marker
182
218
  * format writes it (group 1 — its URL is the target of words the author chose),
@@ -204,21 +240,21 @@ const LINK_OR_URL = /(\[[^[\]\n]+\]\((?:https?:\/\/|mailto:)[^\s)]+\))|(https?:\
204
240
  * not come back yet — which stays a link. The run keeps the URL as its text,
205
241
  * so a reader that draws references as text shows what was written.
206
242
  *
207
- * Messages only: a description is a block document, whose links are not this
208
- * function's business (§13.3).
243
+ * A block document's too, since 0.33.0 (§13.3): a description's URL reads as
244
+ * its chip as a message's does. There a run whose text is its own `link` mark's
245
+ * `href` is that URL, and keeps the card its writer chose (`embed`); a link on
246
+ * other words stays a link.
209
247
  */
210
248
  export function linksAsReferences(blocks: readonly RenderBlock[], resolveLink: LinkResolver): RenderBlock[] {
211
- const referenceOf = (url: string): string | undefined => {
212
- const value = normalise(resolveLink(url) ?? '')
213
- if (!value) return undefined
214
- // An address no naddr can hold (a `d` over 255 bytes) stays a link rather than taking the message down with it.
215
- try {
216
- return `nostr:${EVENT_ID.test(value) ? encodeNevent({ id: value, relays: [] }) : addrToNaddr(value)}`
217
- } catch {
218
- return undefined
219
- }
220
- }
249
+ const referenceOf = (url: string) => referenceOfLink(url, resolveLink)
221
250
  const split = (run: RenderInline): RenderInline[] => {
251
+ if (run.href !== undefined) {
252
+ // A block document's link: the URL as its own words is the URL, and takes its card along.
253
+ const reference = !run.reference && run.text === run.href && !run.marks.includes('code') ? referenceOf(run.href) : undefined
254
+ if (!reference) return [run]
255
+ const { href: _href, ...rest } = run
256
+ return [{ ...rest, reference }]
257
+ }
222
258
  if (run.reference || run.marks.includes('code') || !run.text.includes('://')) return [run]
223
259
  const out: RenderInline[] = []
224
260
  let at = 0
package/src/events.ts CHANGED
@@ -120,6 +120,13 @@ export const KIND = {
120
120
  /** NIP-FC File — see docs/buzz-compat/nips/NIP-FC.md in the Peek repo. */
121
121
  FILE: 30840,
122
122
  // 30841 (NIP-FC Component) is retired — never reallocate it (COM-3, KINDS.md).
123
+ /**
124
+ * The document — a file type an app owns through its `kind:31990`, as Ship
125
+ * owns an issue; Leaf is the first owner. The bare file's shape, but owned:
126
+ * a document is written and opened in its owner's app, where a topic
127
+ * (`FILE`) is a conversation nobody owns (SPEC, Miky 2026-10-14).
128
+ */
129
+ DOCUMENT: 30842,
123
130
  /**
124
131
  * NIP-42 relay auth — the challenge response that turns a connected socket
125
132
  * into an authenticated one (`Kind::Authentication`, PEE-5).
@@ -974,6 +981,24 @@ export function buildBareFile(
974
981
  }
975
982
  }
976
983
 
984
+ /**
985
+ * kind:30842 — the document (SPEC, decided by Miky 2026-10-14).
986
+ *
987
+ * The bare file's shape and tag order — `d`, `title`, `h` (REQUIRED, and the
988
+ * relay refuses one without it), then `a` if it sits under another file of any
989
+ * kind — under a kind an app owns through its manifest. Leaf's "New document"
990
+ * writes it. Its text is then the `description` field like every file's, so
991
+ * the author saves through a change too and `document` is only the first text.
992
+ */
993
+ export function buildDocument(
994
+ pubkey: string,
995
+ createdAtMs: number,
996
+ args: Parameters<typeof buildBareFile>[2],
997
+ ): UnsignedEvent {
998
+ if (!args.channelUuid) throw new Error('a document must name the Folder it lives in (h)')
999
+ return { ...buildBareFile(pubkey, createdAtMs, args), kind: KIND.DOCUMENT }
1000
+ }
1001
+
977
1002
  /**
978
1003
  * kind:9802 highlight — NIP-84.
979
1004
  *
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.32.0'
50
+ export const PROTOCOL_VERSION = '0.34.0'
51
51
 
52
52
  export {
53
53
  // types
@@ -94,6 +94,7 @@ export {
94
94
  buildMessage,
95
95
  buildResolution,
96
96
  buildBareFile,
97
+ buildDocument,
97
98
  buildHighlight,
98
99
  buildUnsignedRelayAuthEvent,
99
100
  } from './events.js'
@@ -225,6 +226,9 @@ export {
225
226
  renderTreeText,
226
227
  standaloneReference,
227
228
  referencesIn,
229
+ type BlockCard,
230
+ blockCards,
231
+ cardLayout,
228
232
  } from './render.js'
229
233
 
230
234
  export {
@@ -259,7 +263,7 @@ export {
259
263
  resolveBlockAnchor,
260
264
  resolvePart,
261
265
  } from './anchors.js'
262
- export { type Embed, type EmbedLayout, type LinkResolver, EMBED_TAG, cardsIn, embedTag, embedsOf, linksAsReferences } from './embeds.js'
266
+ export { type Embed, type EmbedLayout, type LinkResolver, EMBED_TAG, cardsIn, embedTag, embedsOf, linksAsReferences, referenceOfLink, urlRunsIn } from './embeds.js'
263
267
  export {
264
268
  type BlossomVerb,
265
269
  type Imeta,
package/src/render.ts CHANGED
@@ -35,9 +35,11 @@ import {
35
35
  type InlineTextNode,
36
36
  parseBodySegments,
37
37
  parseInlineMarks,
38
+ targetMark,
38
39
  } from './content.js'
39
40
  import { type Block, type BlockDocument, type CalloutTone, parseBlockDocument, inlineTextOf, listItemDepths, listItemChecked, calloutTone } from './blocks.js'
40
41
  import type { SignedEvent } from './events.js'
42
+ import { type LinkResolver, referenceOfLink } from './embeds.js'
41
43
 
42
44
  /** A run of text and the marks on it. Nothing here needs escaping; it is text. */
43
45
  export interface RenderInline {
@@ -51,6 +53,18 @@ export interface RenderInline {
51
53
  * nothing still shows the token rather than a blank.
52
54
  */
53
55
  reference?: string
56
+ /**
57
+ * The card its writer chose for this reference in a block document (§13.3,
58
+ * "A reference's card"): absent for none. A message's cards are its `embed`
59
+ * tags instead (§13.6.2), so a marker body never has one.
60
+ */
61
+ embed?: 'compact' | 'detailed'
62
+ /**
63
+ * The URL a block document's `link` mark points this run at (§13.3). On a run
64
+ * whose text is the URL, `linksAsReferences` turns it into the reference the
65
+ * URL names, `embed` and all; a link on words keeps it.
66
+ */
67
+ href?: string
54
68
  }
55
69
 
56
70
  /**
@@ -158,6 +172,8 @@ const KNOWN: ReadonlySet<string> = new Set([
158
172
  'blockquote', 'codeBlock', 'table', 'horizontalRule', 'attachment', 'widget',
159
173
  ])
160
174
 
175
+ const INLINE_MARKS: ReadonlySet<string> = new Set<InlineMark>(['bold', 'italic', 'underline', 'code'])
176
+
161
177
  const marksOf = (span: { bold?: boolean; italic?: boolean; underline?: boolean; code?: boolean }): InlineMark[] => {
162
178
  const out: InlineMark[] = []
163
179
  if (span.bold) out.push('bold')
@@ -232,11 +248,16 @@ function blockFromDocument(block: Block): RenderBlock {
232
248
  if (isInlineRun(block.content)) {
233
249
  out.inline = block.content.map((node) => {
234
250
  const marks = node.marks ?? []
235
- const reference = marks.find((m) => m.type === 'reference')
251
+ const reference = targetMark(marks, 'reference')
252
+ const link = reference ? undefined : targetMark(marks, 'link')
253
+ const embed = cardLayout((reference ?? link)?.embed)
236
254
  return {
237
255
  text: node.text,
238
- marks: marks.filter((m) => m.type !== 'reference').map((m) => m.type) as InlineMark[],
239
- ...(reference && 'attrs' in reference ? { reference: reference.attrs.uri } : {}),
256
+ // Only the four the vocabulary has: a mark this reader does not know is not one to draw (§13.3).
257
+ marks: marks.map((m) => m.type).filter((type): type is InlineMark => INLINE_MARKS.has(type)),
258
+ ...(reference ? { reference: reference.uri } : {}),
259
+ ...(link ? { href: link.href } : {}),
260
+ ...(embed ? { embed } : {}),
240
261
  }
241
262
  })
242
263
  } else {
@@ -328,10 +349,11 @@ export function renderTreeText(blocks: readonly RenderBlock[]): string {
328
349
  * on its line is alone on its line whether or not somebody left a space after
329
350
  * it.
330
351
  *
331
- * **For a block document (a description) only, since OPT-18.** In a message a
332
- * reference reads as its chip wherever it sits, and a card comes only from the
333
- * author's `embed` (§13.6.2). A description has no `embed` yet, so its readers
334
- * still draw a reference alone on its line as a card until it can choose one.
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.
335
357
  */
336
358
  export function standaloneReference(block: RenderBlock): string | undefined {
337
359
  if (block.type !== 'paragraph' || block.children?.length) return undefined
@@ -341,6 +363,58 @@ export function standaloneReference(block: RenderBlock): string | undefined {
341
363
  return only.reference && only.text.trim() === only.reference ? only.reference : undefined
342
364
  }
343
365
 
366
+ // ── A reference's card in a block document — SPEC §13.3 ─────────────────────
367
+
368
+ /**
369
+ * `attrs.embed` on a reference mark, read: `compact`, `detailed`, or absent for
370
+ * no card. A string this reader does not know is `compact` — the writer asked
371
+ * for a card, and the smallest is the safe reading, as for a message's `embed`
372
+ * tag (§13.6.2). `none`, a non-string and absence are all no card.
373
+ */
374
+ export function cardLayout(raw: unknown): 'compact' | 'detailed' | undefined {
375
+ // An empty string names no layout: no card, as an editor saves it.
376
+ if (typeof raw !== 'string' || raw === '' || raw === 'none') return undefined
377
+ return raw === 'detailed' ? 'detailed' : 'compact'
378
+ }
379
+
380
+ /** One card a block document asks for: the reference it hangs from, and how much to show. */
381
+ export interface BlockCard {
382
+ /** The `nostr:` URI, as the reference mark carries it. */
383
+ reference: string
384
+ layout: 'compact' | 'detailed'
385
+ }
386
+
387
+ /**
388
+ * The cards to draw after this block, in the order their references appear
389
+ * (§13.3, "A reference's card"). Only the block's own runs: a list's cards hang
390
+ * from each item, so a reader asks each item.
391
+ *
392
+ * Each occurrence is its own card, so the same object twice may draw twice. A
393
+ * reference split across runs (part of it bold) is one occurrence, and takes
394
+ * its card from its first run.
395
+ *
396
+ * A link carries its card the same way. Read the block through
397
+ * `linksAsReferences` first and a URL is its reference already; a link on
398
+ * other words draws its card only when `resolveLink` says what its `href`
399
+ * names (§7.7), and without one names nothing.
400
+ *
401
+ * Inside a card's body or a part a reader asks nothing: there every reference
402
+ * is its chip (§13.3), or two objects that card each other nest forever.
403
+ */
404
+ export function blockCards(block: RenderBlock, resolveLink?: LinkResolver): BlockCard[] {
405
+ const out: BlockCard[] = []
406
+ let previous: string | undefined
407
+ for (const run of block.inline ?? []) {
408
+ const target = run.reference ?? (run.href !== undefined ? `href:${run.href}` : undefined)
409
+ if (target && target === previous) continue
410
+ previous = target
411
+ if (!run.embed) continue
412
+ const reference = run.reference ?? (run.href !== undefined && resolveLink ? referenceOfLink(run.href, resolveLink) : undefined)
413
+ if (reference) out.push({ reference, layout: run.embed })
414
+ }
415
+ return out
416
+ }
417
+
344
418
  /**
345
419
  * Every `nostr:` reference in a resolved tree, in the order they are written.
346
420
  *