@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.
- package/package.json +1 -1
- package/src/commands/add.ts +6 -4
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +6 -2
- package/templates/apps/inbox/public/index.html +275 -85
- package/templates/apps/inbox/registry.json +3 -3
- package/templates/apps/inbox/worker/inbox-do.ts +415 -22
- package/templates/apps/inbox/worker/index.ts +241 -69
- package/templates/apps/inbox/worker/mcp.ts +279 -0
- package/templates/apps/inbox/worker/send-op.ts +174 -0
- package/templates/apps/inbox/worker/shared.ts +117 -0
- package/templates/apps/inbox/wrangler.jsonc +17 -4
- package/templates/infra/modules/cloudflare/index.ts +214 -5
- package/templates/infra/modules/r2/index.ts +137 -0
- package/templates/infra/modules/r2/registry.json +8 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { Inbox } from './inbox-do'
|
|
2
|
+
import { type MailEnv, emitWebhook, makeSnippet, newId, normalizeMsgId, sendMail } from './shared'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The one send operation, shared by POST /api/send and the MCP send_email
|
|
6
|
+
* tool (a Worker cannot fetch its own routes, so this is a function, not a
|
|
7
|
+
* self-request). Validates, dispatches now or queues for the DO alarm
|
|
8
|
+
* (sendAt), records the outbound row, and emits the message.sent webhook.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface SendBody {
|
|
12
|
+
to: string
|
|
13
|
+
subject: string
|
|
14
|
+
text?: string
|
|
15
|
+
html?: string
|
|
16
|
+
from?: string
|
|
17
|
+
/** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
|
|
18
|
+
inReplyTo?: string
|
|
19
|
+
/**
|
|
20
|
+
* ISO timestamp: instead of sending now, queue the message for the DO
|
|
21
|
+
* alarm to dispatch at (or shortly after) this time.
|
|
22
|
+
*/
|
|
23
|
+
sendAt?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SendEnv extends MailEnv {
|
|
27
|
+
DEFAULT_FROM?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SendOutcome {
|
|
31
|
+
status: number
|
|
32
|
+
body: Record<string, unknown>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function performSend(
|
|
36
|
+
env: SendEnv,
|
|
37
|
+
stub: DurableObjectStub<Inbox>,
|
|
38
|
+
body: SendBody,
|
|
39
|
+
): Promise<SendOutcome> {
|
|
40
|
+
if (!body.to || !body.subject || (!body.text && !body.html)) {
|
|
41
|
+
return { status: 400, body: { error: 'required: to, subject, and text or html' } }
|
|
42
|
+
}
|
|
43
|
+
const from = body.from ?? env.DEFAULT_FROM
|
|
44
|
+
if (!from) {
|
|
45
|
+
return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or pass from)' } }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Email Sending only accepts whitelisted custom headers (a Message-ID of
|
|
49
|
+
// our own is rejected), so the wire Message-ID is provider-chosen and
|
|
50
|
+
// unknown to us. We store a synthetic one for OUR send chain; recipient
|
|
51
|
+
// replies thread via the subject+participant fallback.
|
|
52
|
+
const id = newId()
|
|
53
|
+
const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
|
|
54
|
+
const inReplyTo = normalizeMsgId(body.inReplyTo)
|
|
55
|
+
const text = body.text ?? ''
|
|
56
|
+
const snippet = makeSnippet(text, body.html ?? '')
|
|
57
|
+
|
|
58
|
+
// sendAt → queue for the DO alarm instead of dispatching now.
|
|
59
|
+
if (body.sendAt !== undefined) {
|
|
60
|
+
const at = new Date(body.sendAt)
|
|
61
|
+
if (Number.isNaN(at.getTime())) {
|
|
62
|
+
return { status: 400, body: { error: 'sendAt is not a valid date' } }
|
|
63
|
+
}
|
|
64
|
+
await stub.insert({
|
|
65
|
+
id,
|
|
66
|
+
status: 'scheduled',
|
|
67
|
+
scheduled_at: at.toISOString(),
|
|
68
|
+
direction: 'outbound',
|
|
69
|
+
in_reply_to: inReplyTo,
|
|
70
|
+
message_id: messageId,
|
|
71
|
+
from_addr: from,
|
|
72
|
+
to_addr: body.to,
|
|
73
|
+
subject: body.subject,
|
|
74
|
+
date: at.toISOString(),
|
|
75
|
+
snippet,
|
|
76
|
+
text_body: text,
|
|
77
|
+
html_body: body.html ?? '',
|
|
78
|
+
r2_key: '',
|
|
79
|
+
attachments_json: '[]',
|
|
80
|
+
size: text.length + (body.html?.length ?? 0),
|
|
81
|
+
})
|
|
82
|
+
return { status: 202, body: { ok: true, id, status: 'scheduled', sendAt: at.toISOString() } }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
await sendMail(env, {
|
|
87
|
+
from,
|
|
88
|
+
to: body.to,
|
|
89
|
+
subject: body.subject,
|
|
90
|
+
text: body.text,
|
|
91
|
+
html: body.html,
|
|
92
|
+
inReplyTo,
|
|
93
|
+
})
|
|
94
|
+
} catch (err) {
|
|
95
|
+
return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Record the outbound message so the inbox shows both sides of a
|
|
99
|
+
// conversation. No raw MIME (we never see the provider's final wire form),
|
|
100
|
+
// so r2_key stays empty and /raw 404s for these.
|
|
101
|
+
const { threadId } = await stub.insert({
|
|
102
|
+
id,
|
|
103
|
+
direction: 'outbound',
|
|
104
|
+
in_reply_to: inReplyTo,
|
|
105
|
+
message_id: messageId,
|
|
106
|
+
from_addr: from,
|
|
107
|
+
to_addr: body.to,
|
|
108
|
+
subject: body.subject,
|
|
109
|
+
date: new Date().toISOString(),
|
|
110
|
+
snippet,
|
|
111
|
+
text_body: text,
|
|
112
|
+
html_body: body.html ?? '',
|
|
113
|
+
r2_key: '',
|
|
114
|
+
attachments_json: '[]',
|
|
115
|
+
size: text.length + (body.html?.length ?? 0),
|
|
116
|
+
})
|
|
117
|
+
await emitWebhook(env, 'message.sent', {
|
|
118
|
+
id,
|
|
119
|
+
threadId,
|
|
120
|
+
from,
|
|
121
|
+
to: body.to,
|
|
122
|
+
subject: body.subject,
|
|
123
|
+
snippet,
|
|
124
|
+
direction: 'outbound',
|
|
125
|
+
})
|
|
126
|
+
return { status: 200, body: { ok: true, id, from, to: body.to, messageId, threadId } }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Send an existing draft: validate completeness, dispatch, flip to sent. */
|
|
130
|
+
export async function performDraftSend(
|
|
131
|
+
env: SendEnv,
|
|
132
|
+
stub: DurableObjectStub<Inbox>,
|
|
133
|
+
draftId: string,
|
|
134
|
+
): Promise<SendOutcome> {
|
|
135
|
+
const draft = await stub.get(draftId)
|
|
136
|
+
if (!draft || draft.status !== 'draft') return { status: 404, body: { error: 'not a draft' } }
|
|
137
|
+
const from = draft.from_addr || env.DEFAULT_FROM
|
|
138
|
+
if (!from) {
|
|
139
|
+
return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or the draft from)' } }
|
|
140
|
+
}
|
|
141
|
+
if (!draft.to_addr || !draft.subject || (!draft.text_body && !draft.html_body)) {
|
|
142
|
+
return { status: 400, body: { error: 'draft incomplete: needs to, subject, and text or html' } }
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
await sendMail(env, {
|
|
146
|
+
from,
|
|
147
|
+
to: draft.to_addr,
|
|
148
|
+
subject: draft.subject,
|
|
149
|
+
text: draft.text_body || undefined,
|
|
150
|
+
html: draft.html_body || undefined,
|
|
151
|
+
inReplyTo: draft.in_reply_to,
|
|
152
|
+
})
|
|
153
|
+
} catch (err) {
|
|
154
|
+
return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
|
|
155
|
+
}
|
|
156
|
+
// Persist the from that was actually used (may have come from
|
|
157
|
+
// DEFAULT_FROM), then flip the row to sent — thread resolves NOW.
|
|
158
|
+
if (from !== draft.from_addr) await stub.updateDraft(draftId, { from_addr: from })
|
|
159
|
+
const sent = await stub.markDraftSent(draftId, new Date().toISOString())
|
|
160
|
+
if (!sent) return { status: 500, body: { error: 'draft vanished during send' } }
|
|
161
|
+
await emitWebhook(env, 'message.sent', {
|
|
162
|
+
id: draftId,
|
|
163
|
+
threadId: sent.threadId,
|
|
164
|
+
from,
|
|
165
|
+
to: draft.to_addr,
|
|
166
|
+
subject: draft.subject,
|
|
167
|
+
snippet: draft.snippet,
|
|
168
|
+
direction: 'outbound',
|
|
169
|
+
})
|
|
170
|
+
return {
|
|
171
|
+
status: 200,
|
|
172
|
+
body: { ok: true, id: draftId, from, to: draft.to_addr, threadId: sent.threadId },
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers shared by the Worker entry (index.ts) and the Inbox Durable Object
|
|
3
|
+
* (inbox-do.ts — its alarm() dispatches scheduled sends). Lives apart from
|
|
4
|
+
* both to avoid an import cycle.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Email Service send binding (the NEW object-based API, not the legacy
|
|
9
|
+
* EmailMessage one). The legacy `new EmailMessage(from, to, raw)` path routes
|
|
10
|
+
* through Email Routing and only delivers to VERIFIED destination addresses;
|
|
11
|
+
* the object form goes through Email Sending and accepts any recipient as
|
|
12
|
+
* long as the From domain is onboarded.
|
|
13
|
+
*/
|
|
14
|
+
export interface SendEmailBinding {
|
|
15
|
+
send(message: {
|
|
16
|
+
from: string
|
|
17
|
+
to: string
|
|
18
|
+
subject: string
|
|
19
|
+
text?: string
|
|
20
|
+
html?: string
|
|
21
|
+
headers?: Record<string, string>
|
|
22
|
+
}): Promise<unknown>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The env slice mail dispatch + webhooks need (subset of the worker Env). */
|
|
26
|
+
export interface MailEnv {
|
|
27
|
+
EMAIL: SendEmailBinding
|
|
28
|
+
WEBHOOK_URL?: string
|
|
29
|
+
WEBHOOK_SECRET?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Time-ordered id: ms timestamp (base36, padded) + random suffix. Sortable as TEXT. */
|
|
33
|
+
export function newId(): string {
|
|
34
|
+
const time = Date.now().toString(36).padStart(9, '0')
|
|
35
|
+
const rand = crypto.getRandomValues(new Uint8Array(8))
|
|
36
|
+
const suffix = Array.from(rand, (b) => b.toString(36).padStart(2, '0'))
|
|
37
|
+
.join('')
|
|
38
|
+
.slice(0, 12)
|
|
39
|
+
return `${time}-${suffix}`
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Normalize an RFC 5322 Message-ID to its bare form (no angle brackets or
|
|
44
|
+
* whitespace) so stored ids and In-Reply-To references compare equal.
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeMsgId(id: string | undefined | null): string {
|
|
47
|
+
return (id ?? '').replace(/[\s<>]/g, '')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** First 200 chars of the text (or tag-stripped html) body. */
|
|
51
|
+
export function makeSnippet(text: string, html: string): string {
|
|
52
|
+
return (text || html.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim().slice(0, 200)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Dispatch via the Email Sending binding. In-Reply-To/References are the only
|
|
57
|
+
* threading headers Cloudflare accepts (a custom Message-ID is rejected).
|
|
58
|
+
*/
|
|
59
|
+
export async function sendMail(
|
|
60
|
+
env: MailEnv,
|
|
61
|
+
msg: {
|
|
62
|
+
from: string
|
|
63
|
+
to: string
|
|
64
|
+
subject: string
|
|
65
|
+
text?: string
|
|
66
|
+
html?: string
|
|
67
|
+
inReplyTo?: string
|
|
68
|
+
},
|
|
69
|
+
): Promise<void> {
|
|
70
|
+
const inReplyTo = normalizeMsgId(msg.inReplyTo)
|
|
71
|
+
await env.EMAIL.send({
|
|
72
|
+
from: msg.from,
|
|
73
|
+
to: msg.to,
|
|
74
|
+
subject: msg.subject,
|
|
75
|
+
...(msg.text ? { text: msg.text } : {}),
|
|
76
|
+
...(msg.html ? { html: msg.html } : {}),
|
|
77
|
+
...(inReplyTo
|
|
78
|
+
? { headers: { 'In-Reply-To': `<${inReplyTo}>`, References: `<${inReplyTo}>` } }
|
|
79
|
+
: {}),
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* POST an event to WEBHOOK_URL (if configured): fire-and-forget with one
|
|
85
|
+
* retry — callers run it inside ctx.waitUntil so it never delays mail
|
|
86
|
+
* handling. Body is `{ event, message }`; signed when WEBHOOK_SECRET is set.
|
|
87
|
+
*/
|
|
88
|
+
export async function emitWebhook(
|
|
89
|
+
env: MailEnv,
|
|
90
|
+
event: 'message.received' | 'message.sent',
|
|
91
|
+
message: Record<string, unknown>,
|
|
92
|
+
): Promise<void> {
|
|
93
|
+
if (!env.WEBHOOK_URL) return
|
|
94
|
+
const body = JSON.stringify({ event, message })
|
|
95
|
+
const headers: Record<string, string> = { 'content-type': 'application/json' }
|
|
96
|
+
if (env.WEBHOOK_SECRET) {
|
|
97
|
+
const key = await crypto.subtle.importKey(
|
|
98
|
+
'raw',
|
|
99
|
+
new TextEncoder().encode(env.WEBHOOK_SECRET),
|
|
100
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
101
|
+
false,
|
|
102
|
+
['sign'],
|
|
103
|
+
)
|
|
104
|
+
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(body))
|
|
105
|
+
headers['x-inbox-signature'] =
|
|
106
|
+
`sha256=${Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, '0')).join('')}`
|
|
107
|
+
}
|
|
108
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
109
|
+
try {
|
|
110
|
+
const res = await fetch(env.WEBHOOK_URL, { method: 'POST', headers, body })
|
|
111
|
+
if (res.ok) return
|
|
112
|
+
} catch {
|
|
113
|
+
// fall through to retry
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
console.warn(`webhook delivery failed after 2 attempts: ${event}`)
|
|
117
|
+
}
|
|
@@ -7,7 +7,12 @@
|
|
|
7
7
|
// minimal static web UI. Outbound mail goes through the send_email binding
|
|
8
8
|
// (Cloudflare Email Sending — the cloudflare-email module onboards the
|
|
9
9
|
// domain).
|
|
10
|
-
|
|
10
|
+
// Generic defaults below (name, bucket_name, DEFAULT_FROM) — the per-project
|
|
11
|
+
// values live in the zbc instance file instead of here: the cloudflare
|
|
12
|
+
// module's `workerName` overrides the worker name, `r2Bindings` overrides
|
|
13
|
+
// the bucket, and a `workerVars` literal sets DEFAULT_FROM. That keeps this
|
|
14
|
+
// file identical across projects.
|
|
15
|
+
"name": "inbox",
|
|
11
16
|
"main": "worker/index.ts",
|
|
12
17
|
// Must be recent enough for the Email Service object-form EMAIL.send();
|
|
13
18
|
// older dates fall back to legacy Email Routing semantics (verified
|
|
@@ -23,13 +28,21 @@
|
|
|
23
28
|
"bindings": [{ "name": "INBOX", "class_name": "Inbox" }]
|
|
24
29
|
},
|
|
25
30
|
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Inbox"] }],
|
|
26
|
-
"r2_buckets": [{ "binding": "RAW", "bucket_name": "
|
|
31
|
+
"r2_buckets": [{ "binding": "RAW", "bucket_name": "inbox-raw" }],
|
|
27
32
|
// Unrestricted destination: once your domain is onboarded for Email Sending,
|
|
28
33
|
// the worker may send to arbitrary recipients.
|
|
29
34
|
"send_email": [{ "name": "EMAIL" }],
|
|
30
35
|
"vars": {
|
|
31
36
|
// Default From when /api/send omits one. Must be on your onboarded email
|
|
32
|
-
// domain
|
|
33
|
-
|
|
37
|
+
// domain. Set it per project via the instance file:
|
|
38
|
+
// workerVars: [{ name: 'DEFAULT_FROM', value: 'inbox@mail.example.com' }]
|
|
39
|
+
"DEFAULT_FROM": "",
|
|
40
|
+
// Optional webhook: every received/sent message POSTs { event, message }
|
|
41
|
+
// here (signed with the WEBHOOK_SECRET worker secret when set).
|
|
42
|
+
"WEBHOOK_URL": "",
|
|
43
|
+
// Optional inbound labeling: comma-separated label set (e.g.
|
|
44
|
+
// "billing,support,spam,other"). Requires the ANTHROPIC_API_KEY worker
|
|
45
|
+
// secret; leave empty to disable.
|
|
46
|
+
"LABELS": ""
|
|
34
47
|
}
|
|
35
48
|
}
|
|
@@ -87,12 +87,20 @@ const buildSchema = z.object({
|
|
|
87
87
|
})
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
* A worker secret/var entry:
|
|
91
|
-
*
|
|
92
|
-
*
|
|
90
|
+
* A worker secret/var entry: a plain name (resolved from this environment's
|
|
91
|
+
* secrets.yaml), a `{ name, value }` literal (vars that are per-instance
|
|
92
|
+
* config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
|
|
93
|
+
* needs no editing), or a `{ name, from, output }` reference into an imported
|
|
94
|
+
* instance's outputs (`ctx.imports[from][output]`).
|
|
93
95
|
*/
|
|
94
96
|
const workerValueSchema = z.union([
|
|
95
97
|
z.string(),
|
|
98
|
+
z.object({
|
|
99
|
+
/** Env var name inside the Worker. */
|
|
100
|
+
name: z.string(),
|
|
101
|
+
/** Literal value, straight from this instance's config file. */
|
|
102
|
+
value: z.string(),
|
|
103
|
+
}),
|
|
96
104
|
z.object({
|
|
97
105
|
/** Env var name inside the Worker. */
|
|
98
106
|
name: z.string(),
|
|
@@ -121,6 +129,10 @@ function resolveWorkerValue(
|
|
|
121
129
|
return { name: entry, value }
|
|
122
130
|
}
|
|
123
131
|
|
|
132
|
+
if ('value' in entry) {
|
|
133
|
+
return { name: entry.name, value: entry.value }
|
|
134
|
+
}
|
|
135
|
+
|
|
124
136
|
const instanceOutputs = ctx.imports[entry.from]
|
|
125
137
|
if (instanceOutputs === undefined) {
|
|
126
138
|
throw new Error(
|
|
@@ -136,6 +148,165 @@ function resolveWorkerValue(
|
|
|
136
148
|
return { name: entry.name, value }
|
|
137
149
|
}
|
|
138
150
|
|
|
151
|
+
/**
|
|
152
|
+
* An R2 binding override: which bucket the named `r2_buckets` binding in the
|
|
153
|
+
* package's wrangler config should attach to. Either a literal bucket name or
|
|
154
|
+
* a `{ from, output }` reference into an imported instance's outputs (the r2
|
|
155
|
+
* module emits `bucketName`). Wrangler has no CLI flag for this, so the module
|
|
156
|
+
* patches a generated copy of the wrangler config and deploys with --config —
|
|
157
|
+
* which is what lets a scaffolded package's wrangler.jsonc stay generic while
|
|
158
|
+
* the per-project bucket name lives in the instance file.
|
|
159
|
+
*/
|
|
160
|
+
const r2BindingSchema = z.union([
|
|
161
|
+
z.object({
|
|
162
|
+
/** Binding name inside the Worker (the `binding` field in r2_buckets). */
|
|
163
|
+
binding: z.string(),
|
|
164
|
+
/** Literal bucket name. */
|
|
165
|
+
bucketName: z.string(),
|
|
166
|
+
}),
|
|
167
|
+
z.object({
|
|
168
|
+
binding: z.string(),
|
|
169
|
+
/** Instance name — must be listed in this instance's `imports`. */
|
|
170
|
+
from: z.string(),
|
|
171
|
+
/** Which output of that instance holds the bucket name. */
|
|
172
|
+
output: z.string(),
|
|
173
|
+
}),
|
|
174
|
+
])
|
|
175
|
+
|
|
176
|
+
type R2BindingEntry = z.infer<typeof r2BindingSchema>
|
|
177
|
+
|
|
178
|
+
function resolveR2Binding(
|
|
179
|
+
entry: R2BindingEntry,
|
|
180
|
+
ctx: { imports: Record<string, unknown> },
|
|
181
|
+
): { binding: string; bucketName: string } {
|
|
182
|
+
if ('bucketName' in entry) return { binding: entry.binding, bucketName: entry.bucketName }
|
|
183
|
+
const instanceOutputs = ctx.imports[entry.from]
|
|
184
|
+
if (instanceOutputs === undefined) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
`r2Bindings entry "${entry.binding}" references instance "${entry.from}", which is not in this instance's imports`,
|
|
187
|
+
)
|
|
188
|
+
}
|
|
189
|
+
const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
|
|
190
|
+
if (typeof value !== 'string') {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`r2Bindings entry "${entry.binding}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
return { binding: entry.binding, bucketName: value }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Strip line and block comments from JSONC, string-aware. */
|
|
199
|
+
function stripJsoncComments(src: string): string {
|
|
200
|
+
let out = ''
|
|
201
|
+
let i = 0
|
|
202
|
+
let inStr = false
|
|
203
|
+
while (i < src.length) {
|
|
204
|
+
const c = src[i]!
|
|
205
|
+
if (inStr) {
|
|
206
|
+
out += c
|
|
207
|
+
if (c === '\\') {
|
|
208
|
+
out += src[i + 1] ?? ''
|
|
209
|
+
i += 2
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
if (c === '"') inStr = false
|
|
213
|
+
i++
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
if (c === '"') {
|
|
217
|
+
inStr = true
|
|
218
|
+
out += c
|
|
219
|
+
i++
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
if (c === '/' && src[i + 1] === '/') {
|
|
223
|
+
while (i < src.length && src[i] !== '\n') i++
|
|
224
|
+
continue
|
|
225
|
+
}
|
|
226
|
+
if (c === '/' && src[i + 1] === '*') {
|
|
227
|
+
i += 2
|
|
228
|
+
while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) i++
|
|
229
|
+
i += 2
|
|
230
|
+
continue
|
|
231
|
+
}
|
|
232
|
+
out += c
|
|
233
|
+
i++
|
|
234
|
+
}
|
|
235
|
+
return out
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Remove trailing commas (`,}` / `,]`), string-aware — JSONC allows them. */
|
|
239
|
+
function stripTrailingCommas(src: string): string {
|
|
240
|
+
let out = ''
|
|
241
|
+
let inStr = false
|
|
242
|
+
for (let i = 0; i < src.length; i++) {
|
|
243
|
+
const c = src[i]!
|
|
244
|
+
if (inStr) {
|
|
245
|
+
out += c
|
|
246
|
+
if (c === '\\') {
|
|
247
|
+
out += src[i + 1] ?? ''
|
|
248
|
+
i++
|
|
249
|
+
continue
|
|
250
|
+
}
|
|
251
|
+
if (c === '"') inStr = false
|
|
252
|
+
continue
|
|
253
|
+
}
|
|
254
|
+
if (c === '"') {
|
|
255
|
+
inStr = true
|
|
256
|
+
out += c
|
|
257
|
+
continue
|
|
258
|
+
}
|
|
259
|
+
if (c === ',') {
|
|
260
|
+
let j = i + 1
|
|
261
|
+
while (j < src.length && /\s/.test(src[j]!)) j++
|
|
262
|
+
if (src[j] === '}' || src[j] === ']') continue
|
|
263
|
+
}
|
|
264
|
+
out += c
|
|
265
|
+
}
|
|
266
|
+
return out
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
interface WranglerR2Entry {
|
|
270
|
+
binding: string
|
|
271
|
+
bucket_name?: string
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Rewrite `bucket_name` for each resolved r2Bindings entry, in the top-level
|
|
276
|
+
* `r2_buckets` and (when `wranglerEnv` is set) the matching `env.<name>` block.
|
|
277
|
+
* A binding with no matching r2_buckets entry is a hard config error.
|
|
278
|
+
*/
|
|
279
|
+
function patchR2Buckets(
|
|
280
|
+
config: Record<string, unknown>,
|
|
281
|
+
resolved: Array<{ binding: string; bucketName: string }>,
|
|
282
|
+
wranglerEnv?: string,
|
|
283
|
+
): void {
|
|
284
|
+
const blocks: Array<Record<string, unknown>> = [config]
|
|
285
|
+
if (wranglerEnv) {
|
|
286
|
+
const envBlock = (config.env as Record<string, Record<string, unknown>> | undefined)?.[
|
|
287
|
+
wranglerEnv
|
|
288
|
+
]
|
|
289
|
+
if (envBlock) blocks.push(envBlock)
|
|
290
|
+
}
|
|
291
|
+
for (const { binding, bucketName } of resolved) {
|
|
292
|
+
let found = false
|
|
293
|
+
for (const block of blocks) {
|
|
294
|
+
const entry = (block.r2_buckets as WranglerR2Entry[] | undefined)?.find(
|
|
295
|
+
(b) => b.binding === binding,
|
|
296
|
+
)
|
|
297
|
+
if (entry) {
|
|
298
|
+
entry.bucket_name = bucketName
|
|
299
|
+
found = true
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!found) {
|
|
303
|
+
throw new Error(
|
|
304
|
+
`r2Bindings entry "${binding}" has no matching r2_buckets binding in the package's wrangler config`,
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
139
310
|
export const cloudflareModule = defineModule({
|
|
140
311
|
name: 'cloudflare',
|
|
141
312
|
configSchema: z.object({
|
|
@@ -164,6 +335,14 @@ export const cloudflareModule = defineModule({
|
|
|
164
335
|
* route sensitive values through this field.
|
|
165
336
|
*/
|
|
166
337
|
workerVars: z.array(workerValueSchema).default([]),
|
|
338
|
+
/**
|
|
339
|
+
* Override which R2 bucket each named `r2_buckets` binding attaches to.
|
|
340
|
+
* Entries are `{ binding, bucketName }` literals or `{ binding, from,
|
|
341
|
+
* output }` references into an imported instance's outputs (the r2 module
|
|
342
|
+
* emits `bucketName`). Lets the package's wrangler config stay generic —
|
|
343
|
+
* the per-project bucket lives here, next to the other identifiers.
|
|
344
|
+
*/
|
|
345
|
+
r2Bindings: z.array(r2BindingSchema).default([]),
|
|
167
346
|
/**
|
|
168
347
|
* For container-backed Workers: roll the running container to the new image
|
|
169
348
|
* IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
|
|
@@ -235,20 +414,50 @@ export const cloudflareModule = defineModule({
|
|
|
235
414
|
const resolvedSecrets = config.workerSecrets.map((entry) =>
|
|
236
415
|
resolveWorkerValue(entry, ctx, 'workerSecrets'),
|
|
237
416
|
)
|
|
417
|
+
const resolvedR2 = config.r2Bindings.map((entry) => resolveR2Binding(entry, ctx))
|
|
418
|
+
|
|
419
|
+
// 2b. r2Bindings: wrangler has no CLI flag for bucket overrides, so patch
|
|
420
|
+
// a generated copy of the package's wrangler config and deploy with
|
|
421
|
+
// --config. Written next to the original so relative paths (main,
|
|
422
|
+
// assets dir) still resolve; comments don't survive the round-trip,
|
|
423
|
+
// but the file is throwaway (deleted after deploy).
|
|
424
|
+
let generatedConfig: string | undefined
|
|
425
|
+
if (resolvedR2.length > 0) {
|
|
426
|
+
const configPath = ['wrangler.jsonc', 'wrangler.json']
|
|
427
|
+
.map((f) => path.join(workdir, f))
|
|
428
|
+
.find((f) => fs.existsSync(f))
|
|
429
|
+
if (!configPath) {
|
|
430
|
+
throw new Error(
|
|
431
|
+
`r2Bindings requires a wrangler.jsonc/wrangler.json in ${config.workdir} (wrangler.toml is not supported)`,
|
|
432
|
+
)
|
|
433
|
+
}
|
|
434
|
+
const parsed = JSON.parse(
|
|
435
|
+
stripTrailingCommas(stripJsoncComments(fs.readFileSync(configPath, 'utf8'))),
|
|
436
|
+
) as Record<string, unknown>
|
|
437
|
+
patchR2Buckets(parsed, resolvedR2, config.wranglerEnv)
|
|
438
|
+
generatedConfig = path.join(workdir, 'wrangler.zbc-generated.json')
|
|
439
|
+
fs.writeFileSync(generatedConfig, JSON.stringify(parsed, null, 2))
|
|
440
|
+
}
|
|
238
441
|
|
|
239
442
|
// 3. Deploy. Creates/updates the Worker script (+ assets, DO, container).
|
|
240
443
|
// --env selects the named wrangler environment (e.g. preview) so it ships
|
|
241
444
|
// a distinct worker from the same package; --name overrides the worker
|
|
242
445
|
// name (per-PR preview workers); both omitted = the package's default.
|
|
243
446
|
const deployArgs = ['deploy']
|
|
447
|
+
if (generatedConfig) deployArgs.push('--config', generatedConfig)
|
|
244
448
|
if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
|
|
245
449
|
if (config.workerName) deployArgs.push('--name', config.workerName)
|
|
246
450
|
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
247
451
|
for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
|
|
248
452
|
console.log(
|
|
249
|
-
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}`,
|
|
453
|
+
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
|
|
250
454
|
)
|
|
251
|
-
|
|
455
|
+
let out: string
|
|
456
|
+
try {
|
|
457
|
+
out = wrangler(workdir, deployArgs, env)
|
|
458
|
+
} finally {
|
|
459
|
+
if (generatedConfig) fs.rmSync(generatedConfig, { force: true })
|
|
460
|
+
}
|
|
252
461
|
// Success theater guard: wrangler can exit 0 without actually deploying
|
|
253
462
|
// (the --bun incident above). Require the deploy confirmation line — and
|
|
254
463
|
// capture the deployed script name from it for the workerName output.
|