@estiva-app/protocol 0.47.0 → 0.49.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,75 @@
1
+ /**
2
+ * Merging two changes to one text — SPEC §13.3, conformance C41 and C42.
3
+ *
4
+ * When the relay refuses a text save with `conflict:` (§6.2), its app merges
5
+ * three texts: the **base**, the text its save named as `prev`; **theirs**, the
6
+ * text now current; and **mine**, the refused one. Every app merges by this
7
+ * rule, so two crossing saves give the same text whichever app was refused.
8
+ *
9
+ * Words are never lost: a block both sides changed differently, or one side
10
+ * deleted while the other edited, **asks**, and while anything asks nothing of
11
+ * mine is saved. Everything else merges quietly.
12
+ *
13
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md
14
+ */
15
+ import { type Block, type BlockDocument } from './blocks.js';
16
+ /** One of the three texts, with the `content-format` its event carried. */
17
+ export interface MergeText {
18
+ value: string;
19
+ /** `'estiva-blocks-1'` for a block document; anything else, or none, is one block. */
20
+ format?: string;
21
+ }
22
+ /**
23
+ * A block the merge cannot settle without its person.
24
+ *
25
+ * - `changed-by-both`: both sides changed its own content, differently.
26
+ * - `edited-and-deleted`: one side deleted it, or the block it sits under,
27
+ * and the other changed, added or moved it there.
28
+ *
29
+ * `block` is the block's id, or `null` when the text is not a block document
30
+ * and so is one block. `theirs` and `mine` are each side's version as plain
31
+ * text, absent on the side that deleted it; `theirsBlock` and `mineBlock` are
32
+ * the blocks themselves, for a change plain text does not show (a heading's
33
+ * level).
34
+ */
35
+ export interface MergeAsk {
36
+ block: string | null;
37
+ why: 'changed-by-both' | 'edited-and-deleted';
38
+ base?: string;
39
+ theirs?: string;
40
+ mine?: string;
41
+ baseBlock?: Block;
42
+ theirsBlock?: Block;
43
+ mineBlock?: Block;
44
+ }
45
+ export type TextMerge = {
46
+ merged: MergeText;
47
+ asks?: undefined;
48
+ } | {
49
+ merged?: undefined;
50
+ asks: MergeAsk[];
51
+ };
52
+ export type BlockMerge = {
53
+ merged: BlockDocument;
54
+ asks?: undefined;
55
+ } | {
56
+ merged?: undefined;
57
+ asks: MergeAsk[];
58
+ };
59
+ /**
60
+ * Merge two block documents that both started from `base` — §13.3's rule.
61
+ *
62
+ * Returns the merged document, keeping every block id the merge kept, or the
63
+ * blocks that ask. When anything asks, there is no merged document: nothing of
64
+ * mine is saved.
65
+ */
66
+ export declare function mergeBlockDocuments(base: BlockDocument, theirs: BlockDocument, mine: BlockDocument): BlockMerge;
67
+ /**
68
+ * Merge three texts by §13.3's rule.
69
+ *
70
+ * When all three are block documents, block by block; otherwise the text is
71
+ * one block, so a change by both sides asks unless the two are equal. Mine
72
+ * unchanged from the base gives theirs, and theirs unchanged gives mine.
73
+ */
74
+ export declare function mergeTexts(base: MergeText, theirs: MergeText, mine: MergeText): TextMerge;
75
+ //# sourceMappingURL=merge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge.d.ts","sourceRoot":"","sources":["../src/merge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,KAAK,KAAK,EACV,KAAK,aAAa,EAInB,MAAM,aAAa,CAAA;AAMpB,2EAA2E;AAC3E,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,sFAAsF;IACtF,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,GAAG,EAAE,iBAAiB,GAAG,oBAAoB,CAAA;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,KAAK,CAAA;IACjB,WAAW,CAAC,EAAE,KAAK,CAAA;IACnB,SAAS,CAAC,EAAE,KAAK,CAAA;CAClB;AAED,MAAM,MAAM,SAAS,GAAG;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,MAAM,CAAC,EAAE,SAAS,CAAC;IAAC,IAAI,EAAE,QAAQ,EAAE,CAAA;CAAE,CAAA;AAE1G,MAAM,MAAM,UAAU,GAAG;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,IAAI,CAAC,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,MAAM,CAAC,EAAE,SAAS,CAAC;IAAC,IAAI,EAAE,QAAQ,EAAE,CAAA;CAAE,CAAA;AA0I/G;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,aAAa,GAAG,UAAU,CA2H/G;AA8BD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,GAAG,SAAS,CAgBzF"}
package/dist/merge.js ADDED
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Merging two changes to one text — SPEC §13.3, conformance C41 and C42.
3
+ *
4
+ * When the relay refuses a text save with `conflict:` (§6.2), its app merges
5
+ * three texts: the **base**, the text its save named as `prev`; **theirs**, the
6
+ * text now current; and **mine**, the refused one. Every app merges by this
7
+ * rule, so two crossing saves give the same text whichever app was refused.
8
+ *
9
+ * Words are never lost: a block both sides changed differently, or one side
10
+ * deleted while the other edited, **asks**, and while anything asks nothing of
11
+ * mine is saved. Everything else merges quietly.
12
+ *
13
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md
14
+ */
15
+ import { documentText, parseBlockDocument, serializeBlockDocument, } from './blocks.js';
16
+ /** The content format a block document is tagged with (§13.4). */
17
+ const BLOCKS_FORMAT = 'estiva-blocks-1';
18
+ const isInlineRun = (content) => Array.isArray(content) && content.every((n) => typeof n === 'object' && n !== null && n.type === 'text');
19
+ /** A node whose content holds blocks: every one of them has an id. */
20
+ const childBlocksOf = (block) => Array.isArray(block.content) && block.content.length > 0 && !isInlineRun(block.content) &&
21
+ block.content.every((child) => typeof child.id === 'string' && child.id !== '')
22
+ ? block.content
23
+ : undefined;
24
+ function ownContentOf(block) {
25
+ const { id: _id, content, ...rest } = block;
26
+ const own = { ...rest };
27
+ // A block's children are blocks of their own: where they sit is a move,
28
+ // what they say is theirs. Everything else in it is this block's words.
29
+ // An empty content is no words: an emptied list has not been rewritten.
30
+ if (content !== undefined && !childBlocksOf(block) && !(Array.isArray(content) && content.length === 0))
31
+ own.content = content;
32
+ return stableJson(own);
33
+ }
34
+ /** JSON with object keys sorted, so an editor's key order is not a change. */
35
+ function stableJson(value) {
36
+ if (Array.isArray(value))
37
+ return `[${value.map(stableJson).join(',')}]`;
38
+ if (value && typeof value === 'object') {
39
+ const entries = Object.entries(value)
40
+ .filter(([, v]) => v !== undefined)
41
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
42
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(',')}}`;
43
+ }
44
+ return JSON.stringify(value);
45
+ }
46
+ function indexOf(doc) {
47
+ const byId = new Map();
48
+ const children = new Map([[null, []]]);
49
+ const order = [];
50
+ const walk = (blocks, parent) => {
51
+ for (const block of blocks) {
52
+ byId.set(block.id, { block, parent, own: ownContentOf(block) });
53
+ children.get(parent).push(block.id);
54
+ order.push(block.id);
55
+ children.set(block.id, []);
56
+ const kids = childBlocksOf(block);
57
+ if (kids)
58
+ walk(kids, block.id);
59
+ }
60
+ };
61
+ walk(doc.content, null);
62
+ return { byId, children, order };
63
+ }
64
+ /**
65
+ * The blocks one side moved, against the base.
66
+ *
67
+ * A block is moved when its parent changed, or when, among the blocks under
68
+ * that parent that both the base and this side hold, it is outside the longest
69
+ * run still in the base's order — on a tie, the run whose first difference
70
+ * comes earlier in the base. So a neighbour added or deleted moves nothing, and
71
+ * moving one block moves only that one.
72
+ */
73
+ function movedOn(base, side) {
74
+ const moved = new Set();
75
+ for (const [id, placed] of side.byId) {
76
+ const was = base.byId.get(id);
77
+ if (was && was.parent !== placed.parent)
78
+ moved.add(id);
79
+ }
80
+ for (const [parent, ids] of side.children) {
81
+ const baseIds = base.children.get(parent);
82
+ if (!baseIds)
83
+ continue;
84
+ const basePos = new Map(baseIds.map((id, i) => [id, i]));
85
+ // Under this parent on both sides, in this side's order, as base positions.
86
+ const shared = ids.filter((id) => basePos.has(id));
87
+ const seq = shared.map((id) => basePos.get(id));
88
+ for (const i of outsideLongestRun(seq))
89
+ moved.add(shared[i]);
90
+ }
91
+ return moved;
92
+ }
93
+ /**
94
+ * The indexes of `seq` outside its longest increasing run, choosing among
95
+ * equally long runs the one smallest in the base's order at its first
96
+ * difference.
97
+ */
98
+ function outsideLongestRun(seq) {
99
+ const n = seq.length;
100
+ // longest[i]: the longest increasing run starting at i.
101
+ const longest = new Array(n).fill(1);
102
+ for (let i = n - 1; i >= 0; i--) {
103
+ for (let j = i + 1; j < n; j++) {
104
+ if (seq[j] > seq[i] && longest[j] + 1 > longest[i])
105
+ longest[i] = longest[j] + 1;
106
+ }
107
+ }
108
+ const best = Math.max(0, ...longest);
109
+ const kept = new Set();
110
+ let from = 0;
111
+ let floor = -1;
112
+ for (let need = best; need > 0; need--) {
113
+ let pick = -1;
114
+ for (let j = from; j < n; j++) {
115
+ if (seq[j] > floor && longest[j] >= need && (pick === -1 || seq[j] < seq[pick]))
116
+ pick = j;
117
+ }
118
+ kept.add(pick);
119
+ floor = seq[pick];
120
+ from = pick + 1;
121
+ }
122
+ return seq.map((_, i) => i).filter((i) => !kept.has(i));
123
+ }
124
+ /** A block as plain text, its own words only (not the blocks inside it). */
125
+ function ownText(block) {
126
+ if (!block)
127
+ return undefined;
128
+ const kids = childBlocksOf(block);
129
+ const alone = kids ? { ...block, content: undefined } : block;
130
+ return documentText({ type: 'doc', content: [alone] });
131
+ }
132
+ /** A block with no blocks inside it, its own content kept: the merge places its children. */
133
+ function shellOf(block) {
134
+ return childBlocksOf(block) ? { ...block, content: [] } : { ...block };
135
+ }
136
+ /**
137
+ * Merge two block documents that both started from `base` — §13.3's rule.
138
+ *
139
+ * Returns the merged document, keeping every block id the merge kept, or the
140
+ * blocks that ask. When anything asks, there is no merged document: nothing of
141
+ * mine is saved.
142
+ */
143
+ export function mergeBlockDocuments(base, theirs, mine) {
144
+ const B = indexOf(base);
145
+ const T = indexOf(theirs);
146
+ const M = indexOf(mine);
147
+ const movedT = movedOn(B, T);
148
+ const movedM = movedOn(B, M);
149
+ const asks = [];
150
+ const ask = (id, why) => {
151
+ const b = B.byId.get(id)?.block;
152
+ const t = T.byId.get(id)?.block;
153
+ const m = M.byId.get(id)?.block;
154
+ asks.push({
155
+ block: id,
156
+ why,
157
+ ...(b ? { base: ownText(b), baseBlock: b } : {}),
158
+ ...(t ? { theirs: ownText(t), theirsBlock: t } : {}),
159
+ ...(m ? { mine: ownText(m), mineBlock: m } : {}),
160
+ });
161
+ };
162
+ // What each kept block says, and the blocks the merge deletes.
163
+ const content = new Map();
164
+ const deleted = new Set();
165
+ // In the base's order, so blocks that ask come in the order the text had.
166
+ const ids = new Set([...B.order, ...T.order, ...M.order]);
167
+ for (const id of ids) {
168
+ const b = B.byId.get(id);
169
+ const t = T.byId.get(id);
170
+ const m = M.byId.get(id);
171
+ if (!b) {
172
+ // Added. Both adding one id is one block, kept once when they agree.
173
+ if (t && m && t.own !== m.own)
174
+ ask(id, 'changed-by-both');
175
+ else
176
+ content.set(id, shellOf((t ?? m).block));
177
+ continue;
178
+ }
179
+ const changedT = !!t && t.own !== b.own;
180
+ const changedM = !!m && m.own !== b.own;
181
+ if (!t || !m) {
182
+ // Deleted on one side or both. Against an edit it asks; against a move
183
+ // or nothing, it is deleted: a move changes no words.
184
+ if ((!t && changedM) || (!m && changedT))
185
+ ask(id, 'edited-and-deleted');
186
+ else
187
+ deleted.add(id);
188
+ continue;
189
+ }
190
+ if (changedT && changedM && t.own !== m.own) {
191
+ ask(id, 'changed-by-both');
192
+ continue;
193
+ }
194
+ content.set(id, shellOf(changedM && !changedT ? m.block : t.block));
195
+ }
196
+ // The order is theirs, less what the merge deletes.
197
+ const kids = new Map();
198
+ const parentOf = new Map();
199
+ for (const [parent, list] of T.children) {
200
+ if (parent !== null && !content.has(parent))
201
+ continue;
202
+ kids.set(parent, list.filter((id) => content.has(id)));
203
+ for (const id of kids.get(parent))
204
+ parentOf.set(id, parent);
205
+ }
206
+ for (const id of content.keys())
207
+ if (!kids.has(id))
208
+ kids.set(id, []);
209
+ // A block theirs kept under a parent the merge deletes: theirs added, moved
210
+ // or changed it there against mine's delete.
211
+ for (const [parent, list] of T.children) {
212
+ if (parent === null || content.has(parent) || !deleted.has(parent))
213
+ continue;
214
+ for (const id of list)
215
+ if (content.has(id) && touchedBy(id, B, T, movedT))
216
+ ask(id, 'edited-and-deleted');
217
+ }
218
+ const addedByTheirs = (id) => T.byId.has(id) && !B.byId.has(id) && !M.byId.has(id);
219
+ // Then each block mine moved or added, in mine's order, is taken out and
220
+ // placed after the nearest block before it in mine that the merge keeps
221
+ // (and after any blocks theirs added right behind that one), or first under
222
+ // its parent, after theirs' additions there.
223
+ for (const id of M.order) {
224
+ if (!content.has(id))
225
+ continue;
226
+ const addedByMine = !B.byId.has(id) && !T.byId.has(id);
227
+ const mineMoved = movedM.has(id) && !movedT.has(id);
228
+ if (!addedByMine && !mineMoved)
229
+ continue;
230
+ const parent = M.byId.get(id).parent;
231
+ if (parent !== null && !content.has(parent)) {
232
+ ask(id, 'edited-and-deleted');
233
+ continue;
234
+ }
235
+ // Mine puts it under a block theirs has meanwhile put inside it: both
236
+ // moved, so theirs stands rather than a loop that holds neither.
237
+ let above = parent;
238
+ while (above != null && above !== id)
239
+ above = parentOf.get(above);
240
+ if (above === id)
241
+ continue;
242
+ if (parentOf.has(id)) {
243
+ const from = kids.get(parentOf.get(id));
244
+ from.splice(from.indexOf(id), 1);
245
+ }
246
+ const under = kids.get(parent);
247
+ const siblings = M.children.get(parent);
248
+ let at = 0;
249
+ for (let i = siblings.indexOf(id) - 1; i >= 0; i--) {
250
+ const before = under.indexOf(siblings[i]);
251
+ if (before !== -1) {
252
+ at = before + 1;
253
+ break;
254
+ }
255
+ }
256
+ while (at < under.length && addedByTheirs(under[at]))
257
+ at++;
258
+ under.splice(at, 0, id);
259
+ parentOf.set(id, parent);
260
+ }
261
+ if (asks.length)
262
+ return { asks: dedupe(asks) };
263
+ const placed = new Set();
264
+ const build = (parent) => kids.get(parent).map((id) => {
265
+ placed.add(id);
266
+ const block = content.get(id);
267
+ const inner = build(id);
268
+ return inner.length || wasParent(id, B, T, M) ? { ...block, content: inner } : block;
269
+ });
270
+ const merged = { ...theirs, content: build(null) };
271
+ // Never lose words: a block the merge kept but could not place asks.
272
+ for (const id of content.keys())
273
+ if (!placed.has(id))
274
+ ask(id, 'changed-by-both');
275
+ if (asks.length)
276
+ return { asks: dedupe(asks) };
277
+ return { merged };
278
+ }
279
+ /** Whether a block's own content held blocks on any side: an emptied list stays a list. */
280
+ function wasParent(id, ...sides) {
281
+ return sides.some((side) => {
282
+ const block = side.byId.get(id)?.block;
283
+ return !!block && !!childBlocksOf(block);
284
+ });
285
+ }
286
+ function touchedBy(id, base, side, moved) {
287
+ const b = base.byId.get(id);
288
+ const s = side.byId.get(id);
289
+ return !b || moved.has(id) || (!!s && s.own !== b.own);
290
+ }
291
+ function dedupe(asks) {
292
+ const seen = new Set();
293
+ return asks.filter((a) => (seen.has(a.block) ? false : (seen.add(a.block), true)));
294
+ }
295
+ function asDocument(text) {
296
+ if (text.format !== BLOCKS_FORMAT)
297
+ return undefined;
298
+ try {
299
+ return parseBlockDocument(text.value);
300
+ }
301
+ catch {
302
+ return undefined;
303
+ }
304
+ }
305
+ /**
306
+ * Merge three texts by §13.3's rule.
307
+ *
308
+ * When all three are block documents, block by block; otherwise the text is
309
+ * one block, so a change by both sides asks unless the two are equal. Mine
310
+ * unchanged from the base gives theirs, and theirs unchanged gives mine.
311
+ */
312
+ export function mergeTexts(base, theirs, mine) {
313
+ const same = (a, b) => a.value === b.value && (a.format ?? '') === (b.format ?? '');
314
+ if (same(mine, base) || same(mine, theirs))
315
+ return { merged: theirs };
316
+ if (same(theirs, base))
317
+ return { merged: mine };
318
+ const docs = [base, theirs, mine].map(asDocument);
319
+ if (docs.every((d) => d !== undefined)) {
320
+ const [b, t, m] = docs;
321
+ const result = mergeBlockDocuments(b, t, m);
322
+ if (result.asks)
323
+ return result;
324
+ return { merged: { value: serializeBlockDocument(result.merged), format: BLOCKS_FORMAT } };
325
+ }
326
+ const plain = (text) => {
327
+ const doc = asDocument(text);
328
+ return doc ? documentText(doc) : text.value;
329
+ };
330
+ return { asks: [{ block: null, why: 'changed-by-both', base: plain(base), theirs: plain(theirs), mine: plain(mine) }] };
331
+ }
332
+ //# sourceMappingURL=merge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge.js","sourceRoot":"","sources":["../src/merge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAGL,YAAY,EACZ,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,aAAa,CAAA;AAGpB,kEAAkE;AAClE,MAAM,aAAa,GAAG,iBAAiB,CAAA;AAqCvC,MAAM,WAAW,GAAG,CAAC,OAAgB,EAA+B,EAAE,CACpE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAK,CAAwB,CAAC,IAAI,KAAK,MAAM,CAAC,CAAA;AAElI,sEAAsE;AACtE,MAAM,aAAa,GAAG,CAAC,KAAY,EAAuB,EAAE,CAC1D,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG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KAAK,EAAE,sBAAsB,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,EAAE,CAAA;IAC5F,CAAC;IACD,MAAM,KAAK,GAAG,CAAC,IAAe,EAAE,EAAE;QAChC,MAAM,GAAG,GAAG,UAAU,CAAC,IAAI,CAAC,CAAA;QAC5B,OAAO,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAA;IAC7C,CAAC,CAAA;IACD,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAA;AACzH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/protocol",
3
- "version": "0.47.0",
3
+ "version": "0.49.0",
4
4
  "description": "The Estiva wire format: Buzz-shaped Nostr event builders, NIP-01 ids, NIP-19 naddr, NIP-98 HTTP auth, and the relay clients. Speaks the protocol; interprets nothing.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/bridge.ts CHANGED
@@ -208,10 +208,24 @@ export function parsePublishResponse(status: number, text: string): PublishResul
208
208
  export interface QueryResult {
209
209
  ok: boolean
210
210
  events: SignedEvent[]
211
+ /** With `search` (SPEC §6.13): the files found, best first. The relay's statement, never signed. */
212
+ matches?: SearchMatch[]
211
213
  reason?: string
212
214
  httpStatus?: number
213
215
  }
214
216
 
217
+ /** One file a `search` found, and which of its words held the typing — SPEC §6.13. */
218
+ export interface SearchMatch {
219
+ /** The file's address. */
220
+ a: string
221
+ match: {
222
+ /** Of `title`, `summary`, `key` and `text`, each that holds a typed word, best first. */
223
+ fields: string[]
224
+ /** The words around a typed word in the text, as plain text: an author's words, never markup. */
225
+ around?: string
226
+ }
227
+ }
228
+
215
229
  /** The relay's answer to `POST /query`, interpreted. */
216
230
  export function parseQueryResponse(status: number, text: string): QueryResult {
217
231
  if (status < 200 || status >= 300) {
@@ -225,12 +239,64 @@ export function parseQueryResponse(status: number, text: string): QueryResult {
225
239
  }
226
240
  try {
227
241
  const parsed = JSON.parse(text)
242
+ // A search answers an object (§6.13); every other read a bare array.
243
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Array.isArray(parsed.events)) {
244
+ const matches = Array.isArray(parsed.matches) ? parsed.matches.filter(isSearchMatch) : []
245
+ return { ok: true, events: parsed.events, matches, httpStatus: status }
246
+ }
228
247
  return { ok: true, events: Array.isArray(parsed) ? parsed : [], httpStatus: status }
229
248
  } catch {
230
249
  return { ok: false, events: [], reason: `unparseable response: ${text.slice(0, 200)}`, httpStatus: status }
231
250
  }
232
251
  }
233
252
 
253
+ function isSearchMatch(value: unknown): value is SearchMatch {
254
+ const m = value as SearchMatch | null
255
+ return !!m && typeof m.a === 'string' && !!m.match && Array.isArray(m.match.fields) &&
256
+ m.match.fields.every((f) => typeof f === 'string') && (m.match.around === undefined || typeof m.match.around === 'string')
257
+ }
258
+
259
+ /**
260
+ * What a relay says, in its NIP-11 document, about reading files — SPEC §6.13.
261
+ *
262
+ * - `list`: `/query` answers `"fields": "newest"` (`file_list.newest`), so an
263
+ * app reads a list with it rather than every change.
264
+ * - `text`: the read takes `"text": true` beside `#d` (`file_list.text`), so
265
+ * opening a file costs its current text, not its history. Never sent to a
266
+ * relay that does not say so: one that ignored the key would answer as if
267
+ * the text had never changed.
268
+ * - `inOrder`: the types the relay keeps in order (`files.requires_prev`), and
269
+ * whether it has made the switch at all (`files` present).
270
+ * - `search`: the types it finds by their words (`file_search.types`).
271
+ *
272
+ * A relay that says nothing reads as none of them, which is always safe: the
273
+ * app reads every change and folds them itself.
274
+ */
275
+ export interface RelayFileReads {
276
+ list: boolean
277
+ text: boolean
278
+ switched: boolean
279
+ inOrder: string[]
280
+ search: string[]
281
+ }
282
+
283
+ export function relayFileReadsOf(info: unknown): RelayFileReads {
284
+ const doc = (info && typeof info === 'object' ? info : {}) as Record<string, unknown>
285
+ const obj = (v: unknown) => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined)
286
+ const strings = (v: unknown) => (Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : [])
287
+ const files = obj(doc.files)
288
+ // A relay advertising the switch advertises the list too (§6.13); one from
289
+ // before `file_list` existed said it only under `files`.
290
+ const list = obj(doc.file_list) ?? (files?.newest === true ? { newest: true } : undefined)
291
+ return {
292
+ list: list?.newest === true,
293
+ text: list?.newest === true && list.text === true,
294
+ switched: !!files,
295
+ inOrder: strings(files?.requires_prev),
296
+ search: strings(obj(doc.file_search)?.types),
297
+ }
298
+ }
299
+
234
300
  /** What a person reads when the relay stays busy through the quiet retries. */
