@estiva-app/protocol 0.34.0 → 0.36.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,204 @@
1
+ /**
2
+ * A description's text, read whole — SPEC §13.3 "A description as text".
3
+ *
4
+ * {@link markerTextToBlockDocument} with `{ description: true }` reads every
5
+ * block that text spells except one: a table, which §13.2's markers have no
6
+ * syntax for. This reads that too — a GFM pipe table (a header row, a `| --- |`
7
+ * row, then rows, `\|` for a pipe in a cell) becomes a `table` block shaped as
8
+ * an editor saves one. It is the one reader for text that becomes a
9
+ * description: the agent's `edit-issue`, and a markdown paste into an editor
10
+ * that saves a block document (LEAF-10). Moved here from the agent CLI
11
+ * (RIC-20, estiva-agent#75) so the two cannot read the same text differently.
12
+ *
13
+ * A message's text is not read this way: §13.2 has no table, so a pasted table
14
+ * stays text in a message (Miky, 2026-10-15, LEAF-10).
15
+ */
16
+ import { type Block, type BlockDocument, inlineTextOf, newBlockId } from './blocks.js'
17
+ import { blockDocumentToMarkerText, markerTextToBlockDocument } from './bridge-content.js'
18
+ import { fenceCloses } from './content.js'
19
+
20
+ const DESCRIPTION = { description: true }
21
+
22
+ const doc = (content: Block[]): BlockDocument => ({ type: 'doc', content })
23
+
24
+ /** Child blocks, as opposed to an inline run or nothing. */
25
+ const childBlocks = (block: Block): Block[] | undefined =>
26
+ Array.isArray(block.content) && block.content.length > 0 && block.content.every((node) => typeof (node as Block).id === 'string')
27
+ ? (block.content as Block[])
28
+ : undefined
29
+
30
+ /**
31
+ * Text as a description's block document: marker text read with
32
+ * `{ description: true }`, with each GFM pipe table read as a `table` block.
33
+ * A table is a block boundary, so it stands in the marker text as a
34
+ * placeholder paragraph of its own. `previous` lends the other blocks their
35
+ * ids by index among the blocks that are not tables, so a table added or
36
+ * removed above a paragraph does not cost that paragraph its id. A table
37
+ * takes the ids of a table in `previous` that prints the same; failing that,
38
+ * of the table at its position, but only when the text has as many tables as
39
+ * `previous` — else a deleted table's ids would pass to the next one.
40
+ */
41
+ export function descriptionTextToBlockDocument(text: string, previous?: BlockDocument): BlockDocument {
42
+ const before = previous?.content ?? []
43
+ const mark = placeholderFor(text)
44
+ const tables: string[][][] = []
45
+ const lines = text.split('\n')
46
+ const out: string[] = []
47
+ for (let i = 0; i < lines.length; i++) {
48
+ const line = lines[i]
49
+ const fenceEnd = fenceCloses(lines, i)
50
+ if (fenceEnd !== -1) {
51
+ out.push(...lines.slice(i, fenceEnd + 1))
52
+ i = fenceEnd
53
+ continue
54
+ }
55
+ const header = PIPE.test(line) ? rowCells(line) : undefined
56
+ if (!header || i + 1 >= lines.length || !isSeparator(lines[i + 1], header.length)) {
57
+ out.push(line)
58
+ continue
59
+ }
60
+ const rows = [header]
61
+ for (i += 2; i < lines.length && lines[i].trim() && PIPE.test(lines[i]); i++) rows.push(rowCells(lines[i]))
62
+ i--
63
+ out.push('', `${mark}${tables.length}${mark}`, '')
64
+ tables.push(rows)
65
+ }
66
+ const aligned = before.filter((block) => block.type !== 'table')
67
+ if (!tables.length) return markerTextToBlockDocument(text, doc(aligned), DESCRIPTION)
68
+
69
+ // Which blocks are tables' places is known before ids are lent: the blocks
70
+ // the text spells do not depend on `previous`.
71
+ const marked = out.join('\n')
72
+ const places = new Map(tables.map((_, n) => [`${mark}${n}${mark}`, n]))
73
+ const placeOf = (block: Block) => (block.type === 'paragraph' ? places.get(inlineTextOf(block)) : undefined)
74
+ markerTextToBlockDocument(marked, undefined, DESCRIPTION).content.forEach((block, i) => {
75
+ if (placeOf(block) !== undefined) aligned.splice(i, 0, { type: 'paragraph', id: '' })
76
+ })
77
+
78
+ const oldTables = before.filter((block) => block.type === 'table')
79
+ const used = new Set<Block>()
80
+ const lend = (rows: string[][], n: number): Block | undefined => {
81
+ const printed = tableToDescriptionText(tableBlock(rows, undefined))
82
+ const same = oldTables.find((old) => !used.has(old) && printed !== undefined && tableToDescriptionText(old) === printed)
83
+ const positional = oldTables.length === tables.length && !used.has(oldTables[n]) ? oldTables[n] : undefined
84
+ const old = same ?? positional
85
+ if (old) used.add(old)
86
+ return old
87
+ }
88
+ return doc(
89
+ markerTextToBlockDocument(marked, doc(aligned), DESCRIPTION).content.map((block) => {
90
+ const n = placeOf(block)
91
+ return n === undefined ? block : tableBlock(tables[n], lend(tables[n], n))
92
+ }),
93
+ )
94
+ }
95
+
96
+ /**
97
+ * A mark the text does not hold, so nothing a person writes — or pastes — is
98
+ * mistaken for a table's place: a private-use character, or, in text that
99
+ * holds every one of them, one followed by a counter.
100
+ */
101
+ function placeholderFor(text: string): string {
102
+ for (let code = 0xe000; code <= 0xf8ff; code++) {
103
+ const mark = String.fromCharCode(code)
104
+ if (!text.includes(mark)) return mark
105
+ }
106
+ let n = 0
107
+ while (text.includes(`${n}x`)) n++
108
+ return `${n}x`
109
+ }
110
+
111
+ /** An unescaped pipe: a line that can be a table's header or row. */
112
+ const PIPE = /(?<!\\)\|/
113
+
114
+ /** A row's cells, outer pipes optional, `\|` read as a literal pipe. */
115
+ function rowCells(line: string): string[] {
116
+ const inner = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '')
117
+ return inner.split(/(?<!\\)\|/).map((cell) => cell.trim().replace(/\\\|/g, '|'))
118
+ }
119
+
120
+ /** GFM's delimiter row: one `---` (optionally `:`-aligned) per header cell. */
121
+ function isSeparator(line: string, width: number): boolean {
122
+ if (!PIPE.test(line)) return false
123
+ const cells = rowCells(line)
124
+ return cells.length === width && cells.every((cell) => /^:?-+:?$/.test(cell))
125
+ }
126
+
127
+ /** A table as wide as its widest row, so no cell's text is lost. */
128
+ function tableBlock(rows: string[][], old: Block | undefined): Block {
129
+ const width = Math.max(...rows.map((cells) => cells.length))
130
+ const oldRows = old ? (childBlocks(old) ?? []) : []
131
+ return {
132
+ type: 'table',
133
+ id: old?.id ?? newBlockId(),
134
+ content: rows.map((cells, r) => {
135
+ const oldCells = oldRows[r] ? (childBlocks(oldRows[r]) ?? []) : []
136
+ const type = r === 0 ? 'tableHeader' : 'tableCell'
137
+ return {
138
+ type: 'tableRow',
139
+ id: oldRows[r]?.id ?? newBlockId(),
140
+ content: Array.from({ length: width }, (_, c) => tableCell(type, cells[c] ?? '', oldCells[c]?.type === type ? oldCells[c] : undefined)),
141
+ }
142
+ }),
143
+ }
144
+ }
145
+
146
+ /** A cell as an editor saves one: one paragraph, the text's inline marks kept. */
147
+ function tableCell(type: string, text: string, old: Block | undefined): Block {
148
+ const [parsed, ...more] = text ? markerTextToBlockDocument(text).content : []
149
+ const paragraph: Block =
150
+ parsed?.type === 'paragraph' && !more.length ? parsed : text ? { type: 'paragraph', id: '', content: [{ type: 'text', text }] } : { type: 'paragraph', id: '' }
151
+ const oldParagraph = old ? childBlocks(old)?.[0] : undefined
152
+ return {
153
+ type,
154
+ id: old?.id ?? newBlockId(),
155
+ attrs: old?.attrs ?? { colspan: 1, rowspan: 1 },
156
+ content: [{ ...paragraph, id: oldParagraph?.type === 'paragraph' ? oldParagraph.id : newBlockId() }],
157
+ }
158
+ }
159
+
160
+ /**
161
+ * A table as GFM text, for a table text can carry: a header row first, and
162
+ * each cell one paragraph on one line. `undefined` for any other table, which
163
+ * §13.3 gives no spelling.
164
+ */
165
+ export function tableToDescriptionText(block: Block): string | undefined {
166
+ const rows = (childBlocks(block) ?? []).map((row) => childBlocks(row) ?? [])
167
+ if (!rows.length || !rows[0].length) return undefined
168
+ const lines: string[] = []
169
+ for (const [r, cells] of rows.entries()) {
170
+ if (cells.some((cell) => cell.type !== (r === 0 ? 'tableHeader' : 'tableCell'))) return undefined
171
+ const texts = cells.map((cell) => {
172
+ const children = childBlocks(cell) ?? []
173
+ if (children.length > 1 || (children[0] && children[0].type !== 'paragraph')) return undefined
174
+ const line = children[0] && Array.isArray(children[0].content) ? cellParagraphText(children[0]) : ''
175
+ return line.includes('\n') ? undefined : line.replace(/\|/g, '\\|')
176
+ })
177
+ if (texts.some((t) => t === undefined)) return undefined
178
+ lines.push(`| ${texts.join(' | ')} |`)
179
+ if (r === 0) lines.push(`| ${cells.map(() => '---').join(' | ')} |`)
180
+ }
181
+ return lines.join('\n')
182
+ }
183
+
184
+ /**
185
+ * A cell's paragraph as marker text, with the whitespace that ends its run
186
+ * dropped first: an editor saves some runs as `"text\n"`, which nobody sees
187
+ * but which would make the cell two lines.
188
+ */
189
+ const cellParagraphText = (paragraph: Block) => blockDocumentToMarkerText(doc([trimRun(paragraph)]), DESCRIPTION)
190
+
191
+ function trimRun(block: Block): Block {
192
+ const run = [...(block.content as { type: string; text?: string }[])]
193
+ while (run.length) {
194
+ const last = run[run.length - 1]
195
+ if (last.type !== 'text' || typeof last.text !== 'string') break
196
+ const trimmedText = last.text.trimEnd()
197
+ if (trimmedText) {
198
+ run[run.length - 1] = { ...last, text: trimmedText }
199
+ break
200
+ }
201
+ run.pop()
202
+ }
203
+ return { ...block, content: run as Block['content'] }
204
+ }
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.34.0'
50
+ export const PROTOCOL_VERSION = '0.36.0'
51
51
 
52
52
  export {
53
53
  // types
@@ -237,6 +237,8 @@ export {
237
237
  type DescriptionTextOptions,
238
238
  } from './bridge-content.js'
239
239
 
240
+ export { descriptionTextToBlockDocument, tableToDescriptionText } from './description-text.js'
241
+
240
242
  export {
241
243
  type EditorNode,
242
244
  type EditorDocument,