@zabaca/zbc 0.13.0 → 0.15.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 (48) hide show
  1. package/CHANGELOG.md +117 -6
  2. package/package.json +5 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/apply.ts +33 -9
  5. package/src/commands/destroy.ts +1 -1
  6. package/src/commands/init.ts +1 -0
  7. package/src/engine/apply.ts +110 -22
  8. package/src/engine/destroy.ts +183 -14
  9. package/src/engine/discover.ts +1 -1
  10. package/src/engine/resolve.ts +113 -14
  11. package/src/utils/copy-template.ts +10 -0
  12. package/templates/CLAUDE.md +1 -1
  13. package/templates/apps/inbox/package.json +3 -1
  14. package/templates/apps/inbox/tsconfig.json +3 -1
  15. package/templates/apps/inbox/worker/api.ts +197 -0
  16. package/templates/apps/inbox/worker/commands.ts +299 -0
  17. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  18. package/templates/apps/inbox/worker/index.ts +15 -202
  19. package/templates/apps/inbox/worker/mcp.ts +49 -100
  20. package/templates/infra/modules/cloudflare/index.ts +29 -73
  21. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  22. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  23. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  24. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  25. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  26. package/templates/infra/modules/cloudflare-token/index.ts +10 -32
  27. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  28. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  29. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  30. package/templates/infra/modules/fly/index.ts +17 -42
  31. package/templates/infra/modules/fly/registry.json +1 -1
  32. package/templates/infra/modules/host-file/index.ts +6 -7
  33. package/templates/infra/modules/provision-core/index.ts +21 -15
  34. package/templates/infra/modules/r2/index.ts +40 -71
  35. package/templates/infra/modules/r2/registry.json +1 -1
  36. package/templates/infra/modules/remote-provision/index.ts +1 -3
  37. package/templates/infra/modules/turso/index.ts +2 -15
  38. package/templates/infra/modules/vm-provision/index.ts +10 -3
  39. package/templates/infra/src/context.ts +115 -0
  40. package/templates/infra/src/define-module.ts +41 -2
  41. package/templates/infra/src/index.ts +11 -1
  42. package/templates/infra/src/types.ts +85 -3
  43. package/src/commands/add-registry.test.ts +0 -92
  44. package/src/commands/secret.test.ts +0 -717
  45. package/src/commands/vendor-mode.test.ts +0 -183
  46. package/src/infra-types.ts +0 -38
  47. package/src/utils/subtree.test.ts +0 -127
  48. package/templates/apps/inbox/worker/send-op.ts +0 -174
@@ -2,16 +2,9 @@ import { StreamableHTTPTransport } from '@hono/mcp'
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
3
3
  import { Hono } from 'hono'
4
4
  import { z } from 'zod'
5
- import type {
6
- Inbox,
7
- InsertMessage,
8
- MessageFull,
9
- MessageMeta,
10
- ScheduledMeta,
11
- ThreadMeta,
12
- } from './inbox-do'
13
- import { type SendEnv, performDraftSend, performSend } from './send-op'
14
- import { makeSnippet, newId, normalizeMsgId } from './shared'
5
+ import * as commands from './commands'
6
+ import type { SendEnv } from './commands'
7
+ import type { InboxStore } from './inbox-do'
15
8
 
16
9
  /**
17
10
  * MCP server over the inbox — the same operations as /api/*, exposed as
@@ -21,55 +14,29 @@ import { makeSnippet, newId, normalizeMsgId } from './shared'
21
14
  *
22
15
  * Auth is the SAME bearer token as /api/* — the caller checks it before
23
16
  * invoking this, and MCP clients send it as a normal Authorization header.
24
- * Tools call the Durable Object stub directly (a Worker cannot fetch its
25
- * own routes), so this file is wiring, not logic.
17
+ *
18
+ * This file is wiring, not logic: every mutation is a call into `commands.ts`
19
+ * — the same function `api.ts` calls — and every read is a single `store.*`
20
+ * call. Nothing here decides what a mutation does.
26
21
  */
27
22
 
28
23
  const text = (v: unknown) => ({
29
24
  content: [{ type: 'text' as const, text: JSON.stringify(v, null, 2) }],
30
25
  })
