@zabaca/zbc 0.6.1 → 0.7.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.
@@ -1,4 +1,5 @@
1
1
  import { DurableObject } from 'cloudflare:workers'
2
+ import { type MailEnv, emitWebhook, sendMail } from './shared'
2
3
 
3
4
  /**
4
5
  * Inbox — a single SQLite-backed Durable Object holding message metadata and
@@ -18,10 +19,32 @@ export interface MessageMeta {
18
19
  snippet: string
19
20
  size: number
20
21
  created_at: string
22
+ direction: 'inbound' | 'outbound'
23
+ thread_id: string
24
+ /**
25
+ * 'sent' for everything visible in the inbox (inbound rows included);
26
+ * 'draft' = unsent draft, 'scheduled' = queued for the alarm,
27
+ * 'failed' = a scheduled send the alarm could not dispatch (see send_error
28
+ * in the scheduled listing).
29
+ */
30
+ status: 'draft' | 'scheduled' | 'sent' | 'failed'
31
+ /** Classifier label ('' until/unless labeling runs). */
32
+ label: string
33
+ }
34
+
35
+ /** A scheduled/failed row as returned by listScheduled. */
36
+ export interface ScheduledMeta extends MessageMeta {
37
+ scheduled_at: string
38
+ send_error: string
39
+ }
40
+
41
+ export interface ThreadMeta extends MessageMeta {
42
+ thread_count: number
21
43
  }
22
44
 
