chirli 0.0.0-stage → 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 (97) hide show
  1. package/ARCHITECTURE.md +103 -0
  2. package/CONTRIBUTING.md +56 -0
  3. package/LICENSE +22 -0
  4. package/README.md +281 -2
  5. package/SECURITY.md +55 -0
  6. package/THIRD_PARTY_NOTICES.md +51 -0
  7. package/dist/allowlist.d.ts +3 -0
  8. package/dist/allowlist.js +9 -0
  9. package/dist/announcements.d.ts +25 -0
  10. package/dist/announcements.js +142 -0
  11. package/dist/attachments.d.ts +43 -0
  12. package/dist/attachments.js +340 -0
  13. package/dist/blossom.d.ts +30 -0
  14. package/dist/blossom.js +233 -0
  15. package/dist/bot-handlers.d.ts +70 -0
  16. package/dist/bot-handlers.js +317 -0
  17. package/dist/bot.d.ts +63 -0
  18. package/dist/bot.js +244 -0
  19. package/dist/client.d.ts +221 -0
  20. package/dist/client.js +1197 -0
  21. package/dist/command-discovery.d.ts +4 -0
  22. package/dist/command-discovery.js +33 -0
  23. package/dist/command-schema.d.ts +4 -0
  24. package/dist/command-schema.js +101 -0
  25. package/dist/commands.d.ts +32 -0
  26. package/dist/commands.js +253 -0
  27. package/dist/defaults.d.ts +9 -0
  28. package/dist/defaults.js +22 -0
  29. package/dist/errors.d.ts +55 -0
  30. package/dist/errors.js +126 -0
  31. package/dist/inbox.d.ts +55 -0
  32. package/dist/inbox.js +376 -0
  33. package/dist/index.d.ts +25 -0
  34. package/dist/index.js +11 -0
  35. package/dist/key-sync.d.ts +33 -0
  36. package/dist/key-sync.js +293 -0
  37. package/dist/keys.d.ts +66 -0
  38. package/dist/keys.js +418 -0
  39. package/dist/message-storage-sqlite.d.ts +6 -0
  40. package/dist/message-storage-sqlite.js +90 -0
  41. package/dist/message-storage.d.ts +32 -0
  42. package/dist/message-storage.js +1 -0
  43. package/dist/messaging-metadata.d.ts +48 -0
  44. package/dist/messaging-metadata.js +280 -0
  45. package/dist/metadata.d.ts +7 -0
  46. package/dist/metadata.js +63 -0
  47. package/dist/modes.d.ts +26 -0
  48. package/dist/modes.js +108 -0
  49. package/dist/nip4e-compat.d.ts +4 -0
  50. package/dist/nip4e-compat.js +14 -0
  51. package/dist/nipcd.d.ts +109 -0
  52. package/dist/nipcd.js +555 -0
  53. package/dist/protocol.d.ts +68 -0
  54. package/dist/protocol.js +302 -0
  55. package/dist/public-inbox.d.ts +66 -0
  56. package/dist/public-inbox.js +295 -0
  57. package/dist/public-thread.d.ts +62 -0
  58. package/dist/public-thread.js +436 -0
  59. package/dist/relay-pool.d.ts +43 -0
  60. package/dist/relay-pool.js +429 -0
  61. package/dist/relay-roles.d.ts +18 -0
  62. package/dist/relay-roles.js +55 -0
  63. package/dist/relay.d.ts +52 -0
  64. package/dist/relay.js +493 -0
  65. package/dist/request-timing.d.ts +12 -0
  66. package/dist/request-timing.js +37 -0
  67. package/dist/session.d.ts +16 -0
  68. package/dist/session.js +51 -0
  69. package/dist/signer.d.ts +13 -0
  70. package/dist/signer.js +1 -0
  71. package/dist/signers/bunker-relays.d.ts +15 -0
  72. package/dist/signers/bunker-relays.js +87 -0
  73. package/dist/signers/bunker.d.ts +7 -0
  74. package/dist/signers/bunker.js +194 -0
  75. package/dist/signers/nsec.d.ts +3 -0
  76. package/dist/signers/nsec.js +62 -0
  77. package/dist/signers.d.ts +18 -0
  78. package/dist/signers.js +59 -0
  79. package/dist/storage-sqlite.d.ts +29 -0
  80. package/dist/storage-sqlite.js +221 -0
  81. package/dist/storage.d.ts +85 -0
  82. package/dist/storage.js +1 -0
  83. package/dist/store.d.ts +96 -0
  84. package/dist/store.js +404 -0
  85. package/docs/ACCESS.md +28 -0
  86. package/docs/API.md +382 -0
  87. package/docs/INTEROPERABILITY.md +32 -0
  88. package/docs/KEYS.md +75 -0
  89. package/docs/NIP-CD.md +112 -0
  90. package/docs/PUBLIC.md +88 -0
  91. package/docs/RECOVERY.md +59 -0
  92. package/docs/RELAYS.md +145 -0
  93. package/docs/SESSIONS.md +108 -0
  94. package/docs/SIGNERS.md +59 -0
  95. package/docs/STORAGE.md +71 -0
  96. package/docs/TUTORIAL.md +178 -0
  97. package/package.json +47 -4
