@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,3 +1,7 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import * as fs from 'node:fs'
3
+ import * as os from 'node:os'
4
+ import * as path from 'node:path'
1
5
  import { z } from 'zod'
2
6
  import { defineModule } from '../../src/define-module'
3
7
  import type { ApplyContext } from '../../src/types'
@@ -17,6 +21,11 @@ import { CfError, type CfOptions, cf, cfRaw } from '../cloudflare-api'
17
21
  * 'database_id', from: '<this instance>', output: 'databaseId' }` and the
18
22
  * placeholder id in the checked-in wrangler config is never read.
19
23
  *
24
+ * Schema comes two ways, and both run here, before any importing Worker
25
+ * deploys: `migrationsDir`, a versioned history in wrangler's own format and
26
+ * ledger (`d1_migrations`), applied by `wrangler d1 migrations apply`; then
27
+ * `statements` and `additiveColumns`, end-state DDL replayed every apply.
28
+ *
20
29
  * Token scope: CLOUDFLARE_API_TOKEN needs Account → D1: Edit. Or set
21
30
  * `apiToken: { from, output }` to use an imported instance's output instead
22
31
  * (e.g. a `cloudflare-token` instance's `tokenValue`), the same way the
@@ -122,6 +131,77 @@ function isDuplicateColumn(err: unknown): boolean {
122
131
  return err instanceof CfError && /duplicate column name/i.test(err.message)
123
132
  }
124
133
 
134
+ /**
135
+ * Apply a folder of migrations with wrangler's own migrator, against the
136
+ * database by id.
137
+ *
138
+ * Wrangler finds a database's migrations folder in a wrangler config, so it is
139
+ * handed a throwaway one in a temporary directory naming only this database,
140
+ * its id and the folder. The id is given so wrangler uses it verbatim rather
141
+ * than looking the name up. The credential and account reach it through the
142
+ * environment, as they reach the `cloudflare` module's wrangler calls, and
143
+ * wrangler is the project's own (`node_modules/.bin/wrangler`) when there is
144
+ * one, else `bunx wrangler` on node: never `--bun`, which the `cloudflare`
145
+ * module's header explains.
146
+ */
147
+ function applyMigrations(opts: {
148
+ projectRoot: string
149
+ migrationsDir: string
150
+ accountId: string
151
+ apiToken: string
152
+ databaseName: string
153
+ databaseId: string
154
+ }): string {
155
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'zbc-d1-'))
156
+ const configPath = path.join(dir, 'wrangler.json')
157
+ try {
158
+ fs.writeFileSync(
159
+ configPath,
160
+ JSON.stringify({
161
+ name: 'zbc-d1-migrations',
162
+ d1_databases: [
163
+ {
164
+ binding: 'DB',
165
+ database_name: opts.databaseName,
166
+ database_id: opts.databaseId,
167
+ migrations_dir: path.resolve(opts.projectRoot, opts.migrationsDir),
168
+ },
169
+ ],
170
+ }),
171
+ )
172
+ const local = path.join(opts.projectRoot, 'node_modules', '.bin', 'wrangler')
173
+ const [cmd, pre] = fs.existsSync(local) ? [local, []] : ['bunx', ['wrangler']]
174
+ const args = [
175
+ ...pre,
176
+ 'd1',
177
+ 'migrations',
178
+ 'apply',
179
+ opts.databaseName,
180
+ '--remote',
181
+ '--config',
182
+ configPath,
183
+ ]
184
+ const res = spawnSync(cmd, args, {
185
+ cwd: opts.projectRoot,
186
+ env: {
187
+ ...process.env,
188
+ CLOUDFLARE_API_TOKEN: opts.apiToken,
189
+ CLOUDFLARE_ACCOUNT_ID: opts.accountId,
190
+ },
191
+ maxBuffer: 64 * 1024 * 1024,
192
+ })
193
+ const said = `${res.stdout?.toString() ?? ''}\n${res.stderr?.toString() ?? ''}`
194
+ if (res.status !== 0 || res.error) {
195
+ throw new Error(
196
+ `wrangler d1 migrations apply ${opts.databaseName} failed (exit ${res.status}):\n${said.trim() || res.error?.message}`,
197
+ )
198
+ }
199
+ return said
200
+ } finally {
201
+ fs.rmSync(dir, { recursive: true, force: true })
202
+ }
203
+ }
204
+
125
205
  /**
126
206
  * The credential every call below uses: an imported instance's output when
127
207
  * `apiToken` is set, else CLOUDFLARE_API_TOKEN from secrets.yaml. One helper
@@ -159,12 +239,32 @@ export const d1Module = defineModule({
159
239
  /**
160
240
  * End-state DDL, replayed in order on EVERY apply — so every statement has
161
241
  * to be idempotent on its own (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX
162
- * IF NOT EXISTS`). This is not a migration runner and keeps no ledger: it
163
- * converges a schema the same way the rest of a module converges a
164
- * resource. A versioned migrations directory needs somewhere to run after
165
- * the deploy, which the engine does not have yet.
242
+ * IF NOT EXISTS`). This keeps no ledger: it converges a schema the same
243
+ * way the rest of a module converges a resource. A history that holds
244
+ * run-once steps (a backfill, a dropped table) belongs in `migrationsDir`.
166
245
  */
167
246
  statements: z.array(z.string()).default([]),
247
+ /**
248
+ * A folder of versioned migrations (`0001_init.sql`, …), relative to the
249
+ * project root, applied with wrangler's own migrator and recorded in its
250
+ * `d1_migrations` ledger: `wrangler d1 migrations apply <name> --remote`.
251
+ *
252
+ * Wrangler's format and ledger, not a second migrator: a database that
253
+ * was migrated by hand or by a deploy script already holds that ledger,
254
+ * and a runner keeping its own would replay the whole history over it.
255
+ *
256
+ * Run on THIS instance's apply, after the database resolves and before
257
+ * `statements`, so a Worker that imports this instance deploys only after
258
+ * the schema it reads is there. A migration that fails fails the apply,
259
+ * and the Worker behind it is not deployed. Wrangler is handed a throwaway
260
+ * config naming the database by the id just resolved, so the Worker's own
261
+ * wrangler config, and whether it binds by name or by id, play no part.
262
+ *
263
+ * Needs wrangler (this module's devDependency, run from the project's
264
+ * `node_modules/.bin`; `bunx wrangler` when it is not installed there) and
265
+ * a token that may read and write D1.
266
+ */
267
+ migrationsDir: z.string().optional(),
168
268
  /**
169
269
  * Columns added to an existing table, applied after `statements`. Separate
170
270
  * from them because `ALTER TABLE … ADD COLUMN` is the one thing SQLite
@@ -183,6 +283,17 @@ export const d1Module = defineModule({
183
283
  const apiToken = apiTokenFor(config, ctx)
184
284
  const { accountId, databaseName } = config
185
285
 
286
+ // Checked before anything is called: a typo'd folder must not leave a
287
+ // freshly created, empty database behind it.
288
+ if (
289
+ config.migrationsDir !== undefined &&
290
+ !fs.existsSync(path.resolve(ctx.projectRoot, config.migrationsDir))
291
+ ) {
292
+ throw new Error(
293
+ `migrationsDir "${config.migrationsDir}" does not exist under the project root (${ctx.projectRoot})`,
294
+ )
295
+ }
296
+
186
297
  const existing = (await listDatabases(apiToken, accountId)).find((d) => d.name === databaseName)
187
298
 
188
299
  let databaseId: string
@@ -211,6 +322,24 @@ export const d1Module = defineModule({
211
322
  )
212
323
  }
213
324
 
325
+ if (config.migrationsDir !== undefined) {
326
+ const said = applyMigrations({
327
+ projectRoot: ctx.projectRoot,
328
+ migrationsDir: config.migrationsDir,
329
+ accountId,
330
+ apiToken,
331
+ databaseName,
332
+ databaseId,
333
+ })
334
+ // Wrangler's own lines about what it applied, not the whole table it draws.
335
+ const summary = said
336
+ .split('\n')
337
+ .map((line) => line.trim())
338
+ .filter((line) => /No migrations to apply|✅|Migrations to be applied|\.sql/.test(line))
339
+ .join('; ')
340
+ console.log(` Migrated from ${config.migrationsDir}: ${summary || 'done'}`)
341
+ }
342
+
214
343
  for (const statement of config.statements) {
215
344
  await query(apiToken, accountId, databaseId, statement)
216
345
  }
@@ -6,8 +6,11 @@
6
6
  "dependencies": {
7
7
  "zod": "^3.24.0"
8
8
  },
9
+ "devDependencies": {
10
+ "wrangler": "^4.0.0"
11
+ },
9
12
  "secrets": ["CLOUDFLARE_API_TOKEN"],
10
13
  "signupUrl": "https://dash.cloudflare.com/sign-up",
11
14
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
12
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }`.\n\n`statements` are replayed on every apply, so each must be idempotent (`CREATE TABLE IF NOT EXISTS`). Use `additiveColumns` for `ALTER TABLE … ADD COLUMN`, which SQLite cannot spell idempotently — an already-present column is treated as success."
15
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }`.\n\n`statements` are replayed on every apply, so each must be idempotent (`CREATE TABLE IF NOT EXISTS`). Use `additiveColumns` for `ALTER TABLE … ADD COLUMN`, which SQLite cannot spell idempotently — an already-present column is treated as success.\n\nFor a versioned history (`0001_init.sql`, …) set `migrationsDir: 'packages/app/migrations'` (relative to the project root): it is applied with `wrangler d1 migrations apply --remote` and wrangler's own `d1_migrations` ledger on this instance's apply, before `statements`, so a Worker that imports this instance deploys only after its schema is there.\n\n`destroy` deletes the database. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
13
16
  }
@@ -0,0 +1,313 @@
1
+ import { z } from 'zod'
2
+ import { defineModule } from '../../src/define-module'
3
+ import { type CfOptions, cf, cfRaw } from '../cloudflare-api'
4
+
5
+ /**
6
+ * queue: a Cloudflare Queue and the Email Sending event subscriptions that fill
7
+ * it, via the REST API (r2-style: token through ctx.secret, idempotent
8
+ * list then create, console.log progress).
9
+ *
10
+ * What it is for: Cloudflare's Email Sending publishes an event for each
11
+ * recipient of each message a domain sends (delivered, bounced, complained, …)
12
+ * to a queue the account subscribes to, one subscription per sending domain. A
13
+ * Worker that wants its delivery reports consumes that queue.
14
+ *
15
+ * The queue has to EXIST before the Worker that consumes it is deployed:
16
+ * wrangler attaches a consumer by queue name (`queues.consumers` in the
17
+ * Worker's wrangler config) and does not create the queue. So the Worker's
18
+ * instance imports this one, which is what orders the apply.
19
+ *
20
+ * The calls are the ones wrangler's own `queues create` and `queues
21
+ * subscription create` make: `POST /accounts/{id}/queues` with `queue_name`,
22
+ * and `POST /accounts/{id}/event_subscriptions/subscriptions` with a name, a
23
+ * source (`email.sending`, a zone id and a domain), a destination (the queue)
24
+ * and the event names, written as wrangler's `--events` flag takes them
25
+ * (`message.bounced`; the queue message itself carries the full
26
+ * `cf.email.sending.message.bounced`). What the API answers when it LISTS a
27
+ * subscription is typed only by wrangler's client, so `planSubscription` reads
28
+ * the source and the destination in either spelling.
29
+ *
30
+ * ── WHAT IT NEVER DOES ───────────────────────────────────────────────────
31
+ * It deletes nothing it did not make: a queue that is not named here, or a
32
+ * subscription that is not listed, is left alone. `destroy` removes the
33
+ * subscriptions this instance names on its queue and LEAVES THE QUEUE, because
34
+ * messages may be waiting in it. A subscription that already exists under the
35
+ * same name is brought to the wanted events and nothing else, and one whose
36
+ * source reads back as a different domain or zone is a hard error rather than
37
+ * an overwrite.
38
+ *
39
+ * Token scope: CLOUDFLARE_API_TOKEN needs Account → Queues: Edit. Creating an
40
+ * event subscription may ask for more on some accounts; the refusal names the
41
+ * call that was refused.
42
+ */
43
+
44
+ /** Named per-code guidance for this module's calls; see `../cloudflare-api`. */
45
+ const OPTS: CfOptions = {
46
+ hints: {
47
+ 10000:
48
+ `rejected the token (10000 Authentication error). ` +
49
+ `CLOUDFLARE_API_TOKEN is likely missing the Account → Queues: Edit scope. ` +
50
+ `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
51
+ },
52
+ }
53
+
54
+ export const subscriptionSchema = z.object({
55
+ /** The subscription's name, unique on the queue: this is how an apply finds the one it made. */
56
+ name: z.string(),
57
+ /** The zone the sending domain is in. */
58
+ zoneId: z.string(),
59
+ /** The sending domain: the zone's apex, or a verified sending subdomain. */
60
+ domain: z.string(),
61
+ /** The events, as wrangler's `--events` takes them (`message.bounced`). */
62
+ events: z.array(z.string()).min(1),
63
+ })
64
+ export type Subscription = z.infer<typeof subscriptionSchema>
65
+
66
+ /**
67
+ * A subscription as Cloudflare lists it. Wrangler's client types the source and
68
+ * the destination in snake_case (`zone_id`, `queue_id`); both spellings are read,
69
+ * and a field that is in neither is simply unknown.
70
+ */
71
+ export interface ListedSubscription {
72
+ id: string
73
+ name: string
74
+ enabled?: boolean
75
+ source?: { type?: string; zone_id?: string; zoneId?: string; domain?: string }
76
+ destination?: { type?: string; queue_id?: string; queueId?: string }
77
+ events?: string[]
78
+ }
79
+
80
+ export type SubscriptionPlan =
81
+ | { action: 'create' }
82
+ | { action: 'leave'; id: string; warn?: string }
83
+ | { action: 'update-events'; id: string; warn?: string }
84
+ | { action: 'conflict'; id: string; why: string }
85
+
86
+ const sameSet = (a: readonly string[], b: readonly string[]): boolean =>
87
+ a.length === b.length && a.toSorted().join() === b.toSorted().join()
88
+
89
+ /**
90
+ * The listed subscription that is this one: same NAME, on THIS QUEUE. One whose
91
+ * destination names another queue is somebody else's and is not looked at; one
92
+ * whose destination reads back in neither spelling is taken to be on this queue,
93
+ * since the listing was asked for this queue's subscriptions.
94
+ */
95
+ function findMine(
96
+ existing: readonly ListedSubscription[],
97
+ name: string,
98
+ queueId: string,
99
+ ): ListedSubscription | undefined {
100
+ return existing.find((s) => {
101
+ const to = s.destination?.queue_id ?? s.destination?.queueId
102
+ return s.name === name && (to === undefined || to === queueId)
103
+ })
104
+ }
105
+
106
+ /**
107
+ * What to do about one wanted subscription, given the ones listed. Pure, so the
108
+ * outcomes are a table test.
109
+ *
110
+ * A source that reads back as a DIFFERENT domain or zone, or as another source
111
+ * type, is a conflict and is never overwritten: someone changed it, or the name
112
+ * was reused, and which is right is not this module's to decide. A source that
113
+ * reads back in a shape this module cannot read (no domain, no zone) is not a
114
+ * conflict: the next apply must not be blocked by a subscription the first one
115
+ * made, over how Cloudflare spells it. It carries on as the same subscription
116
+ * and says so (`warn`).
117
+ */
118
+ export function planSubscription(
119
+ wanted: Subscription,
120
+ existing: readonly ListedSubscription[],
121
+ queueId: string,
122
+ ): SubscriptionPlan {
123
+ const found = findMine(existing, wanted.name, queueId)
124
+ if (!found) return { action: 'create' }
125
+ const zone = found.source?.zone_id ?? found.source?.zoneId
126
+ const domain = found.source?.domain
127
+ const type = found.source?.type
128
+ const readable = domain !== undefined && zone !== undefined
129
+ if (
130
+ (type !== undefined && type !== 'email.sending') ||
131
+ (readable && (zone !== wanted.zoneId || domain !== wanted.domain))
132
+ ) {
133
+ return {
134
+ action: 'conflict',
135
+ id: found.id,
136
+ why: `a subscription named "${wanted.name}" exists on another source (${type ?? '?'} ${domain ?? '?'}); not changed.`,
137
+ }
138
+ }
139
+ const warn = readable
140
+ ? undefined
141
+ : `its source reads back in a shape this module does not know (${JSON.stringify(found.source ?? null)}), so it is taken to be the one made here.`
142
+ const same = sameSet(found.events ?? [], wanted.events) && found.enabled !== false
143
+ return same
144
+ ? { action: 'leave', id: found.id, ...(warn && { warn }) }
145
+ : { action: 'update-events', id: found.id, ...(warn && { warn }) }
146
+ }
147
+
148
+ interface QueueRow {
149
+ queue_id: string
150
+ queue_name: string
151
+ }
152
+
153
+ /**
154
+ * Every row of a listing, page by page.
155
+ *
156
+ * Paginated rather than asked for in one oversized page, for the reason `d1`
157
+ * gives: a single page that "worked" on a small account is a silent wrong
158
+ * answer on a large one, and here that means a second queue created under a
159
+ * name that is already taken. A listing that reports no `result_info` is one
160
+ * page. Bounded, so a provider that never says "last page" fails rather than
161
+ * hangs.
162
+ */
163
+ async function listAll<T>(token: string, path: string): Promise<T[]> {
164
+ const all: T[] = []
165
+ const sep = path.includes('?') ? '&' : '?'
166
+ for (let page = 1; page <= 100; page++) {
167
+ const envelope = await cfRaw<T[]>(
168
+ token,
169
+ 'GET',
170
+ `${path}${sep}per_page=100&page=${page}`,
171
+ undefined,
172
+ OPTS,
173
+ )
174
+ all.push(...(envelope.result ?? []))
175
+ const info = envelope.result_info
176
+ if (!info || page >= (info.total_pages ?? 1)) return all
177
+ }
178
+ throw new Error(`Cloudflare listing ${path} did not terminate after 100 pages`)
179
+ }
180
+
181
+ async function findQueue(
182
+ token: string,
183
+ accountId: string,
184
+ queueName: string,
185
+ ): Promise<QueueRow | undefined> {
186
+ const queues = await listAll<QueueRow>(token, `/accounts/${accountId}/queues`)
187
+ return queues.find((q) => q.queue_name === queueName)
188
+ }
189
+
190
+ function listSubscriptions(
191
+ token: string,
192
+ accountId: string,
193
+ queueId: string,
194
+ ): Promise<ListedSubscription[]> {
195
+ return listAll<ListedSubscription>(
196
+ token,
197
+ `/accounts/${accountId}/event_subscriptions/subscriptions?queue_id=${encodeURIComponent(queueId)}`,
198
+ )
199
+ }
200
+
201
+ export const queueModule = defineModule({
202
+ name: 'queue',
203
+ configSchema: z.object({
204
+ /** Cloudflare account id (not a secret: it is in the dashboard URL). */
205
+ accountId: z.string(),
206
+ /** Queue name: account-scoped, and what the consuming Worker's wrangler config names. */
207
+ queueName: z.string(),
208
+ /** Email Sending event subscriptions that fill the queue, one per sending domain. */
209
+ subscriptions: z.array(subscriptionSchema).default([]),
210
+ }),
211
+ outputs: z.object({
212
+ queueName: z.string(),
213
+ queueId: z.string(),
214
+ /** The id of each declared subscription, by its name. */
215
+ subscriptionIds: z.record(z.string()),
216
+ }),
217
+ async apply(config, ctx) {
218
+ const token = ctx.secret('CLOUDFLARE_API_TOKEN')
219
+ const base = `/accounts/${config.accountId}`
220
+
221
+ let queue = await findQueue(token, config.accountId, config.queueName)
222
+ if (queue) {
223
+ console.log(` Queue "${config.queueName}" already exists`)
224
+ } else {
225
+ queue = await cf<QueueRow>(
226
+ token,
227
+ 'POST',
228
+ `${base}/queues`,
229
+ { queue_name: config.queueName },
230
+ OPTS,
231
+ )
232
+ console.log(` Created queue "${config.queueName}"`)
233
+ }
234
+
235
+ const existing =
236
+ config.subscriptions.length > 0
237
+ ? await listSubscriptions(token, config.accountId, queue.queue_id)
238
+ : []
239
+ const subscriptionIds: Record<string, string> = {}
240
+ for (const wanted of config.subscriptions) {
241
+ const plan = planSubscription(wanted, existing, queue.queue_id)
242
+ if (plan.action === 'conflict') throw new Error(`Subscription ${wanted.name}: ${plan.why}`)
243
+ if ('warn' in plan && plan.warn) console.log(` Subscription "${wanted.name}": ${plan.warn}`)
244
+ if (plan.action === 'leave') {
245
+ console.log(` Subscription "${wanted.name}" already there`)
246
+ subscriptionIds[wanted.name] = plan.id
247
+ } else if (plan.action === 'update-events') {
248
+ await cf(
249
+ token,
250
+ 'PATCH',
251
+ `${base}/event_subscriptions/subscriptions/${plan.id}`,
252
+ { enabled: true, events: wanted.events },
253
+ OPTS,
254
+ )
255
+ console.log(` Subscription "${wanted.name}": events set to ${wanted.events.join(', ')}`)
256
+ subscriptionIds[wanted.name] = plan.id
257
+ } else {
258
+ const made = await cf<{ id: string }>(
259
+ token,
260
+ 'POST',
261
+ `${base}/event_subscriptions/subscriptions`,
262
+ {
263
+ name: wanted.name,
264
+ enabled: true,
265
+ source: { type: 'email.sending', zone_id: wanted.zoneId, domain: wanted.domain },
266
+ destination: { type: 'queues.queue', queue_id: queue.queue_id },
267
+ events: wanted.events,
268
+ },
269
+ OPTS,
270
+ )
271
+ console.log(
272
+ ` Subscribed "${wanted.name}" (${wanted.domain}) to ${wanted.events.join(', ')}`,
273
+ )
274
+ subscriptionIds[wanted.name] = made.id
275
+ }
276
+ }
277
+ return { queueName: config.queueName, queueId: queue.queue_id, subscriptionIds }
278
+ },
279
+ /**
280
+ * Remove the subscriptions this instance names, on its own queue, and leave
281
+ * the queue: messages may be waiting in it, and a queue is cheap to keep.
282
+ *
283
+ * A failed delete THROWS. It is not the bucket case `r2` reports and moves
284
+ * past (a non-empty bucket is the ordinary outcome there); a subscription
285
+ * left standing keeps publishing into a queue somebody believes was torn
286
+ * down, so a destroy that reported it as done would be the lie.
287
+ */
288
+ async destroy(config, ctx) {
289
+ const token = ctx.secret('CLOUDFLARE_API_TOKEN')
290
+ const queue = await findQueue(token, config.accountId, config.queueName)
291
+ if (!queue) {
292
+ console.log(` Queue "${config.queueName}" is already gone`)
293
+ return
294
+ }
295
+ const existing =
296
+ config.subscriptions.length > 0
297
+ ? await listSubscriptions(token, config.accountId, queue.queue_id)
298
+ : []
299
+ for (const wanted of config.subscriptions) {
300
+ const found = findMine(existing, wanted.name, queue.queue_id)
301
+ if (!found) continue
302
+ await cf(
303
+ token,
304
+ 'DELETE',
305
+ `/accounts/${config.accountId}/event_subscriptions/subscriptions/${found.id}`,
306
+ undefined,
307
+ OPTS,
308
+ )
309
+ console.log(` Deleted subscription "${wanted.name}"`)
310
+ }
311
+ console.log(` Queue "${config.queueName}" left in place (it may hold messages)`)
312
+ },
313
+ })
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "queue",
3
+ "modules": ["cloudflare-api"],
4
+ "description": "Cloudflare Queue and the Email Sending event subscriptions that fill it, provisioned via the REST API. The Worker that consumes it names the queue in its wrangler config (queues.consumers).",
5
+ "files": [{ "path": "index.ts" }],
6
+ "dependencies": {
7
+ "zod": "^3.24.0"
8
+ },
9
+ "secrets": ["CLOUDFLARE_API_TOKEN"],
10
+ "signupUrl": "https://dash.cloudflare.com/sign-up",
11
+ "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
12
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Queues: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/delivery.ts\n import { queueModule } from '../../modules/queue'\n export default queueModule.instance({\n name: 'delivery',\n config: {\n accountId: '<account id>',\n queueName: 'myproject-delivery',\n subscriptions: [{ name: 'myproject-sending', zoneId: '<zone id>', domain: 'example.com', events: ['message.delivered', 'message.bounced'] }],\n },\n })\n\nThe consuming Worker declares the queue by name in its own wrangler config (`queues.consumers: [{ queue: 'myproject-delivery' }]`) and imports this instance, so the queue exists before wrangler attaches the consumer. `destroy` removes the subscriptions this instance names and leaves the queue."
13
+ }
@@ -5,5 +5,5 @@
5
5
  "files": [{ "path": "index.ts" }],
