chirli 0.1.0 → 0.2.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 (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
@@ -1,11 +1,22 @@
1
- import { matchFilter, verifyEvent } from 'nostr-tools';
2
- import { decode } from 'nostr-tools/nip19';
3
- import { hexKey, validTimestamp } from './protocol.js';
4
- export const inputOf = (event) => ({ id: event.id, sender: event.pubkey, createdAt: event.created_at, text: event.content, event: structuredClone(event) });
1
+ import { matchFilter, verifyEvent, } from "nostr-tools";
2
+ import { decode } from "nostr-tools/nip19";
3
+ import { hexKey, validTimestamp } from "./protocol.js";
4
+ export const inputOf = (event) => ({
5
+ id: event.id,
6
+ sender: event.pubkey,
7
+ createdAt: event.created_at,
8
+ kind: event.kind,
9
+ text: event.kind === 15 ? "" : event.content,
10
+ event: structuredClone(event),
11
+ });
5
12
  export function publicEvent(input) {
6
13
  try {
7
14
  const event = structuredClone(input);
8
- return ![13, 14, 1059].includes(event.kind) && validTimestamp(event.created_at) && verifyEvent(event) ? event : undefined;
15
+ return ![13, 14, 15, 1059].includes(event.kind) &&
16
+ validTimestamp(event.created_at) &&
17
+ verifyEvent(event)
18
+ ? event
19
+ : undefined;
9
20
  }
10
21
  catch {
11
22
  return;
@@ -14,91 +25,140 @@ export function publicEvent(input) {
14
25
  const coordinate = (value) => {
15
26
  const match = /^(\d+):([0-9a-f]{64}):([\s\S]*)$/.exec(value);
16
27
  if (!match || Number(match[1]) > 65535 || value.length > 4096)
17
- throw new Error('Malformed thread address');
28
+ throw new Error("Malformed thread address");
18
29
  const kind = Number(match[1]);
19
- if (!((kind === 0 || kind === 3) || (kind >= 10000 && kind < 20000) || (kind >= 30000 && kind < 40000)))
20
- throw new Error('Thread address is not replaceable');
30
+ if (!(kind === 0 ||
31
+ kind === 3 ||
32
+ (kind >= 10000 && kind < 20000) ||
33
+ (kind >= 30000 && kind < 40000)))
34
+ throw new Error("Thread address is not replaceable");
21
35
  return { kind, pubkey: match[2], identifier: match[3] };
22
36
  };
23
37
  export function eventCoordinate(event) {
24
38
  if (event.kind >= 30000 && event.kind < 40000)
25
- return `${event.kind}:${event.pubkey}:${event.tags.find(t => t[0] === 'd')?.[1] ?? ''}`;
26
- if (event.kind === 0 || event.kind === 3 || (event.kind >= 10000 && event.kind < 20000))
39
+ return `${event.kind}:${event.pubkey}:${event.tags.find((t) => t[0] === "d")?.[1] ?? ""}`;
40
+ if (event.kind === 0 ||
41
+ event.kind === 3 ||
42
+ (event.kind >= 10000 && event.kind < 20000))
27
43
  return `${event.kind}:${event.pubkey}:`;
28
44
  }
29
- export const referenceKey = (ref) => ref.address ? `a:${ref.address}` : ref.id ? `e:${ref.id}` : `i:${ref.external}`;
30
- const selfReference = (event) => ({ id: event.id, ...(eventCoordinate(event) ? { address: eventCoordinate(event) } : {}), kind: String(event.kind), author: event.pubkey });
45
+ export const referenceKey = (ref) => ref.address
46
+ ? `a:${ref.address}`
47
+ : ref.id
48
+ ? `e:${ref.id}`
49
+ : `i:${ref.external}`;
50
+ const selfReference = (event) => ({
51
+ id: event.id,
52
+ ...(eventCoordinate(event) ? { address: eventCoordinate(event) } : {}),
53
+ kind: String(event.kind),
54
+ author: event.pubkey,
55
+ });
31
56
  function singleton(event, name) {
32
- const tags = event.tags.filter(t => t[0] === name);
57
+ const tags = event.tags.filter((t) => t[0] === name);
33
58
  if (tags.length > 1)
34
59
  throw new Error(`Ambiguous thread ${name}`);
35
60
  return tags[0];
36
61
  }
37
62
  function modernReference(event, upper) {
38
- const id = singleton(event, upper ? 'E' : 'e'), address = singleton(event, upper ? 'A' : 'a'), external = singleton(event, upper ? 'I' : 'i'), kind = singleton(event, upper ? 'K' : 'k')?.[1];
63
+ const id = singleton(event, upper ? "E" : "e"), address = singleton(event, upper ? "A" : "a"), external = singleton(event, upper ? "I" : "i"), kind = singleton(event, upper ? "K" : "k")?.[1];
39
64
  if (!kind || (!id && !address && !external) || (external && (id || address)))
40
- throw new Error('Missing or conflicting thread reference');
65
+ throw new Error("Missing or conflicting thread reference");
41
66
  if (id && !hexKey(id[1]))
42
- throw new Error('Malformed thread event ID');
67
+ throw new Error("Malformed thread event ID");
43
68
  const point = address ? coordinate(address[1]) : undefined;
44
69
  if (point && String(point.kind) !== kind)
45
- throw new Error('Thread address kind mismatch');
70
+ throw new Error("Thread address kind mismatch");
46
71
  if (!external && !/^\d+$/.test(kind))
47
- throw new Error('Invalid thread kind');
48
- if (!external && (!Number.isSafeInteger(Number(kind)) || Number(kind) > 65535))
49
- throw new Error('Invalid thread kind');
50
- const authors = event.tags.filter(t => t[0] === (upper ? 'P' : 'p')).map(t => t[1]).filter(hexKey);
72
+ throw new Error("Invalid thread kind");
73
+ if (!external &&
74
+ (!Number.isSafeInteger(Number(kind)) || Number(kind) > 65535))
75
+ throw new Error("Invalid thread kind");
76
+ const authors = event.tags
77
+ .filter((t) => t[0] === (upper ? "P" : "p"))
78
+ .map((t) => t[1])
79
+ .filter(hexKey);
51
80
  if (upper && authors.length !== 1 && !external)
52
- throw new Error('Missing root author');
81
+ throw new Error("Missing root author");
53
82
  const hintAuthor = id?.[3];
54
83
  if (hintAuthor && !hexKey(hintAuthor))
55
- throw new Error('Invalid thread author');
56
- const author = point?.pubkey ?? hintAuthor ?? (authors.length === 1 ? authors[0] : undefined);
84
+ throw new Error("Invalid thread author");
85
+ const author = point?.pubkey ??
86
+ hintAuthor ??
87
+ (authors.length === 1 ? authors[0] : undefined);
57
88
  if (upper && !external && (!author || authors[0] !== author))
58
- throw new Error('Conflicting root author');
89
+ throw new Error("Conflicting root author");
59
90
  if (point && hintAuthor && point.pubkey !== hintAuthor)
60
- throw new Error('Conflicting address author');
91
+ throw new Error("Conflicting address author");
61
92
  if (external && (!external[1] || external[1].length > 4096))
62
- throw new Error('Invalid external scope');
63
- return { ...(id ? { id: id[1] } : {}), ...(address ? { address: address[1] } : {}), ...(external ? { external: external[1] } : {}), kind, author, hint: (address ?? id ?? external)?.[2] };
93
+ throw new Error("Invalid external scope");
94
+ return {
95
+ ...(id ? { id: id[1] } : {}),
96
+ ...(address ? { address: address[1] } : {}),
97
+ ...(external ? { external: external[1] } : {}),
98
+ kind,
99
+ author,
100
+ hint: (address ?? id ?? external)?.[2],
101
+ };
64
102
  }
65
103
  export function threadStructure(event) {
66
104
  if (event.kind === 1111)
67
- return { root: modernReference(event, true), parent: modernReference(event, false), explicitRoot: true };
105
+ return {
106
+ root: modernReference(event, true),
107
+ parent: modernReference(event, false),
108
+ explicitRoot: true,
109
+ };
68
110
  if (event.kind !== 1)
69
111
  return { root: selfReference(event), explicitRoot: true };
70
112
  const quotes = new Set();
71
113
  for (const match of event.content.matchAll(/(?:nostr:)?((?:note1|nevent1|naddr1)[0-9a-z]+)/g))
72
114
  try {
73
115
  const value = decode(match[1]);
74
- if (value.type === 'note')
116
+ if (value.type === "note")
75
117
  quotes.add(value.data);
76
- if (value.type === 'nevent')
118
+ if (value.type === "nevent")
77
119
  quotes.add(value.data.id);
78
- if (value.type === 'naddr')
120
+ if (value.type === "naddr")
79
121
  quotes.add(`${value.data.kind}:${value.data.pubkey}:${value.data.identifier}`);
80
122
  }
81
123
  catch { }
82
- const tags = event.tags.filter(t => (t[0] === 'e' || t[0] === 'a') && t[3] !== 'mention' && (t[3] === 'root' || t[3] === 'reply' || (!t[3] && t[0] === 'e' && !quotes.has(t[1]))));
83
- const roots = tags.filter(t => t[3] === 'root'), parents = tags.filter(t => t[3] === 'reply'), positional = tags.filter(t => !t[3]);
124
+ const tags = event.tags.filter((t) => (t[0] === "e" || t[0] === "a") &&
125
+ t[3] !== "mention" &&
126
+ (t[3] === "root" ||
127
+ t[3] === "reply" ||
128
+ (!t[3] && t[0] === "e" && !quotes.has(t[1]))));
129
+ const roots = tags.filter((t) => t[3] === "root"), parents = tags.filter((t) => t[3] === "reply"), positional = tags.filter((t) => !t[3]);
84
130
  if (roots.length > 1 || parents.length > 1)
85
- throw new Error('Ambiguous legacy thread markers');
131
+ throw new Error("Ambiguous legacy thread markers");
86
132
  const root = roots[0] ?? positional[0], parent = parents[0] ?? positional.at(-1) ?? root;
87
133
  const ref = (tag) => {
88
- if (tag[0] === 'a') {
134
+ if (tag[0] === "a") {
89
135
  const value = coordinate(tag[1]);
90
- return { address: tag[1], kind: String(value.kind), author: value.pubkey, hint: tag[2] };
136
+ return {
137
+ address: tag[1],
138
+ kind: String(value.kind),
139
+ author: value.pubkey,
140
+ hint: tag[2],
141
+ };
91
142
  }
92
143
  if (!hexKey(tag[1]) || (tag[4] && !hexKey(tag[4])))
93
- throw new Error('Malformed legacy thread reference');
144
+ throw new Error("Malformed legacy thread reference");
94
145
  return { id: tag[1], author: tag[4] || undefined, hint: tag[2] };
95
146
  };
96
- return { root: root ? ref(root) : undefined, parent: parent ? ref(parent) : undefined, explicitRoot: roots.length > 0 };
147
+ return {
148
+ root: root ? ref(root) : undefined,
149
+ parent: parent ? ref(parent) : undefined,
150
+ explicitRoot: roots.length > 0,
151
+ };
152
+ }
153
+ function matches(ref, event) {
154
+ return ((!ref.id || ref.id === event.id) &&
155
+ (!ref.address || ref.address === eventCoordinate(event)) &&
156
+ (!ref.kind || ref.kind === String(event.kind)) &&
157
+ (!ref.author || ref.author === event.pubkey));
97
158
  }
98
- function matches(ref, event) { return (!ref.id || ref.id === event.id) && (!ref.address || ref.address === eventCoordinate(event)) && (!ref.kind || ref.kind === String(event.kind)) && (!ref.author || ref.author === event.pubkey); }
99
159
  export function threadLimit(limit = 30) {
100
160
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
101
- throw new TypeError('thread limit must be in 1..100');
161
+ throw new TypeError("thread limit must be in 1..100");
102
162
  return limit;
103
163
  }
104
164
  /** Bounded root-batched graph, followed only along the trigger's ancestor path. */
@@ -116,7 +176,12 @@ export class PublicThreads {
116
176
  this.maxEvents = options.maxEvents ?? 500;
117
177
  this.maxLookups = options.maxLookups ?? 16;
118
178
  this.maxDepth = options.maxDepth ?? 64;
119
- for (const [name, value, min, max] of [['timeoutMs', this.timeout, 1, 30000], ['maxEvents', this.maxEvents, 1, 2000], ['maxLookups', this.maxLookups, 1, 64], ['maxDepth', this.maxDepth, 1, 256]])
179
+ for (const [name, value, min, max] of [
180
+ ["timeoutMs", this.timeout, 1, 30000],
181
+ ["maxEvents", this.maxEvents, 1, 2000],
182
+ ["maxLookups", this.maxLookups, 1, 64],
183
+ ["maxDepth", this.maxDepth, 1, 256],
184
+ ])
120
185
  if (!Number.isSafeInteger(value) || value < min || value > max)
121
186
  throw new TypeError(`Invalid public thread ${name}`);
122
187
  }
@@ -124,30 +189,50 @@ export class PublicThreads {
124
189
  const deadline = performance.now() + this.timeout;
125
190
  let lookups = 0;
126
191
  let bounded = false;
127
- return { get bounded() { return bounded; }, query: async (filter) => {
192
+ return {
193
+ get bounded() {
194
+ return bounded;
195
+ },
196
+ query: async (filter) => {
128
197
  if (++lookups > this.maxLookups)
129
- throw new Error('lookup-limit');
198
+ throw new Error("lookup-limit");
130
199
  const left = deadline - performance.now();
131
200
  if (left <= 0)
132
- throw new Error('timeout');
201
+ throw new Error("timeout");
133
202
  let timer;
134
203
  try {
135
- const events = await Promise.race([this.transport.query(this.relays, { ...filter, limit: this.maxEvents }), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timeout')), left); })]);
204
+ const events = await Promise.race([
205
+ this.transport.query(this.relays, {
206
+ ...filter,
207
+ limit: this.maxEvents,
208
+ }),
209
+ new Promise((_, reject) => {
210
+ timer = setTimeout(() => reject(new Error("timeout")), left);
211
+ }),
212
+ ]);
136
213
  if (events.length >= this.maxEvents)
137
214
  bounded = true;
138
- return events.flatMap(frame => { const event = publicEvent(frame); return event && matchFilter(filter, event) ? [event] : []; });
215
+ return events.flatMap((frame) => {
216
+ const event = publicEvent(frame);
217
+ return event && matchFilter(filter, event) ? [event] : [];
218
+ });
139
219
  }
140
220
  finally {
141
221
  clearTimeout(timer);
142
222
  }
143
- } };
223
+ },
224
+ };
144
225
  }
145
226
  filter(ref) {
146
227
  if (ref.id)
147
228
  return { ids: [ref.id] };
148
229
  if (ref.address) {
149
230
  const c = coordinate(ref.address);
150
- return { authors: [c.pubkey], kinds: [c.kind], ...(c.kind >= 30000 ? { '#d': [c.identifier] } : {}) };
231
+ return {
232
+ authors: [c.pubkey],
233
+ kinds: [c.kind],
234
+ ...(c.kind >= 30000 ? { "#d": [c.identifier] } : {}),
235
+ };
151
236
  }
152
237
  if (ref.id)
153
238
  return { ids: [ref.id] };
@@ -157,31 +242,41 @@ export class PublicThreads {
157
242
  let current = trigger;
158
243
  for (let depth = 0; depth < this.maxDepth; depth++) {
159
244
  if (visited.has(current.id))
160
- throw new Error('Cyclic public thread');
245
+ throw new Error("Cyclic public thread");
161
246
  visited.add(current.id);
162
247
  const structure = threadStructure(current);
163
- if (current.kind === 1111)
248
+ if (current.kind === 1111) {
249
+ if (!structure.root)
250
+ throw new Error("Missing public thread root");
164
251
  return structure.root;
252
+ }
165
253
  if (!structure.parent)
166
254
  return selfReference(current);
167
255
  const ref = structure.explicitRoot ? structure.root : structure.parent;
256
+ if (!ref)
257
+ throw new Error("Missing public thread root");
168
258
  const filter = this.filter(ref);
169
259
  if (!filter)
170
- throw new Error('Unresolved public root');
171
- const events = (await budget.query(filter)).filter(event => matches(ref, event)).sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id));
260
+ throw new Error("Unresolved public root");
261
+ const events = (await budget.query(filter))
262
+ .filter((event) => matches(ref, event))
263
+ .sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id));
172
264
  if (!events[0])
173
- throw new Error('Missing public thread root');
265
+ throw new Error("Missing public thread root");
174
266
  current = events[0];
175
267
  if (structure.explicitRoot) {
176
268
  const parsed = threadStructure(current);
177
269
  if (parsed.parent && current.kind === 1)
178
- throw new Error('Conflicting legacy root');
179
- if (current.kind === 1111)
270
+ throw new Error("Conflicting legacy root");
271
+ if (current.kind === 1111) {
272
+ if (!parsed.root)
273
+ throw new Error("Missing public thread root");
180
274
  return parsed.root;
275
+ }
181
276
  return selfReference(current);
182
277
  }
183
278
  }
184
- throw new Error('Public thread depth limit');
279
+ throw new Error("Public thread depth limit");
185
280
  }
186
281
  async resolve(trigger, options = {}) {
187
282
  const limit = threadLimit(options.limit), budget = this.budget(), events = new Map([[trigger.id, trigger]]), batched = new Set(), seen = new Set();
@@ -192,13 +287,15 @@ export class PublicThreads {
192
287
  for (const event of items) {
193
288
  if (events.size >= this.maxEvents && !events.has(event.id)) {
194
289
  complete = false;
195
- reason = 'size-limit';
290
+ reason = "size-limit";
196
291
  break;
197
292
  }
198
293
  events.set(event.id, event);
199
294
  }
200
295
  };
201
- const find = (ref) => [...events.values()].filter(event => matches(ref, event)).sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
296
+ const find = (ref) => [...events.values()]
297
+ .filter((event) => matches(ref, event))
298
+ .sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
202
299
  const batch = async (ref) => {
203
300
  const key = referenceKey(ref);
204
301
  if (batched.has(key))
@@ -209,12 +306,12 @@ export class PublicThreads {
209
306
  if (target)
210
307
  filters.push(target);
211
308
  if (ref.id)
212
- filters.push({ kinds: [1], '#e': [ref.id] }, { kinds: [1111], '#E': [ref.id] });
309
+ filters.push({ kinds: [1], "#e": [ref.id] }, { kinds: [1111], "#E": [ref.id] });
213
310
  if (ref.address)
214
- filters.push({ kinds: [1], '#a': [ref.address] }, { kinds: [1111], '#A': [ref.address] });
311
+ filters.push({ kinds: [1], "#a": [ref.address] }, { kinds: [1111], "#A": [ref.address] });
215
312
  if (ref.external)
216
- filters.push({ kinds: [1111], '#I': [ref.external] });
217
- add((await Promise.all(filters.map(filter => budget.query(filter)))).flat());
313
+ filters.push({ kinds: [1111], "#I": [ref.external] });
314
+ add((await Promise.all(filters.map((filter) => budget.query(filter)))).flat());
218
315
  const root = find(ref), address = root && eventCoordinate(root);
219
316
  if (address && !ref.address)
220
317
  await batch({ ...ref, address });
@@ -226,7 +323,7 @@ export class PublicThreads {
226
323
  for (let depth = 0; depth < this.maxDepth; depth++) {
227
324
  if (seen.has(current.id)) {
228
325
  complete = false;
229
- reason = 'cycle';
326
+ reason = "cycle";
230
327
  break;
231
328
  }
232
329
  seen.add(current.id);
@@ -237,9 +334,10 @@ export class PublicThreads {
237
334
  if (!parent)
238
335
  break;
239
336
  if (parent.external) {
240
- if (!parts.root || referenceKey(parent) !== referenceKey(parts.root)) {
337
+ if (!parts.root ||
338
+ referenceKey(parent) !== referenceKey(parts.root)) {
241
339
  complete = false;
242
- reason = 'external-parent';
340
+ reason = "external-parent";
243
341
  }
244
342
  break;
245
343
  }
@@ -252,24 +350,26 @@ export class PublicThreads {
252
350
  }
253
351
  if (!next) {
254
352
  complete = false;
255
- reason = 'missing-parent';
353
+ reason = "missing-parent";
256
354
  break;
257
355
  }
258
356
  if (next.id === trigger.id || seen.has(next.id)) {
259
357
  complete = false;
260
- reason = 'cycle';
358
+ reason = "cycle";
261
359
  break;
262
360
  }
263
361
  if (declared) {
264
362
  const nextParts = threadStructure(next);
265
- if (next.kind === 1111 && nextParts.root && referenceKey(nextParts.root) !== referenceKey(declared)) {
363
+ if (next.kind === 1111 &&
364
+ nextParts.root &&
365
+ referenceKey(nextParts.root) !== referenceKey(declared)) {
266
366
  complete = false;
267
- reason = 'root-mismatch';
367
+ reason = "root-mismatch";
268
368
  break;
269
369
  }
270
370
  if (!nextParts.parent && !matches(declared, next)) {
271
371
  complete = false;
272
- reason = 'root-mismatch';
372
+ reason = "root-mismatch";
273
373
  break;
274
374
  }
275
375
  }
@@ -277,43 +377,60 @@ export class PublicThreads {
277
377
  current = next;
278
378
  if (depth === this.maxDepth - 1) {
279
379
  complete = false;
280
- reason = 'depth-limit';
380
+ reason = "depth-limit";
281
381
  }
282
382
  }
283
383
  }
284
384
  catch (error) {
285
385
  complete = false;
286
- reason = error instanceof Error && ['timeout', 'lookup-limit'].includes(error.message) ? error.message : 'query-failed';
386
+ reason =
387
+ error instanceof Error &&
388
+ ["timeout", "lookup-limit"].includes(error.message)
389
+ ? error.message
390
+ : "query-failed";
287
391
  }
288
392
  if (budget.bounded) {
289
393
  complete = false;
290
- reason ??= 'query-window';
394
+ reason ??= "query-window";
291
395
  }
292
396
  if (ancestors.length > limit) {
293
397
  complete = false;
294
- reason ??= 'entry-limit';
398
+ reason ??= "entry-limit";
295
399
  }
296
400
  // Topological oldest-to-parent order, never timestamp-sort sibling events into the context.
297
- return { entries: ancestors.slice(0, limit).reverse().map(inputOf), complete, coverage: 'public-ancestors', ...(reason ? { reason } : {}) };
401
+ return {
402
+ entries: ancestors.slice(0, limit).reverse().map(inputOf),
403
+ complete,
404
+ coverage: "public-ancestors",
405
+ ...(reason ? { reason } : {}),
406
+ };
298
407
  }
299
408
  }
300
- export function commentReply(trigger, root, text, hint = '') {
409
+ export function commentReply(trigger, root, text, hint = "") {
301
410
  if (!text)
302
- throw new TypeError('Nonempty reply text required');
411
+ throw new TypeError("Nonempty reply text required");
303
412
  if (!root.kind || (!root.external && !root.author))
304
- throw new Error('Incomplete public root');
413
+ throw new Error("Incomplete public root");
305
414
  const tags = [];
306
415
  if (root.address)
307
- tags.push(['A', root.address]);
308
- else if (root.id)
309
- tags.push(['E', root.id, '', root.author]);
416
+ tags.push(["A", root.address]);
417
+ else if (root.id) {
418
+ if (!root.author)
419
+ throw new Error("Incomplete public root");
420
+ tags.push(["E", root.id, "", root.author]);
421
+ }
310
422
  else if (root.external)
311
- tags.push(['I', root.external]);
423
+ tags.push(["I", root.external]);
312
424
  else
313
- throw new Error('Missing public root');
314
- tags.push(['K', root.kind]);
425
+ throw new Error("Missing public root");
426
+ tags.push(["K", root.kind]);
315
427
  if (root.author)
316
- tags.push(['P', root.author]);
317
- tags.push(['e', trigger.id, hint, trigger.pubkey], ['k', String(trigger.kind)], ['p', trigger.pubkey]);
318
- return { kind: 1111, created_at: Math.floor(Date.now() / 1000), tags, content: text };
428
+ tags.push(["P", root.author]);
429
+ tags.push(["e", trigger.id, hint, trigger.pubkey], ["k", String(trigger.kind)], ["p", trigger.pubkey]);
430
+ return {
431
+ kind: 1111,
432
+ created_at: Math.floor(Date.now() / 1000),
433
+ tags,
434
+ content: text,
435
+ };
319
436
  }
@@ -1,7 +1,7 @@
1
- import WebSocket from 'ws';
2
- import { AbstractRelay, type Subscription as NostrSubscription } from 'nostr-tools/abstract-relay';
3
- import { type Event, type EventTemplate, type Filter } from 'nostr-tools';
4
- import { RelayError } from './errors.js';
1
+ import WebSocket from "ws";
2
+ import { AbstractRelay, type Subscription as NostrSubscription } from "nostr-tools/abstract-relay";
3
+ import { type Event, type EventTemplate, type Filter } from "nostr-tools";
4
+ import { RelayError } from "./errors.js";
5
5
  export interface RelayTimeouts {
6
6
  connectionTimeoutMs: number;
7
7
  eoseTimeoutMs: number;
@@ -22,7 +22,7 @@ interface Consumer {
22
22
  export interface RelayLease {
23
23
  readonly authenticating: boolean;
24
24
  ready: Promise<void>;
25
- subscribe(filter: Filter, params: Parameters<AbstractRelay['subscribe']>[1]): NostrSubscription;
25
+ subscribe(filter: Filter, params: Parameters<AbstractRelay["subscribe"]>[1]): NostrSubscription;
26
26
  publish(event: Event, afterAuth?: boolean): Promise<string>;
27
27
  release(): void;
28
28
  }