@zabaca/zbc 0.24.0 → 0.26.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -1,577 +0,0 @@
1
- import { DurableObject } from 'cloudflare:workers'
2
- import { type MailEnv, emitWebhook, sendMail } from './shared'
3
-
4
- /**
5
- * Inbox — a single SQLite-backed Durable Object holding message metadata and
6
- * parsed bodies. Raw MIME lives in R2 (DO SQLite caps a value at ~2 MB while
7
- * a message can be 5 MiB); `r2_key` points at it.
8
- *
9
- * One DO instance for the whole inbox (idFromName('inbox')) — transactional
10
- * ordering beats sharding at this scale.
11
- */
12
-
13
- export interface MessageMeta {
14
- id: string
15
- from_addr: string
16
- to_addr: string
17
- subject: string
18
- date: string
19
- snippet: string
20
- size: number
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
43
- }
44
-
45
- export interface MessageFull extends MessageMeta {
46
- message_id: string
47
- in_reply_to: string
48
- text_body: string
49
- html_body: string
50
- r2_key: string
51
- attachments: Array<{ filename: string; mimeType: string; size: number }>
52
- }
53
-
54
- export interface InsertMessage {
55
- id: string
56
- message_id: string
57
- from_addr: string
58
- to_addr: string
59
- subject: string
60
- date: string
61
- snippet: string
62
- text_body: string
63
- html_body: string
64
- r2_key: string
65
- attachments_json: string
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
76
- }
77
-
78
- /** Fields of a draft that `updateDraft` may change. */
79
- export type DraftFields = Partial<
80
- Pick<
81
- InsertMessage,
82
- 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
83
- >
84
- >
85
-
86
- /**
87
- * A value the caller must await but the implementation may return
88
- * synchronously: the Inbox class's methods are plain sync SQLite calls, while
89
- * the same methods reached through a `DurableObjectStub` come back as
90
- * Promises. Both satisfy `InboxStore`, and every caller awaits.
91
- */
92
- type Awaitable<T> = T | Promise<T>
93
-
94
- /**
95
- * The narrow view of the Inbox that the commands and the two adapters call.
96
- *
97
- * It exists as an interface rather than as `DurableObjectStub<Inbox>` because
98
- * that type expands workers-types' recursive RPC serialization generics inside
99
- * every `registerTool` inference in `mcp.ts` and trips TS2589 ("type
100
- * instantiation is excessively deep"). `mcp.ts` used to keep a hand-written
101
- * copy of these signatures; the copy lives here now and `Inbox implements
102
- * InboxStore` is what stops it drifting from the class.
103
- *
104
- * It is also the seam the tests use: `worker/commands.test.ts` drives both
105
- * adapters against an in-memory fake of exactly this surface.
106
- */
107
- export interface InboxStore {
108
- list(
109
- limit: number,
110
- cursor?: string,
111
- label?: string,
112
- ): Awaitable<{ messages: MessageMeta[]; nextCursor: string | null }>
113
- listThreads(
114
- limit: number,
115
- cursor?: string,
116
- ): Awaitable<{ threads: ThreadMeta[]; nextCursor: string | null }>
117
- getThread(threadId: string): Awaitable<MessageFull[]>
118
- get(id: string): Awaitable<MessageFull | null>
119
- search(q: string, limit: number): Awaitable<MessageMeta[]>
120
- insert(msg: InsertMessage): Awaitable<{ threadId: string }>
121
- listDrafts(limit: number): Awaitable<MessageMeta[]>
122
- updateDraft(id: string, fields: DraftFields): Awaitable<boolean>
123
- markDraftSent(id: string, date: string): Awaitable<{ threadId: string } | null>
124
- listScheduled(limit: number): Awaitable<ScheduledMeta[]>
125
- cancelScheduled(id: string): Awaitable<boolean>
126
- delete(id: string): Awaitable<string | null>
127
- }
128
-
129
- /** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
130
- function normalizeSubject(subject: string): string {
131
- return subject
132
- .replace(/^(\s*(re|fwd?|fw)\s*:\s*)+/i, '')
133
- .replace(/\s+/g, ' ')
134
- .trim()
135
- .toLowerCase()
136
- }
137
-
138
- export class Inbox extends DurableObject<MailEnv> implements InboxStore {
139
- private sql: SqlStorage
140
-
141
- constructor(ctx: DurableObjectState, env: MailEnv) {
142
- super(ctx, env)
143
- this.sql = ctx.storage.sql
144
- this.sql.exec(`
145
- CREATE TABLE IF NOT EXISTS messages (
146
- id TEXT PRIMARY KEY,
147
- message_id TEXT,
148
- from_addr TEXT NOT NULL,
149
- to_addr TEXT NOT NULL,
150
- subject TEXT,
151
- date TEXT,
152
- snippet TEXT,
153
- text_body TEXT,
154
- html_body TEXT,
155
- r2_key TEXT NOT NULL,
156
- attachments_json TEXT NOT NULL DEFAULT '[]',
157
- size INTEGER NOT NULL DEFAULT 0,
158
- created_at TEXT NOT NULL
159
- );
160
- CREATE INDEX IF NOT EXISTS idx_messages_created ON messages (created_at DESC, id DESC);
161
- `)
162
- // Additive migration for pre-threading deployments (v1 rows had no
163
- // direction/thread columns). ALTER TABLE has no IF NOT EXISTS.
164
- const cols = this.sql
165
- .exec(`SELECT name FROM pragma_table_info('messages')`)
166
- .toArray() as unknown as Array<{ name: string }>
167
- const names = new Set(cols.map((c) => c.name))
168
- if (!names.has('direction')) {
169
- this.sql.exec(`ALTER TABLE messages ADD COLUMN direction TEXT NOT NULL DEFAULT 'inbound'`)
170
- }
171
- if (!names.has('in_reply_to')) {
172
- this.sql.exec(`ALTER TABLE messages ADD COLUMN in_reply_to TEXT NOT NULL DEFAULT ''`)
173
- }
174
- if (!names.has('thread_id')) {
175
- this.sql.exec(`ALTER TABLE messages ADD COLUMN thread_id TEXT NOT NULL DEFAULT ''`)
176
- // Backfill: pre-existing rows each become their own thread, and their
177
- // message_ids get normalized to the bare (bracketless) form the worker
178
- // now stores.
179
- this.sql.exec(
180
- `UPDATE messages SET message_id = replace(replace(trim(message_id), '<', ''), '>', '')`,
181
- )
182
- this.sql.exec(`UPDATE messages SET thread_id = id WHERE thread_id = ''`)
183
- }
184
- if (!names.has('status')) {
185
- this.sql.exec(`ALTER TABLE messages ADD COLUMN status TEXT NOT NULL DEFAULT 'sent'`)
186
- }
187
- if (!names.has('label')) {
188
- this.sql.exec(`ALTER TABLE messages ADD COLUMN label TEXT NOT NULL DEFAULT ''`)
189
- }
190
- if (!names.has('scheduled_at')) {
191
- this.sql.exec(`ALTER TABLE messages ADD COLUMN scheduled_at TEXT NOT NULL DEFAULT ''`)
192
- this.sql.exec(`ALTER TABLE messages ADD COLUMN send_error TEXT NOT NULL DEFAULT ''`)
193
- }
194
- this.sql.exec(`CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages (thread_id, id)`)
195
- }
196
-
197
- /**
198
- * Thread resolution, most-reliable first:
199
- * 1. in_reply_to matches a stored message's RFC Message-ID → that thread.
200
- * 2. Normalized subject matches an existing thread that shares a
201
- * participant address (covers providers that rewrite Message-IDs).
202
- * 3. New thread rooted at this row's id.
203
- */
204
- private resolveThreadId(
205
- rowId: string,
206
- inReplyTo: string,
207
- subject: string,
208
- fromAddr: string,
209
- toAddr: string,
210
- ): string {
211
- if (inReplyTo) {
212
- const byRef = this.sql
213
- .exec(
214
- `SELECT thread_id FROM messages WHERE message_id = ? AND status = 'sent' LIMIT 1`,
215
- inReplyTo,
216
- )
217
- .toArray()[0] as unknown as { thread_id: string } | undefined
218
- if (byRef?.thread_id) return byRef.thread_id
219
- }
220
- const norm = normalizeSubject(subject)
221
- if (norm) {
222
- const participants = [fromAddr, toAddr].map((a) => a.toLowerCase())
223
- const rows = this.sql
224
- .exec(
225
- `SELECT thread_id, subject, from_addr, to_addr FROM messages WHERE status = 'sent' ORDER BY id DESC LIMIT 200`,
226
- )
227
- .toArray() as unknown as Array<{
228
- thread_id: string
229
- subject: string
230
- from_addr: string
231
- to_addr: string
232
- }>
233
- const match = rows.find(
234
- (r) =>
235
- normalizeSubject(r.subject ?? '') === norm &&
236
- [r.from_addr, r.to_addr].some((a) => participants.includes((a ?? '').toLowerCase())),
237
- )
238
- if (match) return match.thread_id
239
- }
240
- return rowId
241
- }
242
-
243
- insert(msg: InsertMessage): { threadId: string } {
244
- const status = msg.status ?? 'sent'
245
- // Drafts/scheduled get no thread until they're actually sent — resolving
246
- // early could anchor a thread to a message that never goes out.
247
- const threadId =
248
- status === 'sent'
249
- ? this.resolveThreadId(msg.id, msg.in_reply_to, msg.subject, msg.from_addr, msg.to_addr)
250
- : ''
251
- this.sql.exec(
252
- `INSERT INTO messages
253
- (id, message_id, from_addr, to_addr, subject, date, snippet,
254
- text_body, html_body, r2_key, attachments_json, size, created_at,
255
- direction, in_reply_to, thread_id, status, scheduled_at)
256
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
257
- msg.id,
258
- msg.message_id,
259
- msg.from_addr,
260
- msg.to_addr,
261
- msg.subject,
262
- msg.date,
263
- msg.snippet,
264
- msg.text_body,
265
- msg.html_body,
266
- msg.r2_key,
267
- msg.attachments_json,
268
- msg.size,
269
- new Date().toISOString(),
270
- msg.direction,
271
- msg.in_reply_to,
272
- threadId,
273
- status,
274
- msg.scheduled_at ?? '',
275
- )
276
- if (status === 'scheduled') this.armAlarm()
277
- return { threadId }
278
- }
279
-
280
- /**
281
- * (Re)arm the DO alarm for the earliest pending scheduled send. Safe to
282
- * call any time — a DO has ONE alarm, so we always point it at MIN(
283
- * scheduled_at); alarm() re-arms for the next one after each batch.
284
- */
285
- private armAlarm(): void {
286
- const next = this.sql
287
- .exec(`SELECT MIN(scheduled_at) AS next FROM messages WHERE status = 'scheduled'`)
288
- .toArray()[0] as unknown as { next: string | null } | undefined
289
- if (next?.next) {
290
- void this.ctx.storage.setAlarm(new Date(next.next).getTime())
291
- }
292
- }
293
-
294
- /**
295
- * Dispatch every due scheduled send. Handles past-due backlogs (missed
296
- * alarms after redeploys/hibernation): everything with scheduled_at <= now
297
- * goes out in this pass, then the alarm re-arms for the next future one.
298
- * A failed dispatch marks the row 'failed' with send_error rather than
299
- * blocking the rest of the batch.
300
- */
301
- async alarm(): Promise<void> {
302
- const now = new Date().toISOString()
303
- const due = this.sql
304
- .exec(
305
- `SELECT id, from_addr, to_addr, subject, text_body, html_body, in_reply_to, snippet
306
- FROM messages WHERE status = 'scheduled' AND scheduled_at <= ? ORDER BY scheduled_at ASC`,
307
- now,
308
- )
309
- .toArray() as unknown as Array<{
310
- id: string
311
- from_addr: string
312
- to_addr: string
313
- subject: string
314
- text_body: string
315
- html_body: string
316
- in_reply_to: string
317
- snippet: string
318
- }>
319
- for (const row of due) {
320
- try {
321
- await sendMail(this.env, {
322
- from: row.from_addr,
323
- to: row.to_addr,
324
- subject: row.subject,
325
- text: row.text_body || undefined,
326
- html: row.html_body || undefined,
327
- inReplyTo: row.in_reply_to,
328
- })
329
- const threadId = this.resolveThreadId(
330
- row.id,
331
- row.in_reply_to,
332
- row.subject,
333
- row.from_addr,
334
- row.to_addr,
335
- )
336
- const sentAt = new Date().toISOString()
337
- this.sql.exec(
338
- `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
339
- threadId,
340
- sentAt,
341
- row.id,
342
- )
343
- await emitWebhook(this.env, 'message.sent', {
344
- id: row.id,
345
- threadId,
346
- from: row.from_addr,
347
- to: row.to_addr,
348
- subject: row.subject,
349
- snippet: row.snippet,
350
- direction: 'outbound',
351
- scheduled: true,
352
- })
353
- } catch (err) {
354
- this.sql.exec(
355
- `UPDATE messages SET status = 'failed', send_error = ? WHERE id = ?`,
356
- (err as Error).message ?? 'send failed',
357
- row.id,
358
- )
359
- }
360
- }
361
- this.armAlarm()
362
- }
363
-
364
- /** Scheduled + failed rows, soonest first (failed sort by original slot). */
365
- listScheduled(limit = 50): ScheduledMeta[] {
366
- const capped = Math.min(Math.max(limit, 1), 200)
367
- return this.sql
368
- .exec(
369
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction,
370
- thread_id, status, label, scheduled_at, send_error
371
- FROM messages WHERE status IN ('scheduled', 'failed')
372
- ORDER BY scheduled_at ASC LIMIT ?`,
373
- capped,
374
- )
375
- .toArray() as unknown as ScheduledMeta[]
376
- }
377
-
378
- /**
379
- * Cancel a pending scheduled send (deletes the row). Failed rows can be
380
- * cancelled too — that's how they're dismissed. Returns false if the id
381
- * isn't a scheduled/failed row.
382
- */
383
- cancelScheduled(id: string): boolean {
384
- const row = this.sql
385
- .exec(`SELECT status FROM messages WHERE id = ?`, id)
386
- .toArray()[0] as unknown as { status: string } | undefined
387
- if (!row || (row.status !== 'scheduled' && row.status !== 'failed')) return false
388
- this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
389
- this.armAlarm()
390
- return true
391
- }
392
-
393
- /** Update an unsent draft's editable fields. Returns false if not a draft. */
394
- updateDraft(id: string, fields: DraftFields): boolean {
395
- const row = this.sql
396
- .exec(`SELECT status FROM messages WHERE id = ?`, id)
397
- .toArray()[0] as unknown as { status: string } | undefined
398
- if (!row || row.status !== 'draft') return false
399
- const cols = Object.keys(fields) as Array<keyof typeof fields>
400
- if (cols.length === 0) return true
401
- this.sql.exec(
402
- `UPDATE messages SET ${cols.map((c) => `${c} = ?`).join(', ')} WHERE id = ?`,
403
- ...cols.map((c) => fields[c] ?? ''),
404
- id,
405
- )
406
- return true
407
- }
408
-
409
- /**
410
- * Flip a draft to sent: resolve its thread NOW (against what actually
411
- * exists at send time) and stamp the send date. Returns null if the row
412
- * isn't an unsent draft.
413
- */
414
- markDraftSent(id: string, date: string): { threadId: string } | null {
415
- const row = this.sql
416
- .exec(
417
- `SELECT status, in_reply_to, subject, from_addr, to_addr FROM messages WHERE id = ?`,
418
- id,
419
- )
420
- .toArray()[0] as unknown as
421
- | { status: string; in_reply_to: string; subject: string; from_addr: string; to_addr: string }
422
- | undefined
423
- if (!row || row.status !== 'draft') return null
424
- const threadId = this.resolveThreadId(
425
- id,
426
- row.in_reply_to,
427
- row.subject,
428
- row.from_addr,
429
- row.to_addr,
430
- )
431
- this.sql.exec(
432
- `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
433
- threadId,
434
- date,
435
- id,
436
- )
437
- return { threadId }
438
- }
439
-
440
- /** Newest-first drafts (metadata only). */
441
- listDrafts(limit = 50): MessageMeta[] {
442
- const capped = Math.min(Math.max(limit, 1), 200)
443
- return this.sql
444
- .exec(
445
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
446
- FROM messages WHERE status = 'draft' ORDER BY id DESC LIMIT ?`,
447
- capped,
448
- )
449
- .toArray() as unknown as MessageMeta[]
450
- }
451
-
452
- /**
453
- * Case-insensitive keyword search over subject + text_body. Plain LIKE —
454
- * fine at this table's scale; revisit with an FTS index if volume grows.
455
- * Drafts included; newest first.
456
- */
457
- search(q: string, limit = 50): MessageMeta[] {
458
- const capped = Math.min(Math.max(limit, 1), 200)
459
- const term = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
460
- return this.sql
461
- .exec(
462
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
463
- FROM messages
464
- WHERE subject LIKE ? ESCAPE '\\' OR text_body LIKE ? ESCAPE '\\'
465
- ORDER BY id DESC LIMIT ?`,
466
- term,
467
- term,
468
- capped,
469
- )
470
- .toArray() as unknown as MessageMeta[]
471
- }
472
-
473
- /** Set the classifier label. No-op if the row is gone (delete raced it). */
474
- setLabel(id: string, label: string): void {
475
- this.sql.exec(`UPDATE messages SET label = ? WHERE id = ?`, label, id)
476
- }
477
-
478
- /**
479
- * Newest-first page (drafts excluded — see listDrafts). `cursor` is the
480
- * last-seen id (ids are time-ordered). `label` filters to one label.
481
- */
482
- list(
483
- limit = 50,
484
- cursor?: string,
485
- label?: string,
486
- ): { messages: MessageMeta[]; nextCursor: string | null } {
487
- const capped = Math.min(Math.max(limit, 1), 200)
488
- const where = [`status = 'sent'`]
489
- const params: unknown[] = []
490
- if (cursor) {
491
- where.push('id < ?')
492
- params.push(cursor)
493
- }
494
- if (label) {
495
- where.push('label = ?')
496
- params.push(label)
497
- }
498
- const rows = this.sql
499
- .exec(
500
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
501
- FROM messages WHERE ${where.join(' AND ')} ORDER BY id DESC LIMIT ?`,
502
- ...params,
503
- capped + 1,
504
- )
505
- .toArray() as unknown as MessageMeta[]
506
- const hasMore = rows.length > capped
507
- const page = hasMore ? rows.slice(0, capped) : rows
508
- return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
509
- }
510
-
511
- /**
512
- * Newest-first page of THREADS: the latest message of each thread plus a
513
- * count. `cursor` is the last-seen latest-message id.
514
- */
515
- listThreads(limit = 50, cursor?: string): { threads: ThreadMeta[]; nextCursor: string | null } {
516
- const capped = Math.min(Math.max(limit, 1), 200)
517
- const base = `
518
- SELECT m.id, m.from_addr, m.to_addr, m.subject, m.date, m.snippet, m.size,
519
- m.created_at, m.direction, m.thread_id, m.status, m.label,
520
- (SELECT COUNT(*) FROM messages c WHERE c.thread_id = m.thread_id) AS thread_count
521
- FROM messages m
522
- WHERE m.status = 'sent'
523
- AND m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
524
- const rows = (cursor
525
- ? this.sql
526
- .exec(`${base} AND m.id < ? ORDER BY m.id DESC LIMIT ?`, cursor, capped + 1)
527
- .toArray()
528
- : this.sql
529
- .exec(`${base} ORDER BY m.id DESC LIMIT ?`, capped + 1)
530
- .toArray()) as unknown as ThreadMeta[]
531
- const hasMore = rows.length > capped
532
- const page = hasMore ? rows.slice(0, capped) : rows
533
- return { threads: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
534
- }
535
-
536
- /** Every message in a thread, oldest-first, with full bodies. */
537
- getThread(threadId: string): MessageFull[] {
538
- const rows = this.sql
539
- .exec(
540
- `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
541
- text_body, html_body, r2_key, attachments_json, size, created_at,
542
- direction, in_reply_to, thread_id, status, label
543
- FROM messages WHERE thread_id = ? ORDER BY id ASC`,
544
- threadId,
545
- )
546
- .toArray() as unknown as Array<MessageFull & { attachments_json: string }>
547
- return rows.map(({ attachments_json, ...rest }) => ({
548
- ...rest,
549
- attachments: JSON.parse(attachments_json || '[]'),
550
- }))
551
- }
552
-
553
- get(id: string): MessageFull | null {
554
- const row = this.sql
555
- .exec(
556
- `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
557
- text_body, html_body, r2_key, attachments_json, size, created_at,
558
- direction, in_reply_to, thread_id, status, label
559
- FROM messages WHERE id = ?`,
560
- id,
561
- )
562
- .toArray()[0] as unknown as (MessageFull & { attachments_json: string }) | undefined
563
- if (!row) return null
564
- const { attachments_json, ...rest } = row
565
- return { ...rest, attachments: JSON.parse(attachments_json || '[]') }
566
- }
567
-
568
- /** Deletes the row; returns the r2_key so the caller can delete the raw blob. */
569
- delete(id: string): string | null {
570
- const row = this.sql.exec(`SELECT r2_key FROM messages WHERE id = ?`, id).toArray()[0] as
571
- | { r2_key: string }
572
- | undefined
573
- if (!row) return null
574
- this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
575
- return row.r2_key
576
- }
577
- }