23
45
  export interface MessageFull extends MessageMeta {
24
46
  message_id: string
47
+ in_reply_to: string
25
48
  text_body: string
26
49
  html_body: string
27
50
  r2_key: string
@@ -41,13 +64,31 @@ export interface InsertMessage {
41
64
  r2_key: string
42
65
  attachments_json: string
43
66
  size: number
67
+ direction: 'inbound' | 'outbound'
68
+ in_reply_to: string
69
+ /**
70
+ * 'draft'/'scheduled' skip thread resolution (resolved at actual send
71
+ * time). Default 'sent'.
72
+ */
73
+ status?: 'draft' | 'scheduled' | 'sent'
74
+ /** Required when status is 'scheduled': ISO time the alarm should send at. */
75
+ scheduled_at?: string
44
76
  }
45
77
 
46
- export class Inbox extends DurableObject {
78
+ /** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
79
+ function normalizeSubject(subject: string): string {
80
+ return subject
81
+ .replace(/^(\s*(re|fwd?|fw)\s*:\s*)+/i, '')
82
+ .replace(/\s+/g, ' ')
83
+ .trim()
84
+ .toLowerCase()
85
+ }
86
+
87
+ export class Inbox extends DurableObject<MailEnv> {
47
88
  private sql: SqlStorage
48
89
 
49
- constructor(ctx: DurableObjectState, env: unknown) {
50
- super(ctx, env as never)
90
+ constructor(ctx: DurableObjectState, env: MailEnv) {
91
+ super(ctx, env)
51
92
  this.sql = ctx.storage.sql
52
93
  this.sql.exec(`
53
94
  CREATE TABLE IF NOT EXISTS messages (
@@ -67,14 +108,101 @@ export class Inbox extends DurableObject {
67
108
  );
68
109
  CREATE INDEX IF NOT EXISTS idx_messages_created ON messages (created_at DESC, id DESC);
69
110
  `)
111
+ // Additive migration for pre-threading deployments (v1 rows had no
112
+ // direction/thread columns). ALTER TABLE has no IF NOT EXISTS.
113
+ const cols = this.sql
114
+ .exec(`SELECT name FROM pragma_table_info('messages')`)
115
+ .toArray() as unknown as Array<{ name: string }>
116
+ const names = new Set(cols.map((c) => c.name))
117
+ if (!names.has('direction')) {
118
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN direction TEXT NOT NULL DEFAULT 'inbound'`)
119
+ }
120
+ if (!names.has('in_reply_to')) {
121
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN in_reply_to TEXT NOT NULL DEFAULT ''`)
122
+ }
123
+ if (!names.has('thread_id')) {
124
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN thread_id TEXT NOT NULL DEFAULT ''`)
125
+ // Backfill: pre-existing rows each become their own thread, and their
126
+ // message_ids get normalized to the bare (bracketless) form the worker
127
+ // now stores.
128
+ this.sql.exec(
129
+ `UPDATE messages SET message_id = replace(replace(trim(message_id), '<', ''), '>', '')`,
130
+ )
131
+ this.sql.exec(`UPDATE messages SET thread_id = id WHERE thread_id = ''`)
132
+ }
133
+ if (!names.has('status')) {
134
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN status TEXT NOT NULL DEFAULT 'sent'`)
135
+ }
136
+ if (!names.has('label')) {
137
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN label TEXT NOT NULL DEFAULT ''`)
138
+ }
139
+ if (!names.has('scheduled_at')) {
140
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN scheduled_at TEXT NOT NULL DEFAULT ''`)
141
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN send_error TEXT NOT NULL DEFAULT ''`)
142
+ }
143
+ this.sql.exec(`CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages (thread_id, id)`)
70
144
  }
71
145
 
72
- insert(msg: InsertMessage): void {
146
+ /**
147
+ * Thread resolution, most-reliable first:
148
+ * 1. in_reply_to matches a stored message's RFC Message-ID → that thread.
149
+ * 2. Normalized subject matches an existing thread that shares a
150
+ * participant address (covers providers that rewrite Message-IDs).
151
+ * 3. New thread rooted at this row's id.
152
+ */
153
+ private resolveThreadId(
154
+ rowId: string,
155
+ inReplyTo: string,
156
+ subject: string,
157
+ fromAddr: string,
158
+ toAddr: string,
159
+ ): string {
160
+ if (inReplyTo) {
161
+ const byRef = this.sql
162
+ .exec(
163
+ `SELECT thread_id FROM messages WHERE message_id = ? AND status = 'sent' LIMIT 1`,
164
+ inReplyTo,
165
+ )
166
+ .toArray()[0] as unknown as { thread_id: string } | undefined
167
+ if (byRef?.thread_id) return byRef.thread_id
168
+ }
169
+ const norm = normalizeSubject(subject)
170
+ if (norm) {
171
+ const participants = [fromAddr, toAddr].map((a) => a.toLowerCase())
172
+ const rows = this.sql
173
+ .exec(
174
+ `SELECT thread_id, subject, from_addr, to_addr FROM messages WHERE status = 'sent' ORDER BY id DESC LIMIT 200`,
175
+ )
176
+ .toArray() as unknown as Array<{
177
+ thread_id: string
178
+ subject: string
179
+ from_addr: string
180
+ to_addr: string
181
+ }>
182
+ const match = rows.find(
183
+ (r) =>
184
+ normalizeSubject(r.subject ?? '') === norm &&
185
+ [r.from_addr, r.to_addr].some((a) => participants.includes((a ?? '').toLowerCase())),
186
+ )
187
+ if (match) return match.thread_id
188
+ }
189
+ return rowId
190
+ }
191
+
192
+ insert(msg: InsertMessage): { threadId: string } {
193
+ const status = msg.status ?? 'sent'
194
+ // Drafts/scheduled get no thread until they're actually sent — resolving
195
+ // early could anchor a thread to a message that never goes out.
196
+ const threadId =
197
+ status === 'sent'
198
+ ? this.resolveThreadId(msg.id, msg.in_reply_to, msg.subject, msg.from_addr, msg.to_addr)
199
+ : ''
73
200
  this.sql.exec(
74
201
  `INSERT INTO messages
75
202
  (id, message_id, from_addr, to_addr, subject, date, snippet,
76
- text_body, html_body, r2_key, attachments_json, size, created_at)
77
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
203
+ text_body, html_body, r2_key, attachments_json, size, created_at,
204
+ direction, in_reply_to, thread_id, status, scheduled_at)
205
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
78
206
  msg.id,
79
207
  msg.message_id,
80
208
  msg.from_addr,
@@ -88,38 +216,303 @@ export class Inbox extends DurableObject {
88
216
  msg.attachments_json,
89
217
  msg.size,
90
218
  new Date().toISOString(),
219
+ msg.direction,
220
+ msg.in_reply_to,
221
+ threadId,
222
+ status,
223
+ msg.scheduled_at ?? '',
224
+ )
225
+ if (status === 'scheduled') this.armAlarm()
226
+ return { threadId }
227
+ }
228
+
229
+ /**
230
+ * (Re)arm the DO alarm for the earliest pending scheduled send. Safe to
231
+ * call any time — a DO has ONE alarm, so we always point it at MIN(
232
+ * scheduled_at); alarm() re-arms for the next one after each batch.
233
+ */
234
+ private armAlarm(): void {
235
+ const next = this.sql
236
+ .exec(`SELECT MIN(scheduled_at) AS next FROM messages WHERE status = 'scheduled'`)
237
+ .toArray()[0] as unknown as { next: string | null } | undefined
238
+ if (next?.next) {
239
+ void this.ctx.storage.setAlarm(new Date(next.next).getTime())
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Dispatch every due scheduled send. Handles past-due backlogs (missed
245
+ * alarms after redeploys/hibernation): everything with scheduled_at <= now
246
+ * goes out in this pass, then the alarm re-arms for the next future one.
247
+ * A failed dispatch marks the row 'failed' with send_error rather than
248
+ * blocking the rest of the batch.
249
+ */
250
+ async alarm(): Promise<void> {
251
+ const now = new Date().toISOString()
252
+ const due = this.sql
253
+ .exec(
254
+ `SELECT id, from_addr, to_addr, subject, text_body, html_body, in_reply_to, snippet
255
+ FROM messages WHERE status = 'scheduled' AND scheduled_at <= ? ORDER BY scheduled_at ASC`,
256
+ now,
257
+ )
258
+ .toArray() as unknown as Array<{
259
+ id: string
260
+ from_addr: string
261
+ to_addr: string
262
+ subject: string
263
+ text_body: string
264
+ html_body: string
265
+ in_reply_to: string
266
+ snippet: string
267
+ }>
268
+ for (const row of due) {
269
+ try {
270
+ await sendMail(this.env, {
271
+ from: row.from_addr,
272
+ to: row.to_addr,
273
+ subject: row.subject,
274
+ text: row.text_body || undefined,
275
+ html: row.html_body || undefined,
276
+ inReplyTo: row.in_reply_to,
277
+ })
278
+ const threadId = this.resolveThreadId(
279
+ row.id,
280
+ row.in_reply_to,
281
+ row.subject,
282
+ row.from_addr,
283
+ row.to_addr,
284
+ )
285
+ const sentAt = new Date().toISOString()
286
+ this.sql.exec(
287
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
288
+ threadId,
289
+ sentAt,
290
+ row.id,
291
+ )
292
+ await emitWebhook(this.env, 'message.sent', {
293
+ id: row.id,
294
+ threadId,
295
+ from: row.from_addr,
296
+ to: row.to_addr,
297
+ subject: row.subject,
298
+ snippet: row.snippet,
299
+ direction: 'outbound',
300
+ scheduled: true,
301
+ })
302
+ } catch (err) {
303
+ this.sql.exec(
304
+ `UPDATE messages SET status = 'failed', send_error = ? WHERE id = ?`,
305
+ (err as Error).message ?? 'send failed',
306
+ row.id,
307
+ )
308
+ }
309
+ }
310
+ this.armAlarm()
311
+ }
312
+
313
+ /** Scheduled + failed rows, soonest first (failed sort by original slot). */
314
+ listScheduled(limit = 50): ScheduledMeta[] {
315
+ const capped = Math.min(Math.max(limit, 1), 200)
316
+ return this.sql
317
+ .exec(
318
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction,
319
+ thread_id, status, label, scheduled_at, send_error
320
+ FROM messages WHERE status IN ('scheduled', 'failed')
321
+ ORDER BY scheduled_at ASC LIMIT ?`,
322
+ capped,
323
+ )
324
+ .toArray() as unknown as ScheduledMeta[]
325
+ }
326
+
327
+ /**
328
+ * Cancel a pending scheduled send (deletes the row). Failed rows can be
329
+ * cancelled too — that's how they're dismissed. Returns false if the id
330
+ * isn't a scheduled/failed row.
331
+ */
332
+ cancelScheduled(id: string): boolean {
333
+ const row = this.sql
334
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
335
+ .toArray()[0] as unknown as { status: string } | undefined
336
+ if (!row || (row.status !== 'scheduled' && row.status !== 'failed')) return false
337
+ this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
338
+ this.armAlarm()
339
+ return true
340
+ }
341
+
342
+ /** Update an unsent draft's editable fields. Returns false if not a draft. */
343
+ updateDraft(
344
+ id: string,
345
+ fields: Partial<
346
+ Pick<
347
+ InsertMessage,
348
+ 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
349
+ >
350
+ >,
351
+ ): boolean {
352
+ const row = this.sql
353
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
354
+ .toArray()[0] as unknown as { status: string } | undefined
355
+ if (!row || row.status !== 'draft') return false
356
+ const cols = Object.keys(fields) as Array<keyof typeof fields>
357
+ if (cols.length === 0) return true
358
+ this.sql.exec(
359
+ `UPDATE messages SET ${cols.map((c) => `${c} = ?`).join(', ')} WHERE id = ?`,
360
+ ...cols.map((c) => fields[c] ?? ''),
361
+ id,
362
+ )
363
+ return true
364
+ }
365
+
366
+ /**
367
+ * Flip a draft to sent: resolve its thread NOW (against what actually
368
+ * exists at send time) and stamp the send date. Returns null if the row
369
+ * isn't an unsent draft.
370
+ */
371
+ markDraftSent(id: string, date: string): { threadId: string } | null {
372
+ const row = this.sql
373
+ .exec(
374
+ `SELECT status, in_reply_to, subject, from_addr, to_addr FROM messages WHERE id = ?`,
375
+ id,
376
+ )
377
+ .toArray()[0] as unknown as
378
+ | { status: string; in_reply_to: string; subject: string; from_addr: string; to_addr: string }
379
+ | undefined
380
+ if (!row || row.status !== 'draft') return null
381
+ const threadId = this.resolveThreadId(
382
+ id,
383
+ row.in_reply_to,
384
+ row.subject,
385
+ row.from_addr,
386
+ row.to_addr,
91
387
  )
388
+ this.sql.exec(
389
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
390
+ threadId,
391
+ date,
392
+ id,
393
+ )
394
+ return { threadId }
92
395
  }
93
396
 
94
- /** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
95
- list(limit = 50, cursor?: string): { messages: MessageMeta[]; nextCursor: string | null } {
397
+ /** Newest-first drafts (metadata only). */
398
+ listDrafts(limit = 50): MessageMeta[] {
96
399
  const capped = Math.min(Math.max(limit, 1), 200)
400
+ return this.sql
401
+ .exec(
402
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
403
+ FROM messages WHERE status = 'draft' ORDER BY id DESC LIMIT ?`,
404
+ capped,
405
+ )
406
+ .toArray() as unknown as MessageMeta[]
407
+ }
408
+
409
+ /**
410
+ * Case-insensitive keyword search over subject + text_body. Plain LIKE —
411
+ * fine at this table's scale; revisit with an FTS index if volume grows.
412
+ * Drafts included; newest first.
413
+ */
414
+ search(q: string, limit = 50): MessageMeta[] {
415
+ const capped = Math.min(Math.max(limit, 1), 200)
416
+ const term = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
417
+ return this.sql
418
+ .exec(
419
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
420
+ FROM messages
421
+ WHERE subject LIKE ? ESCAPE '\\' OR text_body LIKE ? ESCAPE '\\'
422
+ ORDER BY id DESC LIMIT ?`,
423
+ term,
424
+ term,
425
+ capped,
426
+ )
427
+ .toArray() as unknown as MessageMeta[]
428
+ }
429
+
430
+ /** Set the classifier label. No-op if the row is gone (delete raced it). */
431
+ setLabel(id: string, label: string): void {
432
+ this.sql.exec(`UPDATE messages SET label = ? WHERE id = ?`, label, id)
433
+ }
434
+
435
+ /**
436
+ * Newest-first page (drafts excluded — see listDrafts). `cursor` is the
437
+ * last-seen id (ids are time-ordered). `label` filters to one label.
438
+ */
439
+ list(
440
+ limit = 50,
441
+ cursor?: string,
442
+ label?: string,
443
+ ): { messages: MessageMeta[]; nextCursor: string | null } {
444
+ const capped = Math.min(Math.max(limit, 1), 200)
445
+ const where = [`status = 'sent'`]
446
+ const params: unknown[] = []
447
+ if (cursor) {
448
+ where.push('id < ?')
449
+ params.push(cursor)
450
+ }
451
+ if (label) {
452
+ where.push('label = ?')
453
+ params.push(label)
454
+ }
455
+ const rows = this.sql
456
+ .exec(
457
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
458
+ FROM messages WHERE ${where.join(' AND ')} ORDER BY id DESC LIMIT ?`,
459
+ ...params,
460
+ capped + 1,
461
+ )
462
+ .toArray() as unknown as MessageMeta[]
463
+ const hasMore = rows.length > capped
464
+ const page = hasMore ? rows.slice(0, capped) : rows
465
+ return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
466
+ }
467
+
468
+ /**
469
+ * Newest-first page of THREADS: the latest message of each thread plus a
470
+ * count. `cursor` is the last-seen latest-message id.
471
+ */
472
+ listThreads(limit = 50, cursor?: string): { threads: ThreadMeta[]; nextCursor: string | null } {
473
+ const capped = Math.min(Math.max(limit, 1), 200)
474
+ const base = `
475
+ SELECT m.id, m.from_addr, m.to_addr, m.subject, m.date, m.snippet, m.size,
476
+ m.created_at, m.direction, m.thread_id, m.status, m.label,
477
+ (SELECT COUNT(*) FROM messages c WHERE c.thread_id = m.thread_id) AS thread_count
478
+ FROM messages m
479
+ WHERE m.status = 'sent'
480
+ AND m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
97
481
  const rows = (cursor
98
482
  ? this.sql
99
- .exec(
100
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
101
- FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
102
- cursor,
103
- capped + 1,
104
- )
483
+ .exec(`${base} AND m.id < ? ORDER BY m.id DESC LIMIT ?`, cursor, capped + 1)
105
484
  .toArray()
106
485
  : this.sql
107
- .exec(
108
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
109
- FROM messages ORDER BY id DESC LIMIT ?`,
110
- capped + 1,
111
- )
112
- .toArray()) as unknown as MessageMeta[]
486
+ .exec(`${base} ORDER BY m.id DESC LIMIT ?`, capped + 1)
487
+ .toArray()) as unknown as ThreadMeta[]
113
488
  const hasMore = rows.length > capped
114
489
  const page = hasMore ? rows.slice(0, capped) : rows
115
- return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
490
+ return { threads: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
491
+ }
492
+
493
+ /** Every message in a thread, oldest-first, with full bodies. */
494
+ getThread(threadId: string): MessageFull[] {
495
+ const rows = this.sql
496
+ .exec(
497
+ `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
498
+ text_body, html_body, r2_key, attachments_json, size, created_at,
499
+ direction, in_reply_to, thread_id, status, label
500
+ FROM messages WHERE thread_id = ? ORDER BY id ASC`,
501
+ threadId,
502
+ )
503
+ .toArray() as unknown as Array<MessageFull & { attachments_json: string }>
504
+ return rows.map(({ attachments_json, ...rest }) => ({
505
+ ...rest,
506
+ attachments: JSON.parse(attachments_json || '[]'),
507
+ }))
116
508
  }
117
509
 
118
510
  get(id: string): MessageFull | null {
119
511
  const row = this.sql
120
512
  .exec(
121
513
  `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
122
- text_body, html_body, r2_key, attachments_json, size, created_at
514
+ text_body, html_body, r2_key, attachments_json, size, created_at,
515
+ direction, in_reply_to, thread_id, status, label
123
516
  FROM messages WHERE id = ?`,
124
517
  id,
125
518
  )