31
26
 
32
- /** Unwrap a SendOutcome into MCP result-or-error. */
27
+ /** Unwrap a command Outcome into MCP result-or-error. */
33
28
  const outcome = (o: { status: number; body: Record<string, unknown> }) => {
34
29
  if (o.status >= 400) throw new Error(String(o.body.error ?? `failed (${o.status})`))
35
30
  return text(o.body)
36
31
  }
37
32
 
38
- /**
39
- * The DO surface the tools use, with plain Promise returns. The raw
40
- * DurableObjectStub<Inbox> type expands workers-types' recursive RPC
41
- * serialization generics inside every registerTool inference and trips
42
- * TS2589 — this narrow view is the same calls without the type machinery.
43
- */
44
- interface InboxApi {
45
- list(
46
- limit: number,
47
- cursor?: string,
48
- label?: string,
49
- ): Promise<{ messages: MessageMeta[]; nextCursor: string | null }>
50
- listThreads(
51
- limit: number,
52
- cursor?: string,
53
- ): Promise<{ threads: ThreadMeta[]; nextCursor: string | null }>
54
- getThread(threadId: string): Promise<MessageFull[]>
55
- get(id: string): Promise<MessageFull | null>
56
- search(q: string, limit: number): Promise<MessageMeta[]>
57
- insert(msg: InsertMessage): Promise<{ threadId: string }>
58
- listDrafts(limit: number): Promise<MessageMeta[]>
59
- updateDraft(id: string, fields: Record<string, string>): Promise<boolean>
60
- listScheduled(limit: number): Promise<ScheduledMeta[]>
61
- cancelScheduled(id: string): Promise<boolean>
62
- delete(id: string): Promise<string | null>
63
- }
64
-
65
33
  interface McpDeps {
66
34
  env: SendEnv & { RAW: R2Bucket }
67
- stub: DurableObjectStub<Inbox>
35
+ store: InboxStore
68
36
  }
69
37
 
70
38
  export async function handleMcp(request: Request, deps: McpDeps): Promise<Response> {
71
- const { env } = deps
72
- const stub = deps.stub as unknown as InboxApi
39
+ const { env, store } = deps
73
40
  const server = new McpServer({ name: 'inbox', version: '1.0.0' })
74
41
 
75
42
  server.registerTool(
@@ -79,7 +46,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
79
46
  'List conversation threads, newest first. Each row is the latest message of its thread plus thread_count. Page with cursor = the last id from the previous page.',
80
47
  inputSchema: { limit: z.number().optional(), cursor: z.string().optional() },
81
48
  },
82
- async ({ limit, cursor }) => text(await stub.listThreads(limit ?? 50, cursor)),
49
+ async ({ limit, cursor }) => text(await store.listThreads(limit ?? 50, cursor)),
83
50
  )
84
51
  server.registerTool(
85
52
  'read_thread',
@@ -89,7 +56,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
89
56
  inputSchema: { thread_id: z.string() },
90
57
  },
91
58
  async ({ thread_id }) => {
92
- const messages = await stub.getThread(thread_id)
59
+ const messages = await store.getThread(thread_id)
93
60
  if (!messages.length) throw new Error('thread not found')
94
61
  return text({ messages })
95
62
  },
@@ -105,7 +72,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
105
72
  label: z.string().optional(),
106
73
  },
107
74
  },
108
- async ({ limit, cursor, label }) => text(await stub.list(limit ?? 50, cursor, label)),
75
+ async ({ limit, cursor, label }) => text(await store.list(limit ?? 50, cursor, label)),
109
76
  )
110
77
  server.registerTool(
111
78
  'read_message',
@@ -114,7 +81,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
114
81
  inputSchema: { id: z.string() },
115
82
  },
116
83
  async ({ id }) => {
117
- const msg = await stub.get(id)
84
+ const msg = await store.get(id)
118
85
  if (!msg) throw new Error('message not found')
119
86
  return text(msg)
120
87
  },
@@ -125,7 +92,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
125
92
  description: 'Keyword search over subject + text body (case-insensitive), newest first.',
126
93
  inputSchema: { q: z.string(), limit: z.number().optional() },
127
94
  },