6
6
  "secrets": ["CLOUDFLARE_API_TOKEN"],
7
7
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
8
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }"
8
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }\n\n`destroy` deletes the bucket when it is empty. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
9
9
  }
@@ -98,14 +98,31 @@ export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodTy
98
98
  // present-but-empty key the engine would have to special-case.
99
99
  ...(opts.secretOutputs ? { secretOutputs: opts.secretOutputs } : {}),
100
100
  instance(instanceOpts: InstanceOptions<TConfig>): ModuleInstance<TOutputs> {
101
+ const ephemeral =
102
+ instanceOpts.ephemeral ?? legacyConfigEphemeral(opts.name, instanceOpts.config)
103
+ const retain = instanceOpts.retain === true
104
+ if (retain && ephemeral) {
105
+ throw new Error(
106
+ `Instance "${instanceOpts.name}" sets retain and ephemeral: ephemeral destroys it on ` +
107
+ `every apply, and retain says nothing may. Drop one.`,
108
+ )
109
+ }
101
110
  return {
102
111
  name: instanceOpts.name,
103
112
  moduleName: opts.name,
104
113
  config: instanceOpts.config,
105
114
  imports: instanceOpts.imports ?? [],
106
- ephemeral: instanceOpts.ephemeral ?? legacyConfigEphemeral(opts.name, instanceOpts.config),
115
+ ephemeral,
116
+ ...(retain ? { retain } : {}),
107
117
  _outputsSchema: opts.outputs,
108
- _definition: definition as ModuleDefinition<any, TOutputs>,
118
+ // A retained instance carries NO destroy, rather than a flag the
119
+ // engine has to remember to read: an engine older than `retain` then
120
+ // finds nothing to call and skips it, as it skips any module without
121
+ // one. The newer engine reads `retain` only to say why, and to refuse
122
+ // a targeted destroy rather than skip it.
123
+ _definition: (retain
124
+ ? { ...definition, destroy: undefined }
125
+ : definition) as ModuleDefinition<any, TOutputs>,
109
126
  }
110
127
  },