235
301
  export const RELAY_BUSY_MESSAGE = 'the relay is busy, try again in a moment'
236
302
 
@@ -626,11 +692,34 @@ export class Relay {
626
692
  * {@link RelayBusyError}.
627
693
  */
628
694
  async query(filters: Record<string, unknown>[]): Promise<SignedEvent[]> {
695
+ return (await this.queryWithMatches(filters)).events
696
+ }
697
+
698
+ /**
699
+ * {@link Relay.query}, keeping what a `search` found besides its events
700
+ * (SPEC §6.13): `matches` lists the files in rank order, which the events
701
+ * alone do not say.
702
+ */
703
+ async queryWithMatches(filters: Record<string, unknown>[]): Promise<{ events: SignedEvent[]; matches: SearchMatch[] }> {
629
704
  const { status, text } = await this.post('/query', filters)
630
705
  if (isRelayBusyResponse(status, text)) throw new RelayBusyError(status)
631
706
  const result = parseQueryResponse(status, text)
632
707
  if (!result.ok) throw new Error(`query failed: ${result.reason}`)
633
- return result.events
708
+ return { events: result.events, matches: result.matches ?? [] }
709
+ }
710
+
711
+ /**
712
+ * The relay's NIP-11 document, read from its own address. Unauthenticated:
713
+ * it says what the relay offers, to anyone. Throws when it cannot be read,
714
+ * so a caller can tell "says nothing" from "did not answer".
715
+ */
716
+ async info(): Promise<unknown> {
717
+ const send = this.transport ?? fetch
718
+ // A GET carries no body; `FetchLike` names one for the POSTs.
719
+ const init = { method: 'GET', headers: { accept: 'application/nostr+json' } } as unknown as Parameters<FetchLike>[1]
720
+ const res = await send(this.url, init)
721
+ if (res.status < 200 || res.status >= 300) throw new Error(`relay information failed: ${res.status}`)
722
+ return JSON.parse(await res.text())
634
723
  }
635
724
 
636
725
  /**
package/src/events.ts CHANGED
@@ -468,20 +468,23 @@ export function buildEditChannelMetadata(
468
468
  }
469
469
 
470
470
  /** A Folder command's `op`. `handle_folder_command` refuses anything else. */
471
- export type FolderOp = 'add' | 'remove' | 'set'
472
- const FOLDER_OPS: readonly string[] = ['add', 'remove', 'set']
471
+ export type FolderOp = 'add' | 'remove' | 'set' | 'move'
472
+ const FOLDER_OPS: readonly string[] = ['add', 'remove', 'set', 'move']
473
473
 
474
474
  /**
475
475
  * kind:1852 Folder command — the tag shape `handle_folder_command` reads
476
476
  * (`buzz-relay/src/handlers/side_effects.rs`, `nfb-demo-kinds`). Buzz has no
477
477
  * builder for it: the kind is the relay's own and only clients send it.
478
478
  *
479
- * Tag order: h, op, a…, [name]. `a` tags keep the order given, because the
480
- * relay appends them in that order and a Folder's order is the Folder's.
479
+ * Tag order: h, op, [from], a…, [name]. `a` tags keep the order given, because
480
+ * the relay appends them in that order and a Folder's order is the Folder's.
481
481
  *
482
482
  * - `add` and `remove` act on the addresses named and leave the rest alone;
483
483
  * `set` replaces the list wholesale. `add` with no addresses keeps the
484
484
  * contents and is how a name alone is changed — there is no `rename` op.
485
+ * - `move` takes the addresses off the Folder `from` names and puts them on
486
+ * the `h` one, both lists or neither (SPEC §3.3). It names exactly one
487
+ * `from`, never the `h`, and no other op names one.
485
488
  * - `name` is sticky: a command without one keeps the Folder's name.
486
489
  * - The name goes through `canonicalChannelName`, as the channel's does. The
487
490
  * state's name shadows the channel's wherever a Folder is listed, so the two
@@ -496,16 +499,20 @@ const FOLDER_OPS: readonly string[] = ['add', 'remove', 'set']
496
499
  export function buildFolderCommand(
497
500
  pubkey: string,
498
501
  createdAtMs: number,
499
- args: { folder: string; op: FolderOp; addresses?: string[]; name?: string },
502
+ args: { folder: string; op: FolderOp; from?: string; addresses?: string[]; name?: string },
500
503
  ): UnsignedEvent {
501
504
  assertHex64(pubkey, 'pubkey')
502
505
  if (!args.folder) throw new Error('a folder command names the folder')
503
506
  // The relay refuses an unknown op rather than defaulting it; so do we.
504
507
  if (!FOLDER_OPS.includes(args.op)) throw new Error(`unknown folder op: ${String(args.op)}`)
508
+ if ((args.op === 'move') !== (args.from !== undefined)) throw new Error('a move, and only a move, names the folder it leaves')
509
+ if (args.from !== undefined && (!args.from || args.from.toLowerCase() === args.folder.toLowerCase())) throw new Error('a move leaves another folder than the one it goes to')
510
+ if (args.op === 'move' && !args.addresses?.length) throw new Error('a move names the files it moves')
505
511
  const tags: NostrTag[] = [
506
512
  ['h', args.folder],
507
513
  ['op', args.op],
508
514
  ]
515
+ if (args.from !== undefined) tags.push(['from', args.from])
509
516
  for (const address of args.addresses ?? []) {
510
517
  if (!address) throw new Error('a folder command address must not be empty')
511
518
  tags.push(['a', address])
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.47.0'
50
+ export const PROTOCOL_VERSION = '0.49.0'
51
51
 
52
52
  export {
53
53
  // types
@@ -144,6 +144,9 @@ export {
144
144
  export {
145
145
  type PublishResult,
146
146
  type QueryResult,
147
+ type SearchMatch,
148
+ type RelayFileReads,
149
+ relayFileReadsOf,
147
150
  type RelayHeaders,
148
151
  type RelayOptions,
149
152
  type FetchLike,
@@ -221,6 +224,15 @@ export {
221
224
  documentText,
222
225
  } from './blocks.js'
223
226
 
227
+ export {
228
+ type MergeText,
229
+ type MergeAsk,
230
+ type TextMerge,
231
+ type BlockMerge,
232
+ mergeBlockDocuments,
233
+ mergeTexts,
234
+ } from './merge.js'
235
+
224
236
  export {
225
237
  type RenderInline,
226
238
  type RenderBlock,