128
- async ({ q, limit }) => text({ messages: await stub.search(q, limit ?? 50) }),
95
+ async ({ q, limit }) => text({ messages: await store.search(q, limit ?? 50) }),
129
96
  )
130
97
  server.registerTool(
131
98
  'send_email',
@@ -144,7 +111,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
144
111
  },
145
112
  async (input) =>
146
113
  outcome(
147
- await performSend(env, deps.stub, {
114
+ await commands.send(env, store, {
148
115
  to: input.to,
149
116
  subject: input.subject,
150
117
  text: input.text,
@@ -169,34 +136,22 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
169
136
  in_reply_to: z.string().optional(),
170
137
  },
171
138
  },
172
- async (input) => {
173
- const id = newId()
174
- const from = input.from ?? env.DEFAULT_FROM ?? ''
175
- const bodyText = input.text ?? ''
176
- await stub.insert({
177
- id,
178
- status: 'draft',
179
- direction: 'outbound',
180
- in_reply_to: normalizeMsgId(input.in_reply_to),
181
- message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
182
- from_addr: from,
183
- to_addr: input.to ?? '',
184
- subject: input.subject ?? '',
185
- date: new Date().toISOString(),
186
- snippet: makeSnippet(bodyText, input.html ?? ''),
187
- text_body: bodyText,
188
- html_body: input.html ?? '',
189
- r2_key: '',
190
- attachments_json: '[]',
191
- size: bodyText.length + (input.html?.length ?? 0),
192
- })
193
- return text({ ok: true, id, status: 'draft' })
194
- },
139
+ async (input) =>
140
+ outcome(
141
+ await commands.createDraft(env, store, {
142
+ to: input.to,
143
+ subject: input.subject,
144
+ text: input.text,
145
+ html: input.html,
146
+ from: input.from,
147
+ inReplyTo: input.in_reply_to,
148
+ }),
149
+ ),
195
150
  )
196
151
  server.registerTool(
197
152
  'list_drafts',
198
153
  { description: 'List unsent drafts, newest first.' },
199
- async () => text({ drafts: await stub.listDrafts(50) }),
154
+ async () => text({ drafts: await store.listDrafts(50) }),
200
155
  )
201
156
  server.registerTool(
202
157
  'update_draft',
@@ -212,23 +167,17 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
212
167
  in_reply_to: z.string().optional(),
213
168
  },
214
169
  },
215
- async ({ id, ...input }) => {
216
- const updated = await stub.updateDraft(id, {
217
- ...(input.from !== undefined ? { from_addr: input.from } : {}),
218
- ...(input.to !== undefined ? { to_addr: input.to } : {}),
219
- ...(input.subject !== undefined ? { subject: input.subject } : {}),
220
- ...(input.text !== undefined ? { text_body: input.text } : {}),
221
- ...(input.html !== undefined ? { html_body: input.html } : {}),
222
- ...(input.in_reply_to !== undefined
223
- ? { in_reply_to: normalizeMsgId(input.in_reply_to) }
224
- : {}),
225
- ...(input.text !== undefined || input.html !== undefined
226
- ? { snippet: makeSnippet(input.text ?? '', input.html ?? '') }
227
- : {}),
228
- })
229
- if (!updated) throw new Error('not a draft')
230
- return text({ ok: true, id })
231
- },
170
+ async ({ id, ...input }) =>
171
+ outcome(
172
+ await commands.updateDraft(store, id, {
173
+ to: input.to,
174
+ subject: input.subject,
175
+ text: input.text,
176
+ html: input.html,
177
+ from: input.from,
178
+ inReplyTo: input.in_reply_to,
179
+ }),
180
+ ),
232
181
  )
233
182
  server.registerTool(
234
183
  'send_draft',
@@ -236,7 +185,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
236
185
  description: 'Send an existing draft (must have to, subject, and text or html).',
237
186
  inputSchema: { id: z.string() },
238
187
  },
239
- async ({ id }) => outcome(await performDraftSend(env, deps.stub, id)),
188
+ async ({ id }) => outcome(await commands.sendDraft(env, store, id)),
240
189
  )