111
128
  }
@@ -275,6 +275,24 @@ export interface InstanceOptions<TConfig extends z.ZodType> {
275
275
  * with three different failure policies and the fourth with none at all.
276
276
  */
277
277
  ephemeral?: boolean
278
+ /**
279
+ * Never destroy this resource: `zbc destroy <env>` leaves it standing and
280
+ * says so, and `zbc destroy <env> <this instance>` is refused. For a
281
+ * resource whose loss is not a teardown but a loss of records (a database,
282
+ * the bucket of their files), on a module whose `destroy` deletes.
283
+ *
284
+ * A property of the INSTANCE, like `ephemeral`, because whether a resource
285
+ * may be torn down is the environment's decision: the same `d1` module backs
286
+ * a scratch database a preview throws away and one nobody may delete.
287
+ *
288
+ * The instance carries no `destroy` at all (`_definition.destroy` is
289
+ * removed), so an engine that predates this key skips it too, as it skips
290
+ * any module without one. Refused together with `ephemeral`, which destroys
291
+ * on every apply. To delete a retained resource, remove `retain` in a
292
+ * reviewed change first, or delete it in the provider by hand. See
293
+ * docs/adr/0019-a-retained-instance-is-never-destroyed.md in zbc.
294
+ */
295
+ retain?: boolean
278
296
  }
