@zabaca/zbc 0.13.0 → 0.14.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.
- package/CHANGELOG.md +117 -6
- package/package.json +5 -2
- package/src/commands/add.ts +13 -0
- package/src/commands/init.ts +1 -0
- package/src/engine/apply.ts +60 -21
- package/src/engine/destroy.ts +183 -14
- package/src/engine/discover.ts +1 -1
- package/src/engine/resolve.ts +56 -11
- package/src/utils/copy-template.ts +10 -0
- package/templates/apps/inbox/package.json +3 -1
- package/templates/apps/inbox/tsconfig.json +3 -1
- package/templates/apps/inbox/worker/api.ts +197 -0
- package/templates/apps/inbox/worker/commands.ts +299 -0
- package/templates/apps/inbox/worker/inbox-do.ts +53 -10
- package/templates/apps/inbox/worker/index.ts +15 -202
- package/templates/apps/inbox/worker/mcp.ts +49 -100
- package/templates/infra/modules/cloudflare/index.ts +25 -70
- package/templates/infra/modules/cloudflare-access/index.ts +3 -3
- package/templates/infra/modules/cloudflare-api/index.ts +144 -32
- package/templates/infra/modules/cloudflare-api/registry.json +1 -1
- package/templates/infra/modules/cloudflare-email/index.ts +103 -144
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-token/index.ts +10 -30
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
- package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
- package/templates/infra/modules/fly/index.ts +17 -34
- package/templates/infra/modules/host-file/index.ts +6 -7
- package/templates/infra/modules/provision-core/index.ts +21 -15
- package/templates/infra/modules/r2/index.ts +38 -55
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/modules/remote-provision/index.ts +1 -3
- package/templates/infra/modules/turso/index.ts +2 -4
- package/templates/infra/modules/vm-provision/index.ts +10 -3
- package/templates/infra/src/context.ts +115 -0
- package/templates/infra/src/define-module.ts +8 -2
- package/templates/infra/src/index.ts +11 -1
- package/templates/infra/src/types.ts +72 -3
- package/src/commands/add-registry.test.ts +0 -92
- package/src/commands/secret.test.ts +0 -717
- package/src/commands/vendor-mode.test.ts +0 -183
- package/src/infra-types.ts +0 -38
- package/src/utils/subtree.test.ts +0 -127
- package/templates/apps/inbox/worker/send-op.ts +0 -174
|
@@ -13,5 +13,7 @@
|
|
|
13
13
|
"lib": ["esnext"],
|
|
14
14
|
"types": ["@cloudflare/workers-types"]
|
|
15
15
|
},
|
|
16
|
-
"include": ["worker"]
|
|
16
|
+
"include": ["worker"],
|
|
17
|
+
"// exclude": "Test files are excluded because bun:test's `expect` typings clash with @cloudflare/workers-types' Request/Response shapes when both are in one program (same split warehouse's tsconfig.worker.json documents). `bun test` still type-strips and runs them.",
|
|
18
|
+
"exclude": ["node_modules", "**/*.test.ts"]
|
|
17
19
|
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The JSON adapter: bearer-authed `/api/*` over the Inbox. One of the two
|
|
3
|
+
* adapters (the other is `mcp.ts`) — it parses HTTP, calls a command or a
|
|
4
|
+
* read, and renders the result. No mutation logic lives here.
|
|
5
|
+
*
|
|
6
|
+
* It is a module rather than a block inside `index.ts` for the same reason
|
|
7
|
+
* `handleMcp` is: `index.ts` is the Workers entry and imports the Inbox
|
|
8
|
+
* Durable Object, which imports `cloudflare:workers` — a specifier bun cannot
|
|
9
|
+
* resolve, so a test can never load it. Everything here reaches the DO through
|
|
10
|
+
* the `InboxStore` interface, so `worker/commands.test.ts` can drive both
|
|
11
|
+
* adapters against the same in-memory fake.
|
|
12
|
+
*/
|
|
13
|
+
import PostalMime from 'postal-mime'
|
|
14
|
+
import * as commands from './commands'
|
|
15
|
+
import type { DraftBody, SendBody, SendEnv } from './commands'
|
|
16
|
+
import type { InboxStore } from './inbox-do'
|
|
17
|
+
|
|
18
|
+
export interface ApiEnv extends SendEnv {
|
|
19
|
+
RAW: R2Bucket
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ApiDeps {
|
|
23
|
+
env: ApiEnv
|
|
24
|
+
store: InboxStore
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function json(data: unknown, status = 200): Response {
|
|
28
|
+
return Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function handleApi(request: Request, deps: ApiDeps): Promise<Response> {
|
|
32
|
+
const { env, store } = deps
|
|
33
|
+
const url = new URL(request.url)
|
|
34
|
+
const { pathname } = url
|
|
35
|
+
|
|
36
|
+
// GET /api/messages?limit=&cursor=&label=
|
|
37
|
+
if (pathname === '/api/messages' && request.method === 'GET') {
|
|
38
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
39
|
+
const cursor = url.searchParams.get('cursor') ?? undefined
|
|
40
|
+
const label = url.searchParams.get('label') ?? undefined
|
|
41
|
+
return json(await store.list(Number.isFinite(limit) ? limit : 50, cursor, label))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// GET /api/search?q=&limit= — keyword match over subject + text body
|
|
45
|
+
if (pathname === '/api/search' && request.method === 'GET') {
|
|
46
|
+
const q = url.searchParams.get('q') ?? ''
|
|
47
|
+
if (!q.trim()) return json({ error: 'required: q' }, 400)
|
|
48
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
49
|
+
return json({ messages: await store.search(q.trim(), Number.isFinite(limit) ? limit : 50) })
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// GET /api/threads?limit=&cursor= — newest-first, one row per thread
|
|
53
|
+
if (pathname === '/api/threads' && request.method === 'GET') {
|
|
54
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
55
|
+
const cursor = url.searchParams.get('cursor') ?? undefined
|
|
56
|
+
return json(await store.listThreads(Number.isFinite(limit) ? limit : 50, cursor))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// GET /api/threads/:id — all messages in the thread, oldest-first
|
|
60
|
+
const threadMatch = pathname.match(/^\/api\/threads\/([^/]+)$/)
|
|
61
|
+
if (threadMatch && request.method === 'GET') {
|
|
62
|
+
const messages = await store.getThread(threadMatch[1]!)
|
|
63
|
+
return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// POST /api/send — immediate, or queued for the DO alarm when sendAt set
|
|
67
|
+
if (pathname === '/api/send' && request.method === 'POST') {
|
|
68
|
+
let body: SendBody
|
|
69
|
+
try {
|
|
70
|
+
body = (await request.json()) as SendBody
|
|
71
|
+
} catch {
|
|
72
|
+
return json({ error: 'invalid JSON body' }, 400)
|
|
73
|
+
}
|
|
74
|
+
const outcome = await commands.send(env, store, body)
|
|
75
|
+
return json(outcome.body, outcome.status)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// GET /api/scheduled — pending + failed scheduled sends, soonest first
|
|
79
|
+
if (pathname === '/api/scheduled' && request.method === 'GET') {
|
|
80
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
81
|
+
return json({ scheduled: await store.listScheduled(Number.isFinite(limit) ? limit : 50) })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// DELETE /api/scheduled/:id — cancel a pending (or dismiss a failed) send
|
|
85
|
+
const schedMatch = pathname.match(/^\/api\/scheduled\/([^/]+)$/)
|
|
86
|
+
if (schedMatch && request.method === 'DELETE') {
|
|
87
|
+
const outcome = await commands.cancelScheduled(store, schedMatch[1]!)
|
|
88
|
+
return json(outcome.body, outcome.status)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// POST /api/drafts — store an outbound message without sending it
|
|
92
|
+
if (pathname === '/api/drafts' && request.method === 'POST') {
|
|
93
|
+
let body: DraftBody
|
|
94
|
+
try {
|
|
95
|
+
body = (await request.json()) as DraftBody
|
|
96
|
+
} catch {
|
|
97
|
+
return json({ error: 'invalid JSON body' }, 400)
|
|
98
|
+
}
|
|
99
|
+
const outcome = await commands.createDraft(env, store, body)
|
|
100
|
+
return json(outcome.body, outcome.status)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// GET /api/drafts
|
|
104
|
+
if (pathname === '/api/drafts' && request.method === 'GET') {
|
|
105
|
+
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
106
|
+
return json({ drafts: await store.listDrafts(Number.isFinite(limit) ? limit : 50) })
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// PUT /api/drafts/:id | POST /api/drafts/:id/send
|
|
110
|
+
const draftMatch = pathname.match(/^\/api\/drafts\/([^/]+)(\/send)?$/)
|
|
111
|
+
if (draftMatch) {
|
|
112
|
+
const [, draftId, sendSuffix] = draftMatch
|
|
113
|
+
|
|
114
|
+
if (!sendSuffix && request.method === 'PUT') {
|
|
115
|
+
let body: DraftBody
|
|
116
|
+
try {
|
|
117
|
+
body = (await request.json()) as DraftBody
|
|
118
|
+
} catch {
|
|
119
|
+
return json({ error: 'invalid JSON body' }, 400)
|
|
120
|
+
}
|
|
121
|
+
const outcome = await commands.updateDraft(store, draftId!, body)
|
|
122
|
+
return json(outcome.body, outcome.status)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (sendSuffix && request.method === 'POST') {
|
|
126
|
+
const outcome = await commands.sendDraft(env, store, draftId!)
|
|
127
|
+
return json(outcome.body, outcome.status)
|
|
128
|
+
}
|
|
129
|
+
if (!sendSuffix && request.method === 'GET') {
|
|
130
|
+
const draft = await store.get(draftId!)
|
|
131
|
+
return draft && draft.status === 'draft' ? json(draft) : json({ error: 'not a draft' }, 404)
|
|
132
|
+
}
|
|
133
|
+
// Deliberately NOT commands.deleteMessage: this route deletes drafts and
|
|
134
|
+
// only drafts, refusing anything else, where the command deletes a row of
|
|
135
|
+
// any status. Two different operations that happen to share a verb.
|
|
136
|
+
if (!sendSuffix && request.method === 'DELETE') {
|
|
137
|
+
const draft = await store.get(draftId!)
|
|
138
|
+
if (!draft || draft.status !== 'draft') return json({ error: 'not a draft' }, 404)
|
|
139
|
+
await store.delete(draftId!)
|
|
140
|
+
return json({ ok: true })
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// GET /api/messages/:id/attachments/:n — raw bytes of one attachment.
|
|
145
|
+
// Re-parses the R2 MIME blob per request (cheap at the 5 MiB cap) rather
|
|
146
|
+
// than pre-splitting attachments at write time.
|
|
147
|
+
const attMatch = pathname.match(/^\/api\/messages\/([^/]+)\/attachments\/(\d+)$/)
|
|
148
|
+
if (attMatch && request.method === 'GET') {
|
|
149
|
+
const msg = await store.get(attMatch[1]!)
|
|
150
|
+
if (!msg) return json({ error: 'not found' }, 404)
|
|
151
|
+
if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
|
|
152
|
+
const obj = await env.RAW.get(msg.r2_key)
|
|
153
|
+
if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
|
|
154
|
+
const parsed = await PostalMime.parse(await obj.arrayBuffer())
|
|
155
|
+
const n = Number(attMatch[2])
|
|
156
|
+
const att = (parsed.attachments ?? [])[n]
|
|
157
|
+
if (!att) return json({ error: `no attachment at index ${n}` }, 404)
|
|
158
|
+
const body =
|
|
159
|
+
typeof att.content === 'string' ? new TextEncoder().encode(att.content) : att.content
|
|
160
|
+
return new Response(body, {
|
|
161
|
+
headers: {
|
|
162
|
+
'content-type': att.mimeType || 'application/octet-stream',
|
|
163
|
+
'content-disposition': `attachment; filename="${(att.filename ?? 'attachment').replace(/["\r\n]/g, '')}"`,
|
|
164
|
+
'cache-control': 'no-store',
|
|
165
|
+
},
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// /api/messages/:id[/raw]
|
|
170
|
+
const match = pathname.match(/^\/api\/messages\/([^/]+)(\/raw)?$/)
|
|
171
|
+
if (match) {
|
|
172
|
+
const [, id, rawSuffix] = match
|
|
173
|
+
|
|
174
|
+
if (rawSuffix && request.method === 'GET') {
|
|
175
|
+
const msg = await store.get(id!)
|
|
176
|
+
if (!msg) return json({ error: 'not found' }, 404)
|
|
177
|
+
if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
|
|
178
|
+
const obj = await env.RAW.get(msg.r2_key)
|
|
179
|
+
if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
|
|
180
|
+
return new Response(obj.body, {
|
|
181
|
+
headers: { 'content-type': 'message/rfc822', 'cache-control': 'no-store' },
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (!rawSuffix && request.method === 'GET') {
|
|
186
|
+
const msg = await store.get(id!)
|
|
187
|
+
return msg ? json(msg) : json({ error: 'not found' }, 404)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!rawSuffix && request.method === 'DELETE') {
|
|
191
|
+
const outcome = await commands.deleteMessage(env, store, id!)
|
|
192
|
+
return json(outcome.body, outcome.status)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return json({ error: 'not found' }, 404)
|
|
197
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import type { DraftFields, InboxStore } from './inbox-do'
|
|
2
|
+
import { type MailEnv, emitWebhook, makeSnippet, newId, normalizeMsgId, sendMail } from './shared'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Every mutation the inbox supports, once. The two adapters — `api.ts` (the
|
|
6
|
+
* JSON routes) and `mcp.ts` (the MCP tools) — parse their own input shape,
|
|
7
|
+
* call one of these, and render the `Outcome`; neither holds mutation logic
|
|
8
|
+
* of its own. A Worker cannot fetch its own routes, so this is a module of
|
|
9
|
+
* functions rather than one adapter calling the other.
|
|
10
|
+
*
|
|
11
|
+
* The shape is uniform: `(env?, store, input) -> Outcome`, where `Outcome`
|
|
12
|
+
* carries the HTTP status the JSON route answers with. The MCP adapter reads
|
|
13
|
+
* the same status: >= 400 becomes a tool error, anything else the tool result.
|
|
14
|
+
*
|
|
15
|
+
* Reads (list/search/get/…) are NOT here — they are single `store.*` calls
|
|
16
|
+
* and both adapters make them directly.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A command's result, in the JSON adapter's vocabulary because that adapter
|
|
21
|
+
* is the reference: `status` is the HTTP status `/api/*` answers with, `body`
|
|
22
|
+
* the JSON it renders.
|
|
23
|
+
*/
|
|
24
|
+
export interface Outcome {
|
|
25
|
+
status: number
|
|
26
|
+
body: Record<string, unknown>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SendBody {
|
|
30
|
+
to: string
|
|
31
|
+
subject: string
|
|
32
|
+
text?: string
|
|
33
|
+
html?: string
|
|
34
|
+
from?: string
|
|
35
|
+
/** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
|
|
36
|
+
inReplyTo?: string
|
|
37
|
+
/**
|
|
38
|
+
* ISO timestamp: instead of sending now, queue the message for the DO
|
|
39
|
+
* alarm to dispatch at (or shortly after) this time.
|
|
40
|
+
*/
|
|
41
|
+
sendAt?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SendEnv extends MailEnv {
|
|
45
|
+
DEFAULT_FROM?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Send now, or queue for the DO alarm when `sendAt` is set. Validates,
|
|
50
|
+
* dispatches, records the outbound row, and emits the message.sent webhook.
|
|
51
|
+
*/
|
|
52
|
+
export async function send(env: SendEnv, store: InboxStore, body: SendBody): Promise<Outcome> {
|
|
53
|
+
if (!body.to || !body.subject || (!body.text && !body.html)) {
|
|
54
|
+
return { status: 400, body: { error: 'required: to, subject, and text or html' } }
|
|
55
|
+
}
|
|
56
|
+
const from = body.from ?? env.DEFAULT_FROM
|
|
57
|
+
if (!from) {
|
|
58
|
+
return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or pass from)' } }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Email Sending only accepts whitelisted custom headers (a Message-ID of
|
|
62
|
+
// our own is rejected), so the wire Message-ID is provider-chosen and
|
|
63
|
+
// unknown to us. We store a synthetic one for OUR send chain; recipient
|
|
64
|
+
// replies thread via the subject+participant fallback.
|
|
65
|
+
const id = newId()
|
|
66
|
+
const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
|
|
67
|
+
const inReplyTo = normalizeMsgId(body.inReplyTo)
|
|
68
|
+
const text = body.text ?? ''
|
|
69
|
+
const snippet = makeSnippet(text, body.html ?? '')
|
|
70
|
+
|
|
71
|
+
// sendAt → queue for the DO alarm instead of dispatching now.
|
|
72
|
+
if (body.sendAt !== undefined) {
|
|
73
|
+
const at = new Date(body.sendAt)
|
|
74
|
+
if (Number.isNaN(at.getTime())) {
|
|
75
|
+
return { status: 400, body: { error: 'sendAt is not a valid date' } }
|
|
76
|
+
}
|
|
77
|
+
await store.insert({
|
|
78
|
+
id,
|
|
79
|
+
status: 'scheduled',
|
|
80
|
+
scheduled_at: at.toISOString(),
|
|
81
|
+
direction: 'outbound',
|
|
82
|
+
in_reply_to: inReplyTo,
|
|
83
|
+
message_id: messageId,
|
|
84
|
+
from_addr: from,
|
|
85
|
+
to_addr: body.to,
|
|
86
|
+
subject: body.subject,
|
|
87
|
+
date: at.toISOString(),
|
|
88
|
+
snippet,
|
|
89
|
+
text_body: text,
|
|
90
|
+
html_body: body.html ?? '',
|
|
91
|
+
r2_key: '',
|
|
92
|
+
attachments_json: '[]',
|
|
93
|
+
size: text.length + (body.html?.length ?? 0),
|
|
94
|
+
})
|
|
95
|
+
return { status: 202, body: { ok: true, id, status: 'scheduled', sendAt: at.toISOString() } }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
await sendMail(env, {
|
|
100
|
+
from,
|
|
101
|
+
to: body.to,
|
|
102
|
+
subject: body.subject,
|
|
103
|
+
text: body.text,
|
|
104
|
+
html: body.html,
|
|
105
|
+
inReplyTo,
|
|
106
|
+
})
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Record the outbound message so the inbox shows both sides of a
|
|
112
|
+
// conversation. No raw MIME (we never see the provider's final wire form),
|
|
113
|
+
// so r2_key stays empty and /raw 404s for these.
|
|
114
|
+
const { threadId } = await store.insert({
|
|
115
|
+
id,
|
|
116
|
+
direction: 'outbound',
|
|
117
|
+
in_reply_to: inReplyTo,
|
|
118
|
+
message_id: messageId,
|
|
119
|
+
from_addr: from,
|
|
120
|
+
to_addr: body.to,
|
|
121
|
+
subject: body.subject,
|
|
122
|
+
date: new Date().toISOString(),
|
|
123
|
+
snippet,
|
|
124
|
+
text_body: text,
|
|
125
|
+
html_body: body.html ?? '',
|
|
126
|
+
r2_key: '',
|
|
127
|
+
attachments_json: '[]',
|
|
128
|
+
size: text.length + (body.html?.length ?? 0),
|
|
129
|
+
})
|
|
130
|
+
await emitWebhook(env, 'message.sent', {
|
|
131
|
+
id,
|
|
132
|
+
threadId,
|
|
133
|
+
from,
|
|
134
|
+
to: body.to,
|
|
135
|
+
subject: body.subject,
|
|
136
|
+
snippet,
|
|
137
|
+
direction: 'outbound',
|
|
138
|
+
})
|
|
139
|
+
return { status: 200, body: { ok: true, id, from, to: body.to, messageId, threadId } }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Send an existing draft: validate completeness, dispatch, flip to sent. */
|
|
143
|
+
export async function sendDraft(
|
|
144
|
+
env: SendEnv,
|
|
145
|
+
store: InboxStore,
|
|
146
|
+
draftId: string,
|
|
147
|
+
): Promise<Outcome> {
|
|
148
|
+
const draft = await store.get(draftId)
|
|
149
|
+
if (!draft || draft.status !== 'draft') return { status: 404, body: { error: 'not a draft' } }
|
|
150
|
+
const from = draft.from_addr || env.DEFAULT_FROM
|
|
151
|
+
if (!from) {
|
|
152
|
+
return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or the draft from)' } }
|
|
153
|
+
}
|
|
154
|
+
if (!draft.to_addr || !draft.subject || (!draft.text_body && !draft.html_body)) {
|
|
155
|
+
return { status: 400, body: { error: 'draft incomplete: needs to, subject, and text or html' } }
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
await sendMail(env, {
|
|
159
|
+
from,
|
|
160
|
+
to: draft.to_addr,
|
|
161
|
+
subject: draft.subject,
|
|
162
|
+
text: draft.text_body || undefined,
|
|
163
|
+
html: draft.html_body || undefined,
|
|
164
|
+
inReplyTo: draft.in_reply_to,
|
|
165
|
+
})
|
|
166
|
+
} catch (err) {
|
|
167
|
+
return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
|
|
168
|
+
}
|
|
169
|
+
// Persist the from that was actually used (may have come from
|
|
170
|
+
// DEFAULT_FROM), then flip the row to sent — thread resolves NOW.
|
|
171
|
+
if (from !== draft.from_addr) await store.updateDraft(draftId, { from_addr: from })
|
|
172
|
+
const sent = await store.markDraftSent(draftId, new Date().toISOString())
|
|
173
|
+
if (!sent) return { status: 500, body: { error: 'draft vanished during send' } }
|
|
174
|
+
await emitWebhook(env, 'message.sent', {
|
|
175
|
+
id: draftId,
|
|
176
|
+
threadId: sent.threadId,
|
|
177
|
+
from,
|
|
178
|
+
to: draft.to_addr,
|
|
179
|
+
subject: draft.subject,
|
|
180
|
+
snippet: draft.snippet,
|
|
181
|
+
direction: 'outbound',
|
|
182
|
+
})
|
|
183
|
+
return {
|
|
184
|
+
status: 200,
|
|
185
|
+
body: { ok: true, id: draftId, from, to: draft.to_addr, threadId: sent.threadId },
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* A draft's fields as an adapter hands them in. Every one is optional: a
|
|
191
|
+
* draft may be partial, and completeness is enforced at send time by
|
|
192
|
+
* {@link sendDraft}.
|
|
193
|
+
*/
|
|
194
|
+
export interface DraftBody {
|
|
195
|
+
to?: string
|
|
196
|
+
subject?: string
|
|
197
|
+
text?: string
|
|
198
|
+
html?: string
|
|
199
|
+
from?: string
|
|
200
|
+
/** RFC 5322 Message-ID of the message being replied to. */
|
|
201
|
+
inReplyTo?: string
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Store an outbound message without sending it. */
|
|
205
|
+
export async function createDraft(
|
|
206
|
+
env: SendEnv,
|
|
207
|
+
store: InboxStore,
|
|
208
|
+
body: DraftBody,
|
|
209
|
+
): Promise<Outcome> {
|
|
210
|
+
const id = newId()
|
|
211
|
+
const from = body.from ?? env.DEFAULT_FROM ?? ''
|
|
212
|
+
const text = body.text ?? ''
|
|
213
|
+
await store.insert({
|
|
214
|
+
id,
|
|
215
|
+
status: 'draft',
|
|
216
|
+
direction: 'outbound',
|
|
217
|
+
in_reply_to: normalizeMsgId(body.inReplyTo),
|
|
218
|
+
message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
|
|
219
|
+
from_addr: from,
|
|
220
|
+
to_addr: body.to ?? '',
|
|
221
|
+
subject: body.subject ?? '',
|
|
222
|
+
date: new Date().toISOString(),
|
|
223
|
+
snippet: makeSnippet(text, body.html ?? ''),
|
|
224
|
+
text_body: text,
|
|
225
|
+
html_body: body.html ?? '',
|
|
226
|
+
r2_key: '',
|
|
227
|
+
attachments_json: '[]',
|
|
228
|
+
size: text.length + (body.html?.length ?? 0),
|
|
229
|
+
})
|
|
230
|
+
return { status: 201, body: { ok: true, id, status: 'draft' } }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Patch an unsent draft: only the fields present change, and `snippet` is
|
|
235
|
+
* recomputed whenever either body was touched. Which rows may be patched at
|
|
236
|
+
* all is the DO's rule (`updateDraft` refuses anything but a draft), not this
|
|
237
|
+
* command's — the command only translates the adapter's field names.
|
|
238
|
+
*
|
|
239
|
+
* Known wart, carried verbatim from the two adapter copies this replaced and
|
|
240
|
+
* left alone here so the refactor stays byte-identical: the snippet is derived
|
|
241
|
+
* from the PATCH, not from the patched row. Patching only `html` on a draft
|
|
242
|
+
* that already has a `text_body` therefore writes a snippet taken from the new
|
|
243
|
+
* html while the text part — the one `makeSnippet` would have preferred, and
|
|
244
|
+
* the one that actually goes out — is unchanged. Fixing it needs the command
|
|
245
|
+
* to read the row first (an extra DO round-trip), which is a behaviour change,
|
|
246
|
+
* not a refactor. `commands.test.ts` pins the current behaviour so a fix is a
|
|
247
|
+
* deliberate edit to that test rather than a silent one.
|
|
248
|
+
*/
|
|
249
|
+
export async function updateDraft(
|
|
250
|
+
store: InboxStore,
|
|
251
|
+
id: string,
|
|
252
|
+
patch: DraftBody,
|
|
253
|
+
): Promise<Outcome> {
|
|
254
|
+
const { text, html } = patch
|
|
255
|
+
const fields: DraftFields = {
|
|
256
|
+
...(patch.from !== undefined ? { from_addr: patch.from } : {}),
|
|
257
|
+
...(patch.to !== undefined ? { to_addr: patch.to } : {}),
|
|
258
|
+
...(patch.subject !== undefined ? { subject: patch.subject } : {}),
|
|
259
|
+
...(text !== undefined ? { text_body: text } : {}),
|
|
260
|
+
...(html !== undefined ? { html_body: html } : {}),
|
|
261
|
+
...(patch.inReplyTo !== undefined ? { in_reply_to: normalizeMsgId(patch.inReplyTo) } : {}),
|
|
262
|
+
...(text !== undefined || html !== undefined
|
|
263
|
+
? { snippet: makeSnippet(text ?? '', html ?? '') }
|
|
264
|
+
: {}),
|
|
265
|
+
}
|
|
266
|
+
const updated = await store.updateDraft(id, fields)
|
|
267
|
+
return updated
|
|
268
|
+
? { status: 200, body: { ok: true, id } }
|
|
269
|
+
: { status: 404, body: { error: 'not a draft' } }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Delete a message of any status, plus its raw MIME blob.
|
|
274
|
+
*
|
|
275
|
+
* `store.delete` answers with three distinct values and all three matter:
|
|
276
|
+
* `null` (no such row), `''` (deleted, but it never had raw MIME — a draft,
|
|
277
|
+
* a scheduled row, or anything outbound) and a key (delete the R2 object
|
|
278
|
+
* too). The JSON route used to test `!r2Key`, which folded `''` into "not
|
|
279
|
+
* found" and answered 404 for a row it had just deleted; the MCP tool tested
|
|
280
|
+
* `=== null` and was right. This command takes the MCP reading.
|
|
281
|
+
*/
|
|
282
|
+
export async function deleteMessage(
|
|
283
|
+
env: { RAW: R2Bucket },
|
|
284
|
+
store: InboxStore,
|
|
285
|
+
id: string,
|
|
286
|
+
): Promise<Outcome> {
|
|
287
|
+
const r2Key = await store.delete(id)
|
|
288
|
+
if (r2Key === null) return { status: 404, body: { error: 'not found' } }
|
|
289
|
+
if (r2Key) await env.RAW.delete(r2Key)
|
|
290
|
+
return { status: 200, body: { ok: true } }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Cancel a pending scheduled send, or dismiss a failed one. Deletes the row. */
|
|
294
|
+
export async function cancelScheduled(store: InboxStore, id: string): Promise<Outcome> {
|
|
295
|
+
const cancelled = await store.cancelScheduled(id)
|
|
296
|
+
return cancelled
|
|
297
|
+
? { status: 200, body: { ok: true } }
|
|
298
|
+
: { status: 404, body: { error: 'not a scheduled send' } }
|
|
299
|
+
}
|
|
@@ -75,6 +75,57 @@ export interface InsertMessage {
|
|
|
75
75
|
scheduled_at?: string
|
|
76
76
|
}
|
|
77
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
|
+
|
|
78
129
|
/** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
|
|
79
130
|
function normalizeSubject(subject: string): string {
|
|
80
131
|
return subject
|
|
@@ -84,7 +135,7 @@ function normalizeSubject(subject: string): string {
|
|
|
84
135
|
.toLowerCase()
|
|
85
136
|
}
|
|
86
137
|
|
|
87
|
-
export class Inbox extends DurableObject<MailEnv> {
|
|
138
|
+
export class Inbox extends DurableObject<MailEnv> implements InboxStore {
|
|
88
139
|
private sql: SqlStorage
|
|
89
140
|
|
|
90
141
|
constructor(ctx: DurableObjectState, env: MailEnv) {
|
|
@@ -340,15 +391,7 @@ export class Inbox extends DurableObject<MailEnv> {
|
|
|
340
391
|
}
|
|
341
392
|
|
|
342
393
|
/** 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 {
|
|
394
|
+
updateDraft(id: string, fields: DraftFields): boolean {
|
|
352
395
|
const row = this.sql
|
|
353
396
|
.exec(`SELECT status FROM messages WHERE id = ?`, id)
|
|
354
397
|
.toArray()[0] as unknown as { status: string } | undefined
|