241
190
  server.registerTool(
242
191
  'list_scheduled',
@@ -244,7 +193,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
244
193
  description:
245
194
  'List pending scheduled sends (and failed ones, with send_error), soonest first.',
246
195
  },
247
- async () => text({ scheduled: await stub.listScheduled(50) }),
196
+ async () => text({ scheduled: await store.listScheduled(50) }),
248
197
  )
249
198
  server.registerTool(
250
199
  'cancel_scheduled',
@@ -252,10 +201,7 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
252
201
  description: 'Cancel a pending scheduled send (or dismiss a failed one). Deletes the row.',
253
202
  inputSchema: { id: z.string() },
254
203
  },
255
- async ({ id }) => {
256
- if (!(await stub.cancelScheduled(id))) throw new Error('not a scheduled send')
257
- return text({ ok: true })
258
- },
204
+ async ({ id }) => outcome(await commands.cancelScheduled(store, id)),
259
205
  )
260
206
  server.registerTool(
261
207
  'delete_message',
@@ -264,10 +210,13 @@ export async function handleMcp(request: Request, deps: McpDeps): Promise<Respon
264
210
  inputSchema: { id: z.string() },
265
211
  },
266
212
  async ({ id }) => {
267
- const r2Key = await stub.delete(id)
268
- if (r2Key === null) throw new Error('message not found')
269
- if (r2Key) await env.RAW.delete(r2Key)
270
- return text({ ok: true })
213
+ const result = await commands.deleteMessage(env, store, id)
214
+ // The one place an adapter renders a command's error in its own words:
215
+ // this tool has always said 'message not found' where the JSON route
216
+ // says 'not found', and MCP clients see the string. The command decides
217
+ // WHETHER it is a 404; the tool only spells it.
218
+ if (result.status === 404) throw new Error('message not found')
219
+ return outcome(result)
271
220
  },
272
221
  )
273
222
 
@@ -3,13 +3,14 @@ import * as fs from 'node:fs'
3
3
  import { execSync, spawnSync } from 'node:child_process'
4
4
  import { z } from 'zod'
5
5
  import { defineModule } from '../../src/define-module'
6
+ import type { ApplyContext } from '../../src/types'
6
7
 
7
8
  /**
8
9
  * cloudflare — deploys a Cloudflare Worker (optionally with static assets, a
9
10
  * Durable Object, and a Container) via `wrangler deploy`.
10
11
  *
11
12
  * This is a THIN orchestrator, the same shape as the turso module: `apply` runs
12
- * on the operator machine, reads CF creds from `ctx.secrets`, runs an optional
13
+ * on the operator machine, reads CF creds through `ctx.secret`, runs an optional
13
14
  * local build, then shells `wrangler deploy` in the package's own directory. The
14
15
  * Worker TOPOLOGY (name, assets binding, durable_objects, containers,
15
16
  * migrations) lives in that package's `wrangler.jsonc` — wrangler is the source
@@ -39,8 +40,8 @@ import { defineModule } from '../../src/define-module'
39
40
  * IMPORT SYNC: `workerSecrets` and `workerVars` entries can be either a plain
40
41
  * name (resolved from this environment's secrets.yaml, exactly as before) or a
41
42
  * `{ name, from, output }` reference into an imported instance's outputs
42
- * (`ctx.imports[from][output]`, populated by the engine from that instance's
43
- * validated outputs). Secrets are pushed via `wrangler secret put`, piped
43
+ * (`ctx.output({ from, output }, field)`, resolved by the engine from that
44
+ * instance's validated outputs). Secrets are pushed via `wrangler secret put`, piped
44
45
  * through stdin; vars are passed as `wrangler deploy --var KEY:VALUE`. The two
45
46
  * are deliberately separate fields — a var is visible in `wrangler.jsonc`/the
46
47
  * dashboard, a secret is not — so an imported value's exposure is an explicit
@@ -108,7 +109,7 @@ export function routeUrl(routes: string[]): string {
108
109
  * secrets.yaml), a `{ name, value }` literal (vars that are per-instance
109
110
  * config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
110
111
  * needs no editing), a `{ name, from, output }` reference into an imported
111
- * instance's outputs (`ctx.imports[from][output]`), or a `{ name, secret }`
112
+ * instance's outputs (`ctx.output`), or a `{ name, secret }`
112
113
  * pair that exposes a secrets.yaml key under a different env var name.
113
114
  */