package/dist/client.js ADDED
@@ -0,0 +1,1197 @@
1
+ import { resolve } from "node:path";
2
+ import { AttachmentCache, parseAttachment } from "./attachments.js";
3
+ import { encryptAttachment, normalizeBlossomDownloadOrigins, normalizeBlossomServers, snapshotFile, uploadFile, } from "./blossom.js";
4
+ import { PublicInbox, } from "./public-inbox.js";
5
+ import { inputOf, threadLimit, } from "./public-thread.js";
6
+ import { getEventHash } from "nostr-tools";
7
+ import { identityFromSigner } from "./signers.js";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { Store } from "./store.js";
10
+ import { WebSocketTransport, } from "./relay.js";
11
+ import { fileRumor, hexKey, reactionRumor, replyTarget, rumor, timestamp, createdAtOrAfter, unwrapAsync, wrap, } from "./protocol.js";
12
+ import { createMessagingProtocol, protocolScope, } from "./modes.js";
13
+ import { InboxSubscription, } from "./inbox.js";
14
+ import { validateCommandDefinition, } from "./nipcd.js";
15
+ import { relayRoles, relayUnion, readWriteTags, } from "./relay-roles.js";
16
+ import { KeySync } from "./key-sync.js";
17
+ import { MessagingMetadata, } from "./messaging-metadata.js";
18
+ import { Announcements } from "./announcements.js";
19
+ import { discoverCommandCatalog } from "./command-discovery.js";
20
+ import { CommandCatalog } from "./commands.js";
21
+ import { EncryptionKeys, } from "./keys.js";
22
+ export function rejectRemovedIntakeOptions(options) {
23
+ if ("inboundPolicy" in options ||
24
+ "guards" in options ||
25
+ "allowlist" in options) {
26
+ throw new TypeError("Use bot.use(allowlist(pubkeys)) or custom middleware instead of inboundPolicy, guards or the allowlist option");
27
+ }
28
+ }
29
+ export class Client {
30
+ options;
31
+ metadataLookupRelays;
32
+ attachments;
33
+ blossomServers;
34
+ blossomDownloadOrigins;
35
+ announcements;
36
+ metadata;
37
+ keySync;
38
+ commandDefinitions = new Map();
39
+ commands;
40
+ publicInbox;
41
+ publicHandlers = new Set();
42
+ commandRevision = 0;
43
+ syncedCommandRevision = -1;
44
+ managesCommandCatalog = false;
45
+ commandSyncScheduled = false;
46
+ revokedCommands = new Set();
47
+ synchronizing;
48
+ announcing;
49
+ coreStore;
50
+ account;
51
+ mode;
52
+ nip4eCompatibility;
53
+ keys;
54
+ rotationTimer;
55
+ protocol;
56
+ transport;
57
+ ownsTransport;
58
+ observers = new Set();
59
+ handlers = new Map();
60
+ errors = new Set();
61
+ queues = new Map();
62
+ intake = Promise.resolve();
63
+ sub;
64
+ running = false;
65
+ dmActivatedAt;
66
+ closed = false;
67
+ starting;
68
+ stopping;
69
+ closing;
70
+ generation = 0;
71
+ handlerContext = new AsyncLocalStorage();
72
+ flushing;
73
+ get pubkey() {
74
+ return this.account.pubkey;
75
+ }
76
+ /** Resolve the account asynchronously, regardless of local or remote signing. */
77
+ static async create(options) {
78
+ rejectRemovedIntakeOptions(options);
79
+ const { signer, ...configuration } = options;
80
+ if ("identity" in options) {
81
+ throw new TypeError("Client.create accepts signer, not identity");
82
+ }
83
+ if ("storage" in options) {
84
+ throw new TypeError("Use messageStorage for custom message history");
85
+ }
86
+ const identity = await identityFromSigner(signer, {
87
+ mode: options.mode ?? "nip17",
88
+ });
89
+ return new Client({ ...configuration, identity });
90
+ }
91
+ constructor(input) {
92
+ rejectRemovedIntakeOptions(input);
93
+ const { identity, ...configuration } = input;
94
+ const roles = relayRoles(configuration);
95
+ this.blossomServers = normalizeBlossomServers(configuration.blossomServers);
96
+ this.blossomDownloadOrigins = normalizeBlossomDownloadOrigins(configuration.blossomDownloadOrigins);
97
+ const options = {
98
+ ...configuration,
99
+ ...roles,
100
+ relays: roles.dmRelays,
101
+ };
102
+ this.options = options;
103
+ this.metadataLookupRelays = relayUnion(roles.readRelays, roles.writeRelays, roles.dmRelays);
104
+ if (!hexKey(identity.pubkey) || !options.relays.length) {
105
+ throw new Error("Identity and at least one relay required");
106
+ }
107
+ this.account = {
108
+ ...identity,
109
+ oldEncryptionKeys: identity.oldEncryptionKeys?.map((key) => new Uint8Array(key)),
110
+ };
111
+ if (options.nip4eCompatibility !== undefined &&
112
+ typeof options.nip4eCompatibility !== "boolean") {
113
+ throw new TypeError("nip4eCompatibility must be boolean");
114
+ }
115
+ this.mode = options.mode ?? "nip17";
116
+ const scope = protocolScope(this.mode, this.account);
117
+ this.nip4eCompatibility =
118
+ this.mode === "nip4e" || options.nip4eCompatibility !== false;
119
+ if (options.transport && options.transportOptions) {
120
+ throw new TypeError("Choose transport or transportOptions, not both");
121
+ }
122
+ this.transport =
123
+ options.transport ??
124
+ new WebSocketTransport(options.transportOptions ?? {}, (template) => this.account.sign(template));
125
+ this.ownsTransport = !options.transport;
126
+ if ("storage" in options)
127
+ throw new TypeError("Internal storage accepts only a database path; use messageStorage for messages");
128
+ const database = options.database ?? "psstpsst.sqlite";
129
+ if (options.attachmentDirectory !== undefined &&
130
+ (typeof options.attachmentDirectory !== "string" ||
131
+ !options.attachmentDirectory.trim())) {
132
+ throw new TypeError("attachmentDirectory must be a nonempty path");
133
+ }
134
+ this.attachments = new AttachmentCache(resolve(options.attachmentDirectory ??
135
+ `${database === ":memory:" ? "psstpsst.sqlite" : database}.attachments`, this.account.pubkey), new Set([
136
+ ...this.blossomServers.map((server) => new URL(server).origin),
137
+ ...this.blossomDownloadOrigins,
138
+ ]));
139
+ this.coreStore = new Store(database, options.storageKey, scope, options.messageStorage);
140
+ try {
141
+ this.metadata = new MessagingMetadata(this.account.pubkey, this.coreStore, this.transport, this.metadataLookupRelays, (error) => this.report(error), options.reconnect, options.metadataCache);
142
+ this.keys = new EncryptionKeys(this.account, this.mode, this.coreStore, this.transport, this.metadataLookupRelays, options.keyRotation, [options.writeRelays, options.dmRelays], this.metadata);
143
+ if (options.keySync !== false) {
144
+ const keySync = new KeySync(this.account, this.coreStore, this.transport, relayUnion(options.writeRelays, options.dmRelays), (key) => this.keys.exportEncryptionKey(key), () => this.coreStore
145
+ .declaration(this.account.pubkey)
146
+ ?.tags.find((tag) => tag[0] === "n")?.[1], options.keySync);
147
+ this.keySync = keySync;
148
+ this.keys.setSynchronizer((key) => keySync.request(key));
149
+ this.keys.onImported = () => {
150
+ if (this.running && this.sub) {
151
+ void this.sub.sync().catch((error) => this.report(error));
152
+ }
153
+ };
154
+ this.metadata.onOwnEvent = async (event) => {
155
+ if (event.kind === 4454) {
156
+ await keySync.handle(event);
157
+ return;
158
+ }
159
+ if (this.running) {
160
+ await this.keys.prepare();
161
+ }
162
+ };
163
+ }
164
+ this.protocol = createMessagingProtocol(this.mode, this.account, this.keys, this.metadata, this.options.dmRelays);
165
+ this.commands = new CommandCatalog(this.account, this.coreStore, this.transport, this.options.writeRelays);
166
+ if (options.publicInbox)
167
+ this.publicInbox = new PublicInbox(this.account, this.coreStore, this.transport, options.publicInbox, options.writeRelays, options.reconnect, () => this.publicCommandDefinitions(), async (input) => {
168
+ const context = { active: true };
169
+ try {
170
+ await this.handlerContext.run(context, async () => {
171
+ for (const handler of this.publicHandlers)
172
+ await handler(input);
173
+ });
174
+ }
175
+ finally {
176
+ context.active = false;
177
+ }
178
+ }, (error) => this.report(error));
179
+ this.coreStore.recoverMessages();
180
+ this.announcements = new Announcements(this.account, this.coreStore, this.transport, (event) => this.metadata.rememberOwn(event));
181
+ }
182
+ catch (error) {
183
+ this.coreStore.close();
184
+ if (this.ownsTransport) {
185
+ this.transport.close();
186
+ }
187
+ throw error;
188
+ }
189
+ }
190
+ /** Internal Bot handlers manage history admission through the middleware chain. */
191
+ handle(handler, managesAdmission = false) {
192
+ this.assertOpen();
193
+ this.handlers.set(handler, managesAdmission);
194
+ return () => this.handlers.delete(handler);
195
+ }
196
+ /** Receipt observer only: failures cannot change inbox state or replay business work. */
197
+ on(_event, observer) {
198
+ this.assertOpen();
199
+ this.observers.add(observer);
200
+ return () => this.observers.delete(observer);
201
+ }
202
+ onError(handler) {
203
+ this.errors.add(handler);
204
+ return () => this.errors.delete(handler);
205
+ }
206
+ report(error, message) {
207
+ for (const fn of this.errors) {
208
+ try {
209
+ void Promise.resolve(fn(error, message)).catch(() => { });
210
+ }
211
+ catch { }
212
+ }
213
+ }
214
+ assertOpen() {
215
+ if (this.closed || this.closing) {
216
+ throw new Error("Client is closed or closing");
217
+ }
218
+ }
219
+ start(publishMetadata = false) {
220
+ try {
221
+ this.assertOpen();
222
+ }
223
+ catch (error) {
224
+ return Promise.reject(error);
225
+ }
226
+ if (this.stopping) {
227
+ return this.stopping.then(() => this.start(publishMetadata));
228
+ }
229
+ if (this.starting) {
230
+ return this.starting;
231
+ }
232
+ if (this.running) {
233
+ return Promise.resolve();
234
+ }
235
+ this.running = true;
236
+ const generation = ++this.generation;
237
+ const task = this.startUp(generation, publishMetadata).finally(() => {
238
+ if (this.starting === task) {
239
+ this.starting = undefined;
240
+ }
241
+ });
242
+ this.starting = task;
243
+ return task;
244
+ }
245
+ async startUp(generation, publishMetadata) {
246
+ const current = () => this.running && this.generation === generation && !this.closing;
247
+ try {
248
+ this.coreStore.recoverMessages();
249
+ this.keySync?.start();
250
+ await this.metadata.start();
251
+ if (!current()) {
252
+ return;
253
+ }
254
+ // Complete publication before starting business subscriptions.
255
+ if (publishMetadata)
256
+ await this.publishKeyMetadata();
257
+ else
258
+ await this.protocol.prepare();
259
+ if (!current())
260
+ return;
261
+ if (this.managesCommandCatalog)
262
+ await this.syncCommands();
263
+ if (!current())
264
+ return;
265
+ if (publishMetadata)
266
+ await this.publishMetadata();
267
+ if (!current())
268
+ return;
269
+ this.dmActivatedAt = this.coreStore.ensureDmActivation(this.pubkey, Date.now());
270
+ this.sub = new InboxSubscription({
271
+ transport: this.transport,
272
+ store: this.coreStore,
273
+ relays: this.options.relays,
274
+ filter: {
275
+ kinds: [1059],
276
+ "#p": [this.account.pubkey],
277
+ limit: this.options.historyLimit ?? 500,
278
+ },
279
+ reconnect: this.options.reconnect,
280
+ recovery: this.options.recovery,
281
+ recoveryBaseline: Math.floor(this.dmActivatedAt / 1000),
282
+ localReadWindow: true,
283
+ receive: (event, source, relay) => this.receive(event, source, {
284
+ relay,
285
+ }).then(() => { }),
286
+ error: (error) => this.report(error),
287
+ reconnected: () => this.flushOutbox(),
288
+ });
289
+ await this.sub.ready;
290
+ await this.intake;
291
+ if (current())
292
+ await this.publicInbox?.start(this.publicKinds());
293
+ if (current()) {
294
+ await this.flushOutbox();
295
+ if (!current()) {
296
+ return;
297
+ }
298
+ await this.keys.rotateIfDue();
299
+ this.scheduleRotation();
300
+ }
301
+ }
302
+ catch (error) {
303
+ // External stop waits for startup; startup failure must not wait on that same stop.
304
+ if (this.generation === generation) {
305
+ await this.drainStop(this.quiesce());
306
+ }
307
+ throw error;
308
+ }
309
+ }
310
+ /** Verify and persist a relay event using the same asynchronous signer capabilities. */
311
+ receive(event, source, metadata) {
312
+ if (!this.running || this.closing)
313
+ return Promise.resolve(false);
314
+ this.assertOpen();
315
+ const generation = this.generation;
316
+ const current = () => this.running && this.generation === generation && !this.closing;
317
+ if ([1, 1111].includes(event.kind)) {
318
+ return Promise.resolve().then(() => current()
319
+ ? (this.publicInbox?.receive(event, source, metadata?.relay) ?? false)
320
+ : false);
321
+ }
322
+ const snapshot = metadata
323
+ ? {
324
+ relay: metadata.relay,
325
+ }
326
+ : undefined;
327
+ // Preserve wire intake order; stop fences any decryption that was not yet admitted.
328
+ const task = this.intake.then(async () => {
329
+ if (!current())
330
+ return false;
331
+ try {
332
+ const decoded = await unwrapAsync(event, this.account, this.protocol.envelope, current);
333
+ return current() && decoded
334
+ ? this.accept(decoded, source, snapshot)
335
+ : false;
336
+ }
337
+ catch (error) {
338
+ if (!current())
339
+ return false;
340
+ throw error;
341
+ }
342
+ });
343
+ this.intake = task.then(() => { }, () => { });
344
+ return task;
345
+ }
346
+ accept(decoded, source, metadata) {
347
+ const r = decoded.rumor, own = r.pubkey === this.account.pubkey;
348
+ // Classification uses only authenticated rumor time; relay/history labels and
349
+ // intentionally backdated wrappers never decide business eligibility.
350
+ if (this.dmActivatedAt === undefined ||
351
+ !createdAtOrAfter(r, this.dmActivatedAt))
352
+ return false;
353
+ const conversation = own
354
+ ? r.tags.find((tag) => tag[0] === "p")?.[1]
355
+ : r.pubkey;
356
+ if (!conversation ||
357
+ (r.kind === 15 && !parseAttachment(r)) ||
358
+ (!own && !this.coreStore.claimInput(r.id)))
359
+ return false;
360
+ const replyTo = replyTarget(r);
361
+ const message = {
362
+ id: r.id,
363
+ sender: r.pubkey,
364
+ conversation,
365
+ text: r.kind === 15 ? "" : r.content,
366
+ timestamp: timestamp(r),
367
+ source,
368
+ direction: own ? "outgoing" : "incoming",
369
+ rumor: r,
370
+ ...(replyTo === undefined ? {} : { replyTo }),
371
+ ...(metadata?.relay
372
+ ? {
373
+ relay: metadata.relay,
374
+ }
375
+ : {}),
376
+ };
377
+ if (!own) {
378
+ this.enqueue(message, decoded);
379
+ return true;
380
+ }
381
+ let inserted = false;
382
+ this.coreStore.transaction(() => {
383
+ this.protocol.remember(decoded, this.coreStore);
384
+ inserted = this.coreStore.insert(message);
385
+ });
386
+ return inserted;
387
+ }
388
+ enqueue(message, decoded) {
389
+ const previous = this.queues.get(message.conversation) ?? Promise.resolve();
390
+ const next = previous
391
+ .catch(() => { })
392
+ .then(async () => {
393
+ let admitted = false;
394
+ const admit = () => {
395
+ if (admitted)
396
+ return;
397
+ this.coreStore.transaction(() => {
398
+ this.protocol.remember(decoded, this.coreStore);
399
+ this.coreStore.insert(message, "processing");
400
+ });
401
+ admitted = true;
402
+ for (const observer of this.observers) {
403
+ try {
404
+ void Promise.resolve(observer(structuredClone(message))).catch((error) => this.report(error, structuredClone(message)));
405
+ }
406
+ catch (error) {
407
+ this.report(error, structuredClone(message));
408
+ }
409
+ }
410
+ };
411
+ const context = { active: true };
412
+ try {
413
+ await this.handlerContext.run(context, async () => {
414
+ // Raw internal listeners are not a second route around Bot middleware.
415
+ const handlers = [...this.handlers];
416
+ const managed = handlers.filter(([, managesAdmission]) => managesAdmission);
417
+ for (const [handler] of managed)
418
+ await handler(structuredClone(message), admit, decoded);
419
+ if (!managed.length)
420
+ admit();
421
+ if (admitted) {
422
+ for (const [handler, managesAdmission] of handlers) {
423
+ if (!managesAdmission)
424
+ await handler(structuredClone(message), admit, decoded);
425
+ }
426
+ }
427
+ });
428
+ if (admitted)
429
+ this.coreStore.state(message.id, "done");
430
+ }
431
+ catch (error) {
432
+ try {
433
+ if (admitted)
434
+ this.coreStore.state(message.id, "failed");
435
+ }
436
+ finally {
437
+ this.report(error, message);
438
+ }
439
+ }
440
+ finally {
441
+ context.active = false;
442
+ }
443
+ })
444
+ .catch((error) => this.report(error, message));
445
+ this.queues.set(message.conversation, next);
446
+ void next.finally(() => {
447
+ if (this.queues.get(message.conversation) === next) {
448
+ this.queues.delete(message.conversation);
449
+ }
450
+ });
451
+ }
452
+ async idle() {
453
+ this.assertOutsideHandler("idle()");
454
+ await this.drainInbox();
455
+ await this.publicInbox?.idle();
456
+ }
457
+ async drainInbox() {
458
+ for (;;) {
459
+ const intake = this.intake;
460
+ await intake;
461
+ await Promise.all(this.queues.values());
462
+ if (this.intake === intake && this.queues.size === 0) {
463
+ return;
464
+ }
465
+ }
466
+ }
467
+ getMessage(id, peer) {
468
+ this.assertOpen();
469
+ if (!hexKey(id))
470
+ throw new TypeError("Invalid message ID");
471
+ const message = this.coreStore.getMessage(id, peer);
472
+ return message && this.withAttachment(message);
473
+ }
474
+ getMessageState(id) {
475
+ this.assertOpen();
476
+ if (!hexKey(id)) {
477
+ throw new TypeError("Invalid message ID");
478
+ }
479
+ return this.coreStore.messageState(id);
480
+ }
481
+ listMessages(options) {
482
+ this.assertOpen();
483
+ const page = this.coreStore.listMessages(options);
484
+ for (const entry of page.entries)
485
+ this.withAttachment(entry.message);
486
+ return page;
487
+ }
488
+ // Closing rejects new work, but a draining handler must still commit its session.
489
+ assertSessionOpen() {
490
+ if (this.closed ||
491
+ (this.closing && !this.handlerContext.getStore()?.active)) {
492
+ throw new Error("Client is closed or closing");
493
+ }
494
+ }
495
+ getSession(peer) {
496
+ this.assertSessionOpen();
497
+ if (!hexKey(peer)) {
498
+ throw new TypeError("Invalid session peer");
499
+ }
500
+ return this.coreStore.session(peer);
501
+ }
502
+ setSession(peer, value) {
503
+ this.assertSessionOpen();
504
+ if (!hexKey(peer)) {
505
+ throw new TypeError("Invalid session peer");
506
+ }
507
+ this.coreStore.saveSession(peer, value);
508
+ }
509
+ assertOutsideHandler(operation = "stop() or close()") {
510
+ if (this.handlerContext.getStore()?.active) {
511
+ throw new Error(`Cannot await ${operation} inside a message handler; drain outside the handler and use requestStop() for shutdown`);
512
+ }
513
+ }
514
+ quiesce() {
515
+ this.running = false;
516
+ this.generation++;
517
+ this.keySync?.stop();
518
+ clearTimeout(this.rotationTimer);
519
+ this.rotationTimer = undefined;
520
+ this.sub?.close();
521
+ this.sub = undefined;
522
+ this.publicInbox?.stop();
523
+ // Cancel an initial metadata read before waiting for startup to finish.
524
+ const metadata = this.metadata.stop();
525
+ void metadata.catch(() => { });
526
+ return metadata;
527
+ }
528
+ async drainStop(metadata) {
529
+ await this.drainInbox();
530
+ await this.publicInbox?.idle();
531
+ if (this.flushing) {
532
+ await this.flushing.catch(() => { });
533
+ }
534
+ await this.keys.idle();
535
+ await this.announcing?.catch(() => { });
536
+ await this.announcements.idle();
537
+ await this.synchronizing?.catch(() => { });
538
+ await this.commands.idle();
539
+ await metadata;
540
+ await this.keySync?.idle();
541
+ }
542
+ stopInternal() {
543
+ if (this.stopping) {
544
+ return this.stopping;
545
+ }
546
+ const startup = this.starting, metadata = this.quiesce();
547
+ const task = (async () => {
548
+ await startup?.catch(() => { });
549
+ await this.drainStop(metadata);
550
+ })().finally(() => {
551
+ if (this.stopping === task) {
552
+ this.stopping = undefined;
553
+ }
554
+ });
555
+ this.stopping = task;
556
+ return task;
557
+ }
558
+ /** Handler-safe stop request; await stop() outside handlers to drain current work. */
559
+ requestStop() {
560
+ this.assertOpen();
561
+ void this.stopInternal().catch((error) => this.report(error));
562
+ }
563
+ async stop() {
564
+ this.assertOutsideHandler();
565
+ await this.stopInternal();
566
+ }
567
+ close() {
568
+ try {
569
+ this.assertOutsideHandler();
570
+ }
571
+ catch (error) {
572
+ return Promise.reject(error);
573
+ }
574
+ if (this.closing) {
575
+ return this.closing;
576
+ }
577
+ if (this.closed) {
578
+ return Promise.resolve();
579
+ }
580
+ const task = Promise.resolve().then(async () => {
581
+ await this.stopInternal();
582
+ try {
583
+ if (this.ownsTransport) {
584
+ this.transport.close();
585
+ }
586
+ }
587
+ finally {
588
+ try {
589
+ this.coreStore.close();
590
+ }
591
+ finally {
592
+ this.closed = true;
593
+ }
594
+ }
595
+ });
596
+ this.closing = task;
597
+ return task;
598
+ }
599
+ async syncHistory() {
600
+ this.assertOpen();
601
+ if (!this.sub || !this.running) {
602
+ throw new Error("Start the client before synchronizing history");
603
+ }
604
+ return this.sub.sync();
605
+ }
606
+ history(peer, options) {
607
+ this.assertOpen();
608
+ const page = this.coreStore.history(peer, options);
609
+ for (const message of page.messages)
610
+ this.withAttachment(message);
611
+ return page;
612
+ }
613
+ withAttachment(message) {
614
+ const { id, rumor, conversation } = message;
615
+ const file = this.attachments.attachment(rumor, () => !this.closed &&
616
+ this.coreStore.getMessage(id, conversation) !== undefined);
617
+ if (file)
618
+ message.file = file;
619
+ return message;
620
+ }
621
+ inputForMessage(message) {
622
+ const input = inputOf(message.rumor);
623
+ const { file } = this.withAttachment(message);
624
+ return file ? { ...input, file } : input;
625
+ }
626
+ /** Rebind an unsigned rumor only to this account's authenticated incoming record. */
627
+ authenticatedInput(event) {
628
+ let snapshot;
629
+ try {
630
+ snapshot = structuredClone(event);
631
+ }
632
+ catch {
633
+ throw new TypeError("Expected an authenticated input event");
634
+ }
635
+ if (!snapshot || typeof snapshot !== "object")
636
+ throw new TypeError("Expected an input event, not an ID");
637
+ if (snapshot.kind === 1 || snapshot.kind === 1111) {
638
+ if (!this.publicInbox)
639
+ throw new Error("Public inbox is not configured");
640
+ return this.publicInbox.target(snapshot);
641
+ }
642
+ if ((snapshot.kind !== 14 && snapshot.kind !== 15) ||
643
+ "sig" in snapshot ||
644
+ !hexKey(snapshot.id))
645
+ throw new TypeError("Expected a signed kind 1/1111 event or authenticated kind 14/15 rumor");
646
+ const message = this.coreStore.getMessage(snapshot.id);
647
+ if (!message) {
648
+ throw new TypeError("DM input does not match an authenticated incoming record for this account");
649
+ }
650
+ const canonical = (input) => JSON.stringify([
651
+ input.id,
652
+ input.pubkey,
653
+ input.kind,
654
+ input.created_at,
655
+ input.tags,
656
+ input.content,
657
+ ]);
658
+ const recipients = Array.isArray(snapshot.tags)
659
+ ? snapshot.tags.filter((tag) => Array.isArray(tag) && tag[0] === "p")
660
+ : [];
661
+ try {
662
+ if (message.direction !== "incoming" ||
663
+ message.sender === this.pubkey ||
664
+ message.sender !== snapshot.pubkey ||
665
+ message.conversation !== snapshot.pubkey ||
666
+ recipients.length !== 1 ||
667
+ recipients[0][1] !== this.pubkey ||
668
+ snapshot.id !== getEventHash(snapshot) ||
669
+ canonical(snapshot) !== canonical(message.rumor) ||
670
+ message.id !== snapshot.id ||
671
+ message.text !== (snapshot.kind === 15 ? "" : snapshot.content) ||
672
+ message.timestamp !== timestamp(snapshot) ||
673
+ message.replyTo !== replyTarget(snapshot))
674
+ throw new Error();
675
+ }
676
+ catch {
677
+ throw new TypeError("DM input does not match an authenticated incoming record for this account");
678
+ }
679
+ return structuredClone(message);
680
+ }
681
+ /** Application-owned delayed work uses the exact event exposed by ctx.input.event. */
682
+ async reply(event, text, options) {
683
+ this.assertOpen();
684
+ const target = this.authenticatedInput(event);
685
+ if ("rumor" in target)
686
+ return this.send(target.conversation, text, options);
687
+ if (options && Object.keys(options).length)
688
+ throw new TypeError("DM send options are not valid for public replies");
689
+ return this.replyPublic(target, text);
690
+ }
691
+ async replyFile(event, data, options = {}) {
692
+ this.assertOpen();
693
+ const target = this.authenticatedInput(event);
694
+ if ("rumor" in target) {
695
+ return this.sendFile(target.conversation, data, {
696
+ ...options,
697
+ replyTo: target.id,
698
+ });
699
+ }
700
+ return this.replyPublicFile(target, data, options);
701
+ }
702
+ /** Verified public context retains its source relay without journaling the input. */
703
+ async replyPublicFile(target, data, options = {}) {
704
+ this.assertOpen();
705
+ if (!this.publicInbox)
706
+ throw new Error("Public inbox is not configured");
707
+ const { mimeType } = options;
708
+ const bytes = snapshotFile(data);
709
+ return this.publicInbox.replyFile(target, async () => {
710
+ const result = await this.uploadFile(bytes, { mimeType });
711
+ this.assertOpen();
712
+ return result;
713
+ });
714
+ }
715
+ async thread(event, options) {
716
+ this.assertOpen();
717
+ const target = this.authenticatedInput(event);
718
+ return "rumor" in target
719
+ ? this.threadPrivate(target, options)
720
+ : this.threadPublic(target, options);
721
+ }
722
+ publicKinds() {
723
+ return [
724
+ ...new Set(this.publicCommandDefinitions().flatMap((definition) => (definition.scopes ?? [])
725
+ .filter((scope) => scope === "kind:1" || scope === "kind:1111")
726
+ .map((scope) => Number(scope.slice(5))))),
727
+ ];
728
+ }
729
+ handlePublic(handler) {
730
+ this.publicHandlers.add(handler);
731
+ return () => {
732
+ this.publicHandlers.delete(handler);
733
+ };
734
+ }
735
+ replyPublic(input, text) {
736
+ this.assertOpen();
737
+ if (!this.publicInbox)
738
+ throw new Error("Public inbox is not configured");
739
+ return this.publicInbox.reply(input, text);
740
+ }
741
+ threadPublic(input, options) {
742
+ this.assertOpen();
743
+ if (!this.publicInbox)
744
+ throw new Error("Public inbox is not configured");
745
+ return this.publicInbox.thread(input, options);
746
+ }
747
+ getPublicSession(key) {
748
+ this.assertSessionOpen();
749
+ return this.coreStore.metadata(`public-session:${key}`);
750
+ }
751
+ setPublicSession(key, value) {
752
+ this.assertSessionOpen();
753
+ this.coreStore.saveMetadata(`public-session:${key}`, value);
754
+ }
755
+ async threadPrivate(message, options = {}) {
756
+ const limit = threadLimit(options.limit);
757
+ let cursor;
758
+ const prior = [];
759
+ for (let page = 0; page < 10 && prior.length <= limit; page++) {
760
+ const history = this.coreStore.history(message.conversation, {
761
+ limit: 100,
762
+ cursor,
763
+ });
764
+ prior.push(...history.messages.filter((item) => item.id !== message.id &&
765
+ (item.timestamp < message.timestamp ||
766
+ (item.timestamp === message.timestamp && item.id < message.id))));
767
+ cursor = history.nextCursor;
768
+ if (!cursor)
769
+ break;
770
+ }
771
+ return {
772
+ entries: prior
773
+ .slice(0, limit)
774
+ .reverse()
775
+ .map((item) => this.inputForMessage(item)),
776
+ complete: false,
777
+ coverage: "local-conversation",
778
+ reason: "local-only",
779
+ };
780
+ }
781
+ /** Register one public command coordinate. Startup reconciles the complete local set. */
782
+ registerCommandDefinition(definition) {
783
+ this.assertOpen();
784
+ this.managesCommandCatalog = true;
785
+ const snapshot = validateCommandDefinition(definition);
786
+ if (snapshot.scopes?.some((scope) => scope === "kind:1" || scope === "kind:1111") &&
787
+ !this.publicInbox)
788
+ throw new TypeError("Public commands require explicit publicInbox.relays");
789
+ const old = this.commandDefinitions.get(snapshot.id);
790
+ if (old && JSON.stringify(old.definition) !== JSON.stringify(snapshot))
791
+ throw new TypeError("Conflicting command coordinate");
792
+ const entry = old ?? { definition: snapshot, refs: 0 };
793
+ entry.refs++;
794
+ this.commandDefinitions.set(snapshot.id, entry);
795
+ this.revokedCommands.delete(snapshot.id);
796
+ this.commandRevision++;
797
+ this.scheduleCommandSync();
798
+ let removed = false;
799
+ const unregister = () => {
800
+ if (removed)
801
+ return;
802
+ removed = true;
803
+ if (this.commandDefinitions.get(snapshot.id) === entry &&
804
+ --entry.refs === 0 &&
805
+ !entry.manual) {
806
+ this.commandDefinitions.delete(snapshot.id);
807
+ this.commandRevision++;
808
+ this.scheduleCommandSync();
809
+ }
810
+ };
811
+ return Object.assign(unregister, {
812
+ active: () => !removed && this.commandDefinitions.get(snapshot.id) === entry,
813
+ });
814
+ }
815
+ /** Claim the bot-owned command catalog, including an intentionally empty registry. */
816
+ manageCommands() {
817
+ this.assertOpen();
818
+ this.managesCommandCatalog = true;
819
+ this.scheduleCommandSync();
820
+ }
821
+ hasCommand(id) {
822
+ return this.commandDefinitions.has(id);
823
+ }
824
+ publicCommandDefinitions() {
825
+ return [...this.commandDefinitions.values()].map((entry) => structuredClone(entry.definition));
826
+ }
827
+ scheduleCommandSync() {
828
+ if (!this.running || this.closing || this.commandSyncScheduled)
829
+ return;
830
+ this.commandSyncScheduled = true;
831
+ queueMicrotask(() => {
832
+ this.commandSyncScheduled = false;
833
+ if (this.running && !this.closing)
834
+ void this.syncCommands().catch((error) => this.report(error));
835
+ });
836
+ }
837
+ /** Synchronize public definitions and NIP-09 withdrawals on write relays. */
838
+ syncCommands() {
839
+ this.assertOpen();
840
+ this.managesCommandCatalog = true;
841
+ if (this.synchronizing)
842
+ return this.synchronizing;
843
+ const generation = this.generation;
844
+ const active = () => !this.closed && !this.closing && this.generation === generation;
845
+ const task = (async () => {
846
+ // Net presence changes across every completed round in this coalesced operation.
847
+ const changes = new Map();
848
+ for (;;) {
849
+ const revision = this.commandRevision, removals = [...this.revokedCommands];
850
+ const result = await this.commands.sync(this.publicCommandDefinitions(), removals, active);
851
+ for (const category of ["added", "updated", "removed"]) {
852
+ for (const id of result[category]) {
853
+ const change = changes.get(id) ?? {
854
+ initial: category !== "added",
855
+ current: false,
856
+ };
857
+ change.current = category !== "removed";
858
+ changes.set(id, change);
859
+ }
860
+ }
861
+ for (const id of removals)
862
+ if (!this.commandDefinitions.has(id))
863
+ this.revokedCommands.delete(id);
864
+ if (this.commandRevision === revision) {
865
+ if (this.running && this.sub)
866
+ await this.publicInbox?.start(this.publicKinds());
867
+ // Registration can change while the new public subscription waits for EOSE.
868
+ if (!active())
869
+ throw new Error("Command synchronization canceled");
870
+ if (this.commandRevision !== revision)
871
+ continue;
872
+ this.syncedCommandRevision = revision;
873
+ const combined = {
874
+ added: [],
875
+ updated: [],
876
+ removed: [],
877
+ };
878
+ for (const [id, change] of changes) {
879
+ if (change.current)
880
+ combined[change.initial ? "updated" : "added"].push(id);
881
+ else if (change.initial)
882
+ combined.removed.push(id);
883
+ }
884
+ return combined;
885
+ }
886
+ }
887
+ })().finally(() => {
888
+ if (this.synchronizing === task)
889
+ this.synchronizing = undefined;
890
+ });
891
+ this.synchronizing = task;
892
+ return task;
893
+ }
894
+ announce(options = {}) {
895
+ this.assertOpen();
896
+ if (this.announcing) {
897
+ return this.announcing.then(() => this.announce(options));
898
+ }
899
+ const task = (async () => {
900
+ this.coreStore.recoverMessages();
901
+ this.keySync?.start();
902
+ await this.metadata.start();
903
+ await this.publishKeyMetadata(options);
904
+ if (this.managesCommandCatalog)
905
+ await this.syncCommands();
906
+ await this.publishMetadata();
907
+ })().finally(() => {
908
+ if (this.announcing === task) {
909
+ this.announcing = undefined;
910
+ }
911
+ });
912
+ this.announcing = task;
913
+ return task;
914
+ }
915
+ async publishKeyMetadata(options) {
916
+ if (this.nip4eCompatibility)
917
+ await this.keys.announce(options);
918
+ else
919
+ await this.keys.prepare();
920
+ }
921
+ // Discovery metadata can fail independently of inbox availability and key custody.
922
+ async publishMetadata() {
923
+ const created_at = Math.floor(Date.now() / 1000);
924
+ const { writeRelays, dmRelays, discoveryRelays } = this.options;
925
+ await this.announcements.publish([
926
+ {
927
+ template: {
928
+ kind: 10002,
929
+ created_at,
930
+ tags: readWriteTags(this.options.readRelays, this.options.writeRelays),
931
+ content: "",
932
+ },
933
+ groups: [writeRelays],
934
+ optionalRelays: discoveryRelays,
935
+ },
936
+ {
937
+ template: {
938
+ kind: 10050,
939
+ created_at,
940
+ tags: this.options.dmRelays.map((url) => ["relay", url]),
941
+ content: "",
942
+ },
943
+ groups: [writeRelays, dmRelays],
944
+ optionalRelays: discoveryRelays,
945
+ },
946
+ ...(this.blossomServers.length
947
+ ? [
948
+ {
949
+ template: {
950
+ kind: 10063,
951
+ created_at,
952
+ tags: this.blossomServers.map((url) => ["server", url]),
953
+ content: "",
954
+ },
955
+ groups: [writeRelays],
956
+ optionalRelays: discoveryRelays,
957
+ },
958
+ ]
959
+ : []),
960
+ ]);
961
+ }
962
+ /** Retry exact persisted public metadata; it does not register/execute discovered commands. */
963
+ async flushAnnouncements() {
964
+ this.assertOpen();
965
+ const pendingKey = !!this.keys.status().pending;
966
+ if (pendingKey) {
967
+ await this.keys.prepare();
968
+ }
969
+ // Background retries should not poll every relay once the registry has converged.
970
+ if (this.managesCommandCatalog &&
971
+ (this.syncedCommandRevision !== this.commandRevision ||
972
+ this.commands.hasPending())) {
973
+ await this.syncCommands();
974
+ }
975
+ if (pendingKey || this.announcements.hasPending()) {
976
+ await this.publishMetadata();
977
+ }
978
+ }
979
+ encryptionKeys() {
980
+ this.assertOpen();
981
+ return this.keys.status();
982
+ }
983
+ async rotateEncryptionKey() {
984
+ this.assertOpen();
985
+ await this.keys.rotate();
986
+ this.scheduleRotation();
987
+ return this.keys.status();
988
+ }
989
+ scheduleRotation() {
990
+ clearTimeout(this.rotationTimer);
991
+ if (!this.running) {
992
+ return;
993
+ }
994
+ const delay = this.keys.nextDelay();
995
+ if (delay === undefined) {
996
+ return;
997
+ }
998
+ this.rotationTimer = setTimeout(() => {
999
+ void this.keys
1000
+ .rotateIfDue()
1001
+ .catch((error) => this.report(error))
1002
+ .finally(() => this.scheduleRotation());
1003
+ }, delay);
1004
+ this.rotationTimer.unref();
1005
+ }
1006
+ async refreshPeer(peer) {
1007
+ this.assertOpen();
1008
+ const metadata = await this.protocol.resolve(peer, this.coreStore, this.transport, this.metadataLookupRelays, true);
1009
+ return {
1010
+ encryptionPubkey: metadata.encryptionPubkey,
1011
+ relays: metadata.relays,
1012
+ };
1013
+ }
1014
+ async publishCommand(definition) {
1015
+ this.assertOpen();
1016
+ this.managesCommandCatalog = true;
1017
+ const snapshot = validateCommandDefinition(definition), old = this.commandDefinitions.get(snapshot.id);
1018
+ if (old &&
1019
+ old.refs > 0 &&
1020
+ JSON.stringify(old.definition) !== JSON.stringify(snapshot))
1021
+ throw new TypeError("Replace the registered Bot command before publishing a changed definition");
1022
+ if (old) {
1023
+ old.definition = snapshot;
1024
+ old.manual = true;
1025
+ }
1026
+ else {
1027
+ this.commandDefinitions.set(snapshot.id, {
1028
+ definition: snapshot,
1029
+ refs: 0,
1030
+ manual: true,
1031
+ });
1032
+ }
1033
+ this.revokedCommands.delete(snapshot.id);
1034
+ this.commandRevision++;
1035
+ await this.syncCommands();
1036
+ const event = this.commands.definition(snapshot.id);
1037
+ if (!event)
1038
+ throw new Error("Command definition missing after synchronization");
1039
+ return { event, status: "relay-accepted" };
1040
+ }
1041
+ async revokeCommand(id) {
1042
+ this.assertOpen();
1043
+ this.managesCommandCatalog = true;
1044
+ if (typeof id !== "string")
1045
+ throw new TypeError("Invalid command ID");
1046
+ this.commandDefinitions.delete(id);
1047
+ this.revokedCommands.add(id);
1048
+ this.commandRevision++;
1049
+ await this.syncCommands();
1050
+ const event = this.commands.revocation(id);
1051
+ if (!event)
1052
+ throw new Error("Command revocation missing after synchronization");
1053
+ return { event, status: "relay-accepted" };
1054
+ }
1055
+ async discoverCommands(options) {
1056
+ this.assertOpen();
1057
+ return discoverCommandCatalog(this.transport, options);
1058
+ }
1059
+ async send(peer, text, { replyTo } = {}, input) {
1060
+ this.assertOpen();
1061
+ if (typeof text !== "string" || !text.length) {
1062
+ throw new Error("Nonempty text required");
1063
+ }
1064
+ if (replyTo !== undefined && !hexKey(replyTo)) {
1065
+ throw new TypeError("replyTo must be a lowercase hex message ID");
1066
+ }
1067
+ const r = rumor(this.account.pubkey, peer, text, undefined, replyTo);
1068
+ const message = {
1069
+ id: r.id,
1070
+ sender: r.pubkey,
1071
+ conversation: peer,
1072
+ text,
1073
+ timestamp: timestamp(r),
1074
+ source: "live",
1075
+ direction: "outgoing",
1076
+ rumor: r,
1077
+ ...(replyTo === undefined ? {} : { replyTo }),
1078
+ };
1079
+ return this.publishPrivate(peer, r, message, input);
1080
+ }
1081
+ async uploadFile(data, options) {
1082
+ this.assertOpen();
1083
+ return uploadFile(this.account, this.blossomServers, this.blossomDownloadOrigins, data, options);
1084
+ }
1085
+ async sendFile(peer, data, options = {}, input) {
1086
+ this.assertOpen();
1087
+ if (!this.blossomServers.length)
1088
+ throw new Error("Configure blossomServers before sending files");
1089
+ if (!hexKey(peer))
1090
+ throw new TypeError("Expected a lowercase hex recipient pubkey");
1091
+ const { replyTo } = options;
1092
+ if (replyTo !== undefined && !hexKey(replyTo))
1093
+ throw new TypeError("replyTo must be a lowercase hex message ID");
1094
+ const { bytes, tags } = encryptAttachment(data, options);
1095
+ await this.protocol.prepare();
1096
+ this.assertOpen();
1097
+ const { url, sha256, size } = await this.uploadFile(bytes);
1098
+ this.assertOpen();
1099
+ const r = fileRumor(this.account.pubkey, peer, url, [...tags, ["x", sha256], ["size", String(size)]], replyTo);
1100
+ return this.publishPrivate(peer, r, {
1101
+ id: r.id,
1102
+ sender: r.pubkey,
1103
+ conversation: peer,
1104
+ text: "",
1105
+ timestamp: timestamp(r),
1106
+ source: "live",
1107
+ direction: "outgoing",
1108
+ rumor: r,
1109
+ ...(replyTo === undefined ? {} : { replyTo }),
1110
+ }, input);
1111
+ }
1112
+ async react(event, reaction) {
1113
+ this.assertOpen();
1114
+ const target = this.authenticatedInput(event);
1115
+ return "rumor" in target
1116
+ ? this.reactToMessage(target, reaction)
1117
+ : this.reactPublic(target, reaction);
1118
+ }
1119
+ async reactPublic(input, reaction) {
1120
+ this.assertOpen();
1121
+ if (!this.publicInbox)
1122
+ throw new Error("Public inbox is not configured");
1123
+ return this.publicInbox.react(input, reaction);
1124
+ }
1125
+ /** The Bot may use a verified incoming anchor before admitting it to history. */
1126
+ async reactToMessage(target, reaction = "+", input) {
1127
+ this.assertOpen();
1128
+ if (typeof reaction !== "string" || !reaction.trim()) {
1129
+ throw new TypeError("Nonempty reaction required");
1130
+ }
1131
+ const r = reactionRumor(this.account.pubkey, target.conversation, target.id, reaction);
1132
+ return this.publishPrivate(target.conversation, r, undefined, input);
1133
+ }
1134
+ async publishPrivate(peer, r, message, input) {
1135
+ const recipients = await this.protocol.recipients(peer, this.coreStore, this.transport, this.metadataLookupRelays, input);
1136
+ const sendingIdentity = {
1137
+ ...this.account,
1138
+ oldEncryptionKeys: this.account.oldEncryptionKeys?.slice(),
1139
+ };
1140
+ const events = [];
1141
+ for (const recipient of recipients) {
1142
+ events.push({
1143
+ event: await wrap(r, sendingIdentity, recipient.pubkey, recipient.encryptionPubkey, recipient.envelope ?? this.protocol.envelope),
1144
+ relays: recipient.relays,
1145
+ });
1146
+ }
1147
+ this.coreStore.transaction(() => {
1148
+ if (message)
1149
+ this.coreStore.insert(message);
1150
+ this.coreStore.putOutbox(r.id, events);
1151
+ });
1152
+ try {
1153
+ await this.flushOutbox();
1154
+ }
1155
+ catch (error) {
1156
+ this.report(error);
1157
+ }
1158
+ return {
1159
+ id: r.id,
1160
+ status: this.coreStore.outbox().some((item) => item.id === r.id)
1161
+ ? "pending"
1162
+ : "relay-accepted",
1163
+ };
1164
+ }
1165
+ flushOutbox() {
1166
+ this.assertOpen();
1167
+ // A caller arriving during a flush may have just committed a newer outbox row.
1168
+ if (this.flushing) {
1169
+ return this.flushing.catch(() => { }).then(() => this.flushOutbox());
1170
+ }
1171
+ this.flushing = (async () => {
1172
+ const pending = this.coreStore.outbox();
1173
+ if (pending.length) {
1174
+ await this.protocol.prepare();
1175
+ }
1176
+ const errors = [];
1177
+ for (const item of pending) {
1178
+ try {
1179
+ for (const envelope of item.events) {
1180
+ await this.transport.publish(envelope.relays, envelope.event);
1181
+ }
1182
+ this.coreStore.ack(item.id);
1183
+ }
1184
+ catch (error) {
1185
+ errors.push(error);
1186
+ }
1187
+ }
1188
+ if (errors.length) {
1189
+ throw new AggregateError(errors, "Some outbox messages remain pending");
1190
+ }
1191
+ await this.publicInbox?.flush();
1192
+ })().finally(() => {
1193
+ this.flushing = undefined;
1194
+ });
1195
+ return this.flushing;
1196
+ }
1197
+ }