279
297
 
280
298
  export interface ModuleInstance<TOutputs extends z.ZodType = z.ZodType> {
@@ -284,6 +302,12 @@ export interface ModuleInstance<TOutputs extends z.ZodType = z.ZodType> {
284
302
  imports: ModuleInstance[]
285
303
  /** See `InstanceOptions.ephemeral`. Always set — the engine reads it directly. */
286
304
  ephemeral: boolean
305
+ /**
306
+ * See `InstanceOptions.retain`. Optional, unlike `ephemeral`: an instance
307
+ * built by an older `define-module.ts` has none, and absent means not
308
+ * retained, which is what that instance always was.
309
+ */
310
+ retain?: boolean
287
311
  _outputsSchema: TOutputs
288
312
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
289
313
  _definition: ModuleDefinition<any, TOutputs>
@@ -1,26 +0,0 @@
1
- {
2
- "name": "@zbc/inbox",
3
- "license": "MIT",
4
- "version": "0.0.1",
5
- "private": true,
6
- "type": "module",
7
- "scripts": {
8
- "dev": "wrangler dev",
9
- "deploy": "wrangler deploy",
10
- "typecheck": "tsc --noEmit",
11
- "test": "bun test worker"
12
- },
13
- "dependencies": {
14
- "@hono/mcp": "^0.3.1",
15
- "@modelcontextprotocol/sdk": "^1.29.0",
16
- "hono": "^4.12.30",
17
- "postal-mime": "^2.4.4",
18
- "zod": "^4.4.3"
19
- },
20
- "devDependencies": {
21
- "@cloudflare/workers-types": "^4.20250101.0",
22
- "@types/bun": "^1.3.14",
23
- "typescript": "^7.0.2",
24
- "wrangler": "^4.0.0"
25
- }
26
- }