114
115
  const workerValueSchema = z.union([
@@ -149,46 +150,24 @@ type WorkerValueEntry = z.infer<typeof workerValueSchema>
149
150
  /** Resolve a workerSecrets/workerVars entry to its `{ name, value }` pair. */
150
151
  function resolveWorkerValue(
151
152
  entry: WorkerValueEntry,
152
- ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
153
+ ctx: ApplyContext,
153
154
  fieldName: string,
154
155
  ): { name: string; value: string } {
155
156
  if (typeof entry === 'string') {
156
- const value = ctx.secrets[entry]
157
- if (!value) {
158
- throw new Error(
159
- `${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
160
- )
161
- }
162
- return { name: entry, value }
157
+ return { name: entry, value: ctx.secret(entry, { field: fieldName }) }
163
158
  }
164
159
 
165
160
  if ('value' in entry) {
166
161
  return { name: entry.name, value: entry.value }
167
162
  }
168
163
 
164
+ const field = `${fieldName} entry "${entry.name}"`
165
+
169
166
  if ('secret' in entry) {
170
- const value = ctx.secrets[entry.secret]
171
- if (!value) {
172
- throw new Error(
173
- `${fieldName} entry "${entry.name}" references secret "${entry.secret}", which is missing from this environment's secrets.yaml`,
174
- )
175
- }
176
- return { name: entry.name, value }
167
+ return { name: entry.name, value: ctx.secret(entry.secret, { field }) }
177
168
  }
178
169
 
179
- const instanceOutputs = ctx.imports[entry.from]
180
- if (instanceOutputs === undefined) {
181
- throw new Error(
182
- `${fieldName} entry "${entry.name}" references instance "${entry.from}", which is not in this instance's imports`,
183
- )
184
- }
185
- const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
186
- if (typeof value !== 'string') {
187
- throw new Error(
188
- `${fieldName} entry "${entry.name}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
189
- )
190
- }
191
- return { name: entry.name, value }
170
+ return { name: entry.name, value: ctx.output(entry, field) }
192
171
  }
193
172
 
194
173
  /**
@@ -220,22 +199,13 @@ type R2BindingEntry = z.infer<typeof r2BindingSchema>
220
199
 
221
200
  function resolveR2Binding(
222
201
  entry: R2BindingEntry,
223
- ctx: { imports: Record<string, unknown> },
202
+ ctx: ApplyContext,
224
203
  ): { binding: string; bucketName: string } {
225
204
  if ('bucketName' in entry) return { binding: entry.binding, bucketName: entry.bucketName }
226
- const instanceOutputs = ctx.imports[entry.from]
227
- if (instanceOutputs === undefined) {
228
- throw new Error(
229
- `r2Bindings entry "${entry.binding}" references instance "${entry.from}", which is not in this instance's imports`,
230
- )
231
- }
232
- const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
233
- if (typeof value !== 'string') {
234
- throw new Error(
235
- `r2Bindings entry "${entry.binding}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
236
- )
205
+ return {
206
+ binding: entry.binding,
207
+ bucketName: ctx.output(entry, `r2Bindings entry "${entry.binding}"`),
237
208
  }
238
- return { binding: entry.binding, bucketName: value }
239
209
  }
240
210
 
241
211
  /** Strip line and block comments from JSONC, string-aware. */
@@ -366,9 +336,10 @@ export const cloudflareModule = defineModule({
366
336
  * original behavior). Set `{ from, output }` to pull it from an imported
367
337
  * instance's outputs instead — e.g. a `cloudflare-token` instance's
368
338
  * `tokenValue` — so a minted, per-apply-rolled deploy token flows straight
369
- * to wrangler and never sits at rest. NOTE: the engine passes no imports
370
- * to `destroy`, so environments that destroy workers (ephemeral previews)
371
- * still need the secrets.yaml fallback for teardown.
339
+ * to wrangler and never sits at rest. `destroy` resolves it the same way:
340
+ * the engine applies the imported instance on demand when a teardown asks
341
+ * for its output, so an environment that destroys workers — an ephemeral
342
+ * instance, or `zbc destroy preview` — needs no secrets.yaml fallback.
372
343
  */
373
344
  apiToken: z.object({ from: z.string(), output: z.string() }).optional(),
374
345
  /** Optional local build run before deploy (e.g. `vite build` for assets). */
@@ -461,10 +432,8 @@ export const cloudflareModule = defineModule({
461
432
  // tokenValue) when `apiToken` is set, else secrets.yaml. Resolved before
462
433
  // anything runs so a bad reference fails fast.
463
434
  const apiToken = config.apiToken
464
- ? resolveWorkerValue({ name: 'CLOUDFLARE_API_TOKEN', ...config.apiToken }, ctx, 'apiToken')
465
- .value
466
- : ctx.secrets['CLOUDFLARE_API_TOKEN']
467
- if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
435
+ ? ctx.output(config.apiToken, 'apiToken')
436
+ : ctx.secret('CLOUDFLARE_API_TOKEN')
468
437
 
469
438
  const env: NodeJS.ProcessEnv = {
470
439
  ...process.env,
@@ -575,27 +544,14 @@ export const cloudflareModule = defineModule({
575
544
  return { deployUrl, workerName }
576
545
  },
577
546
  async destroy(config, ctx) {
578
- // The engine passes `imports: {}` to destroy (reverse-order teardown — the
579
- // imported instance may already be gone), so an `apiToken` reference can't
580
- // resolve here. Fall back to secrets.yaml; error only when neither exists.
581
- let apiToken: string | undefined
582
- if (config.apiToken) {
583
- try {
584
- apiToken = resolveWorkerValue(
585
- { name: 'CLOUDFLARE_API_TOKEN', ...config.apiToken },
586
- ctx,
587
- 'apiToken',
588
- ).value
589
- } catch {
590
- apiToken = undefined
591
- }
592
- }
593
- apiToken ??= ctx.secrets['CLOUDFLARE_API_TOKEN']
594
- if (!apiToken) {
595
- throw new Error(
596
- 'Missing secret: CLOUDFLARE_API_TOKEN (the apiToken import is not available at destroy — keep a CLOUDFLARE_API_TOKEN in secrets.yaml for environments that destroy workers)',
597
- )
598
- }
547
+ // Resolved exactly the way `apply` resolves it. The engine applies the
548
+ // referenced instance on demand when a destroy asks for its output, so the
549
+ // twenty lines that used to live here — a swallowed catch around the
550
+ // reference and a silent fall back to secrets.yaml, because destroy was
551
+ // handed `imports: {}` — say nothing this line does not.
552
+ const apiToken = config.apiToken
553
+ ? ctx.output(config.apiToken, 'apiToken')
554
+ : ctx.secret('CLOUDFLARE_API_TOKEN')
599
555
  const env: NodeJS.ProcessEnv = {
600
556
  ...process.env,
601
557
  CLOUDFLARE_API_TOKEN: apiToken,
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
- import { cf, resolveApiToken, resolveRef } from '../cloudflare-api'
3
+ import { cf } from '../cloudflare-api'
4
4
 
5
5
  // cloudflare-access — a Zero Trust application and the list of principals that
6
6
  // may reach it, as repo state instead of dashboard state.
@@ -814,14 +814,14 @@ export const cloudflareAccessModule = defineModule({
814
814
  changed: z.boolean(),
815
815
  }),
816
816
  async apply(config, ctx) {
817
- const token = resolveApiToken(config.apiToken, ctx.imports)
817
+ const token = ctx.output(config.apiToken, 'apiToken')
818
818
  const account = `/accounts/${config.accountId}`
819
819
  const domain = normalizeDomain(config.domain)
820
820
 
821
821
  // Resolved before anything is called, so a service token instance that is
822
822
  // not imported fails while nothing has been touched.
823
823
  const referencedTokenIds = config.serviceTokens.map((ref, index) =>
824
- resolveRef(ref, ctx.imports, `serviceTokens[${index}]`),
824
+ ctx.output(ref, `serviceTokens[${index}]`),
825
825
  )
826
826
 
827
827
  // 1. The organisation. Two fields off one endpoint, treated in OPPOSITE