@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
|
@@ -3,12 +3,13 @@ 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 { resolveOutput, resolveSecret } from '../../src/context'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* fly — deploys a package to Fly.io via `fly deploy`.
|
|
9
10
|
*
|
|
10
11
|
* Same shape as the `cloudflare` module: a THIN orchestrator. `apply` runs on
|
|
11
|
-
* the operator machine, reads the Fly credential
|
|
12
|
+
* the operator machine, reads the Fly credential through `ctx.secret`, runs an
|
|
12
13
|
* optional local build, then shells `fly deploy` in the package's own
|
|
13
14
|
* directory. The app TOPOLOGY (processes, services, ports, handlers, VM size,
|
|
14
15
|
* regions, autostop/autostart) lives in that package's `fly.toml` — Fly is the
|
|
@@ -77,50 +78,34 @@ const flyValueSchema = z.union([
|
|
|
77
78
|
|
|
78
79
|
type FlyValueEntry = z.infer<typeof flyValueSchema>
|
|
79
80
|
|
|
80
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* Resolve a flySecrets entry to its `{ name, value }` pair.
|
|
83
|
+
*
|
|
84
|
+
* Takes the two raw fields rather than an `ApplyContext` — a full context is
|
|
85
|
+
* structurally one of these, and it keeps the helper callable with a literal.
|
|
86
|
+
* `resolveSecret`/`resolveOutput` are the same implementations `ctx.secret` and
|
|
87
|
+
* `ctx.output` are built from, so the failures read identically either way.
|
|
88
|
+
*/
|
|
81
89
|
export function resolveFlyValue(
|
|
82
90
|
entry: FlyValueEntry,
|
|
83
91
|
ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
|
|
84
92
|
fieldName: string,
|
|
85
93
|
): { name: string; value: string } {
|
|
86
94
|
if (typeof entry === 'string') {
|
|
87
|
-
|
|
88
|
-
if (!value) {
|
|
89
|
-
throw new Error(
|
|
90
|
-
`${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
|
|
91
|
-
)
|
|
92
|
-
}
|
|
93
|
-
return { name: entry, value }
|
|
95
|
+
return { name: entry, value: resolveSecret(ctx.secrets, entry, { field: fieldName }) }
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
if ('value' in entry) {
|
|
97
99
|
return { name: entry.name, value: entry.value }
|
|
98
100
|
}
|
|
99
101
|
|
|
102
|
+
const field = `${fieldName} entry "${entry.name}"`
|
|
103
|
+
|
|
100
104
|
if ('secret' in entry) {
|
|
101
|
-
|
|
102
|
-
if (!value) {
|
|
103
|
-
throw new Error(
|
|
104
|
-
`${fieldName} entry "${entry.name}" reads secret "${entry.secret}", ` +
|
|
105
|
-
"which is missing from this environment's secrets.yaml",
|
|
106
|
-
)
|
|
107
|
-
}
|
|
108
|
-
return { name: entry.name, value }
|
|
105
|
+
return { name: entry.name, value: resolveSecret(ctx.secrets, entry.secret, { field }) }
|
|
109
106
|
}
|
|
110
107
|
|
|
111
|
-
|
|
112
|
-
if (!instanceOutputs) {
|
|
113
|
-
throw new Error(
|
|
114
|
-
`${fieldName} entry "${entry.name}" reads from instance "${entry.from}", which is not in this instance's imports`,
|
|
115
|
-
)
|
|
116
|
-
}
|
|
117
|
-
const value = (instanceOutputs as Record<string, unknown>)[entry.output]
|
|
118
|
-
if (value === undefined) {
|
|
119
|
-
throw new Error(
|
|
120
|
-
`${fieldName} entry "${entry.name}" reads output "${entry.output}" from instance "${entry.from}", which does not emit it`,
|
|
121
|
-
)
|
|
122
|
-
}
|
|
123
|
-
return { name: entry.name, value: String(value) }
|
|
108
|
+
return { name: entry.name, value: resolveOutput(entry, ctx.imports, field) }
|
|
124
109
|
}
|
|
125
110
|
|
|
126
111
|
/** Run flyctl, capturing BOTH streams — flyctl splits human output across them,
|
|
@@ -299,8 +284,7 @@ export const flyModule = defineModule({
|
|
|
299
284
|
ipv6: z.string(),
|
|
300
285
|
}),
|
|
301
286
|
async apply(config, ctx) {
|
|
302
|
-
const token = ctx.
|
|
303
|
-
if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
287
|
+
const token = ctx.secret('FLY_API_TOKEN')
|
|
304
288
|
|
|
305
289
|
const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
|
|
306
290
|
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
@@ -438,8 +422,7 @@ export const flyModule = defineModule({
|
|
|
438
422
|
return { appName, hostname, ipv4: v4, ipv6: v6 }
|
|
439
423
|
},
|
|
440
424
|
async destroy(config, ctx) {
|
|
441
|
-
const token = ctx.
|
|
442
|
-
if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
|
|
425
|
+
const token = ctx.secret('FLY_API_TOKEN')
|
|
443
426
|
const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
|
|
444
427
|
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
445
428
|
const appName = config.appName ?? appNameFromFlyToml(workdir)
|
|
@@ -22,14 +22,13 @@ export const hostFileModule = defineModule({
|
|
|
22
22
|
}),
|
|
23
23
|
outputs: z.object({ path: z.string(), changed: z.boolean() }),
|
|
24
24
|
apply: async (config, ctx) => {
|
|
25
|
+
// `allowBlank`: presence is the contract. An empty secret is a legitimate
|
|
26
|
+
// file body, and refusing it would make "no value yet" unrepresentable.
|
|
25
27
|
const desired =
|
|
26
|
-
config.content !== undefined
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const existing = fs.existsSync(config.path)
|
|
31
|
-
? fs.readFileSync(config.path, 'utf8')
|
|
32
|
-
: null
|
|
28
|
+
config.content !== undefined
|
|
29
|
+
? config.content
|
|
30
|
+
: ctx.secret(config.secretKey!, { allowBlank: true })
|
|
31
|
+
const existing = fs.existsSync(config.path) ? fs.readFileSync(config.path, 'utf8') : null
|
|
33
32
|
const changed = existing !== desired
|
|
34
33
|
const mode = parseInt(config.mode, 8)
|
|
35
34
|
if (changed) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
+
import { resolveOutput } from '../../src/context'
|
|
2
3
|
|
|
3
4
|
// The parts of "converge the inside of a machine" that do not care how the
|
|
4
5
|
// work is delivered: what to run, whether to run it, and how to decide that
|
|
@@ -93,6 +94,20 @@ export function renderProvisionScript(input: {
|
|
|
93
94
|
* Reads `ENVVAR: "instance.field"` references out of another instance's
|
|
94
95
|
* outputs. Outputs only exist during an apply, so this is the only way a
|
|
95
96
|
* just-minted credential can reach a script without being written down.
|
|
97
|
+
*
|
|
98
|
+
* Only the dotted spelling is this function's own — `instance.field` is a
|
|
99
|
+
* flatter form than the `{ from, output }` every other module takes, and it is
|
|
100
|
+
* kept because it is what instance files already say. Once split, the lookup
|
|
101
|
+
* is the engine's `resolveOutput`, the same one behind `ctx.output`.
|
|
102
|
+
*
|
|
103
|
+
* `allowBlank`: an empty value is a real answer here. The authkey module mints
|
|
104
|
+
* only when there is a join to perform, and reports `''` otherwise —
|
|
105
|
+
* `shouldProvision` reads exactly that to decide whether an unchanged digest
|
|
106
|
+
* still has work.
|
|
107
|
+
*
|
|
108
|
+
* A non-string output is now an error rather than a `String(value)`. Exporting
|
|
109
|
+
* `TS_AUTHKEY=true` because a ref pointed at a boolean output is not a value
|
|
110
|
+
* any script wanted, and it reaches the guest looking exactly like one that was.
|
|
96
111
|
*/
|
|
97
112
|
export function resolveVolatileEnv(
|
|
98
113
|
spec: Record<string, string>,
|
|
@@ -104,21 +119,12 @@ export function resolveVolatileEnv(
|
|
|
104
119
|
if (dot <= 0 || dot === ref.length - 1) {
|
|
105
120
|
throw new Error(`volatileEnvFrom.${envVar}: "${ref}" is not of the form instance.field`)
|
|
106
121
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
)
|
|
114
|
-
}
|
|
115
|
-
const value = (source as Record<string, unknown>)[field]
|
|
116
|
-
if (value === undefined) {
|
|
117
|
-
throw new Error(
|
|
118
|
-
`volatileEnvFrom.${envVar}: instance "${instance}" has no output field "${field}"`,
|
|
119
|
-
)
|
|
120
|
-
}
|
|
121
|
-
out[envVar] = String(value)
|
|
122
|
+
out[envVar] = resolveOutput(
|
|
123
|
+
{ from: ref.slice(0, dot), output: ref.slice(dot + 1) },
|
|
124
|
+
imports,
|
|
125
|
+
`volatileEnvFrom.${envVar}`,
|
|
126
|
+
{ allowBlank: true },
|
|
127
|
+
)
|
|
122
128
|
}
|
|
123
129
|
return out
|
|
124
130
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
+
import { cf, type CfOptions } from '../cloudflare-api'
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
|
|
6
|
-
* token
|
|
7
|
+
* token through ctx.secret, idempotent list→create, console.log progress).
|
|
7
8
|
*
|
|
8
9
|
* Exists so bucket lifecycle is owned by infra instead of being a side effect
|
|
9
10
|
* of `wrangler deploy` prompting to create a missing bucket. A worker wires
|
|
@@ -13,46 +14,18 @@ import { defineModule } from '../../src/define-module'
|
|
|
13
14
|
* Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
|
|
14
15
|
*/
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
): Promise<T> {
|
|
29
|
-
const res = await fetch(`${API}${path}`, {
|
|
30
|
-
method: init?.method ?? 'GET',
|
|
31
|
-
headers: {
|
|
32
|
-
Authorization: `Bearer ${token}`,
|
|
33
|
-
'Content-Type': 'application/json',
|
|
34
|
-
},
|
|
35
|
-
body: init?.body === undefined ? undefined : JSON.stringify(init.body),
|
|
36
|
-
})
|
|
37
|
-
let envelope: CfEnvelope<T>
|
|
38
|
-
try {
|
|
39
|
-
envelope = (await res.json()) as CfEnvelope<T>
|
|
40
|
-
} catch {
|
|
41
|
-
throw new Error(`Cloudflare API ${path}: HTTP ${res.status} (non-JSON body)`)
|
|
42
|
-
}
|
|
43
|
-
if (!res.ok || !envelope.success) {
|
|
44
|
-
const codes = (envelope.errors ?? []).map((e) => e.code)
|
|
45
|
-
const detail = (envelope.errors ?? []).map((e) => `${e.code}: ${e.message}`).join('; ')
|
|
46
|
-
if (codes.includes(10000)) {
|
|
47
|
-
throw new Error(
|
|
48
|
-
`Cloudflare API ${path} rejected the token (10000 Authentication error). ` +
|
|
49
|
-
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
50
|
-
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
51
|
-
)
|
|
52
|
-
}
|
|
53
|
-
throw new Error(`Cloudflare API ${path} failed (HTTP ${res.status}): ${detail}`)
|
|
54
|
-
}
|
|
55
|
-
return envelope.result
|
|
17
|
+
/**
|
|
18
|
+
* Named per-code guidance for this module's calls — the one genuinely
|
|
19
|
+
* per-module part of a Cloudflare failure. Everything else about the envelope
|
|
20
|
+
* (the base URL, the error shapes, the typed throw) is `../cloudflare-api`'s.
|
|
21
|
+
*/
|
|
22
|
+
const OPTS: CfOptions = {
|
|
23
|
+
hints: {
|
|
24
|
+
10000:
|
|
25
|
+
`rejected the token (10000 Authentication error). ` +
|
|
26
|
+
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
27
|
+
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
28
|
+
},
|
|
56
29
|
}
|
|
57
30
|
|
|
58
31
|
export const r2Module = defineModule({
|
|
@@ -79,15 +52,18 @@ export const r2Module = defineModule({
|
|
|
79
52
|
bucketName: z.string(),
|
|
80
53
|
}),
|
|
81
54
|
async apply(config, ctx) {
|
|
82
|
-
const apiToken = ctx.
|
|
83
|
-
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
55
|
+
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
84
56
|
const base = `/accounts/${config.accountId}/r2/buckets`
|
|
85
57
|
|
|
86
58
|
if (config.ephemeral) {
|
|
87
59
|
try {
|
|
88
|
-
await
|
|
89
|
-
|
|
90
|
-
|
|
60
|
+
await cf(
|
|
61
|
+
apiToken,
|
|
62
|
+
'DELETE',
|
|
63
|
+
`${base}/${encodeURIComponent(config.bucketName)}`,
|
|
64
|
+
undefined,
|
|
65
|
+
OPTS,
|
|
66
|
+
)
|
|
91
67
|
console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
|
|
92
68
|
} catch {
|
|
93
69
|
// Didn't exist (or non-empty — creation below will then no-op via the
|
|
@@ -95,22 +71,28 @@ export const r2Module = defineModule({
|
|
|
95
71
|
}
|
|
96
72
|
}
|
|
97
73
|
|
|
98
|
-
const listing = await
|
|
74
|
+
const listing = await cf<{ buckets: Array<{ name: string }> }>(
|
|
99
75
|
apiToken,
|
|
76
|
+
'GET',
|
|
100
77
|
`${base}?per_page=1000`,
|
|
78
|
+
undefined,
|
|
79
|
+
OPTS,
|
|
101
80
|
)
|
|
102
81
|
const exists = listing.buckets.some((b) => b.name === config.bucketName)
|
|
103
82
|
|
|
104
83
|
if (exists) {
|
|
105
84
|
console.log(` Bucket "${config.bucketName}" already exists`)
|
|
106
85
|
} else {
|
|
107
|
-
await
|
|
108
|
-
|
|
109
|
-
|
|
86
|
+
await cf(
|
|
87
|
+
apiToken,
|
|
88
|
+
'POST',
|
|
89
|
+
base,
|
|
90
|
+
{
|
|
110
91
|
name: config.bucketName,
|
|
111
92
|
...(config.locationHint ? { locationHint: config.locationHint } : {}),
|
|
112
93
|
},
|
|
113
|
-
|
|
94
|
+
OPTS,
|
|
95
|
+
)
|
|
114
96
|
console.log(
|
|
115
97
|
` Created bucket "${config.bucketName}"${config.locationHint ? ` (${config.locationHint})` : ''}`,
|
|
116
98
|
)
|
|
@@ -119,13 +101,14 @@ export const r2Module = defineModule({
|
|
|
119
101
|
return { bucketName: config.bucketName }
|
|
120
102
|
},
|
|
121
103
|
async destroy(config, ctx) {
|
|
122
|
-
const apiToken = ctx.
|
|
123
|
-
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
104
|
+
const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
124
105
|
try {
|
|
125
|
-
await
|
|
106
|
+
await cf(
|
|
126
107
|
apiToken,
|
|
108
|
+
'DELETE',
|
|
127
109
|
`/accounts/${config.accountId}/r2/buckets/${encodeURIComponent(config.bucketName)}`,
|
|
128
|
-
|
|
110
|
+
undefined,
|
|
111
|
+
OPTS,
|
|
129
112
|
)
|
|
130
113
|
console.log(` Deleted bucket "${config.bucketName}"`)
|
|
131
114
|
} catch (err) {
|
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
"files": [{ "path": "index.ts" }],
|
|
5
5
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
6
6
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
7
|
-
"instructions": "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' }] }"
|
|
7
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope. In COPY mode run `zbc add cloudflare-api` too.\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
8
|
}
|
|
@@ -85,9 +85,7 @@ export const remoteProvisionModule = defineModule({
|
|
|
85
85
|
apply: async (config, ctx) => {
|
|
86
86
|
const env: Record<string, string> = { ...config.env }
|
|
87
87
|
for (const [key, secretKey] of Object.entries(config.envSecrets)) {
|
|
88
|
-
|
|
89
|
-
if (value === undefined) throw new Error(`secret "${secretKey}" not found in secrets.yaml`)
|
|
90
|
-
env[key] = value
|
|
88
|
+
env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
|
|
91
89
|
}
|
|
92
90
|
|
|
93
91
|
const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
|
|
@@ -109,8 +109,7 @@ export const tursoModule = defineModule({
|
|
|
109
109
|
authToken: z.string(),
|
|
110
110
|
}),
|
|
111
111
|
async apply(config, ctx) {
|
|
112
|
-
const apiToken = ctx.
|
|
113
|
-
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
112
|
+
const apiToken = ctx.secret('TURSO_API_TOKEN')
|
|
114
113
|
|
|
115
114
|
// Imported here rather than at the top of the file, the way the migration
|
|
116
115
|
// dependencies below already are: a consumer that vendors zbc-core but
|
|
@@ -210,8 +209,7 @@ export const tursoModule = defineModule({
|
|
|
210
209
|
}
|
|
211
210
|
},
|
|
212
211
|
async destroy(config, ctx) {
|
|
213
|
-
const apiToken = ctx.
|
|
214
|
-
if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
|
|
212
|
+
const apiToken = ctx.secret('TURSO_API_TOKEN')
|
|
215
213
|
|
|
216
214
|
const { createClient } = await import('@tursodatabase/api')
|
|
217
215
|
const turso = createClient({ org: config.orgName, token: apiToken })
|
|
@@ -44,6 +44,15 @@ export interface VmOutputs {
|
|
|
44
44
|
target?: IncusTarget
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* The one legitimate raw reader of `ctx.imports`.
|
|
49
|
+
*
|
|
50
|
+
* Every other lookup in core names what it wants — `ctx.output({ from, output
|
|
51
|
+
* }, field)` — because the instance file said so. This one has nothing to name:
|
|
52
|
+
* it SEARCHES the imports for outputs shaped like a vm, so that an instance
|
|
53
|
+
* importing exactly one vm need not repeat that vm's name. A ref-based
|
|
54
|
+
* resolver cannot express "whichever one it is", which is why this stays.
|
|
55
|
+
*/
|
|
47
56
|
export function findVmOutputs(imports: Record<string, unknown>): VmOutputs[] {
|
|
48
57
|
return Object.values(imports).filter((o): o is VmOutputs => {
|
|
49
58
|
if (typeof o !== 'object' || o === null) return false
|
|
@@ -104,12 +113,10 @@ export const vmProvisionModule = defineModule({
|
|
|
104
113
|
|
|
105
114
|
const env: Record<string, string> = { ...config.env }
|
|
106
115
|
for (const [key, secretKey] of Object.entries(config.envSecrets)) {
|
|
107
|
-
const value = ctx.secrets[secretKey]
|
|
108
116
|
// Presence is the contract, not non-emptiness — an intentionally blank
|
|
109
117
|
// placeholder lets a script no-op the step it gates until the real value
|
|
110
118
|
// is filled in, at which point the digest changes and it re-provisions.
|
|
111
|
-
|
|
112
|
-
env[key] = value
|
|
119
|
+
env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
|
|
113
120
|
}
|
|
114
121
|
|
|
115
122
|
const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// The two questions every module used to answer for itself.
|
|
2
|
+
//
|
|
3
|
+
// "What is this secret" was written seventeen times, in two spellings that
|
|
4
|
+
// disagree about what absent means (`!value`, which calls an empty string
|
|
5
|
+
// missing, and `=== undefined`, which does not). "What did the instance I
|
|
6
|
+
// imported emit" was written six times, and the copies differed in whether a
|
|
7
|
+
// non-string counted, whether an empty string counted, and which of the three
|
|
8
|
+
// distinct failures they could tell apart.
|
|
9
|
+
//
|
|
10
|
+
// Both live here now, and `ApplyContext` is how a module reaches them. The
|
|
11
|
+
// wording of the three `output` failures is `cloudflare-api`'s `resolveRef`
|
|
12
|
+
// verbatim: a missing import and a missing output are both silently
|
|
13
|
+
// `undefined` otherwise, and an apply that carries `Bearer undefined` fails
|
|
14
|
+
// much later, at a Cloudflare 403 that reads like a permissions problem.
|
|
15
|
+
//
|
|
16
|
+
// Runs under the CLI and under a consumer's own bun. Pure — no I/O, no
|
|
17
|
+
// runtime-specific globals — which is what lets it be tested as a value.
|
|
18
|
+
|
|
19
|
+
import type {
|
|
20
|
+
ApplyContext,
|
|
21
|
+
ApplyContextInput,
|
|
22
|
+
OutputOptions,
|
|
23
|
+
OutputRef,
|
|
24
|
+
SecretOptions,
|
|
25
|
+
} from './types'
|
|
26
|
+
|
|
27
|
+
/** `ctx.secret`, over a plain secrets record. */
|
|
28
|
+
export function resolveSecret(
|
|
29
|
+
secrets: Record<string, string>,
|
|
30
|
+
key: string,
|
|
31
|
+
opts: SecretOptions = {},
|
|
32
|
+
): string {
|
|
33
|
+
const raw = secrets[key]
|
|
34
|
+
const subject =
|
|
35
|
+
opts.field === undefined ? `Secret "${key}"` : `${opts.field} needs secret "${key}", which`
|
|
36
|
+
if (raw === undefined) {
|
|
37
|
+
throw new Error(`${subject} is missing from this environment's secrets.yaml`)
|
|
38
|
+
}
|
|
39
|
+
// `KEY:` with nothing after it parses to null, and that is the most natural
|
|
40
|
+
// spelling of the intentionally blank placeholder `allowBlank` exists for —
|
|
41
|
+
// so it means what `KEY: ""` means rather than a different failure. The
|
|
42
|
+
// coercion also keeps the return type honest: without it, a module that asked
|
|
43
|
+
// for a string gets `null` and finds out somewhere much further downstream.
|
|
44
|
+
const value = raw === null ? '' : raw
|
|
45
|
+
if (value === '' && !opts.allowBlank) {
|
|
46
|
+
throw new Error(`${subject} is empty in this environment's secrets.yaml`)
|
|
47
|
+
}
|
|
48
|
+
return value
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `ctx.output`, over a plain imports record.
|
|
53
|
+
*
|
|
54
|
+
* The three messages are the whole value of this function: `field` says which
|
|
55
|
+
* line of the instance file to look at, and the three cases are told apart
|
|
56
|
+
* because they have three different fixes.
|
|
57
|
+
*
|
|
58
|
+
* `ref` is typed loosely on purpose. A zod-inferred config marks both halves
|
|
59
|
+
* optional in some spellings, and the checks have to run at runtime regardless
|
|
60
|
+
* — a `from` naming an instance that is not imported is a real failure mode and
|
|
61
|
+
* nothing in the type system is catching it here.
|
|
62
|
+
*/
|
|
63
|
+
export function resolveOutput(
|
|
64
|
+
ref: OutputRef,
|
|
65
|
+
imports: Record<string, unknown>,
|
|
66
|
+
field: string,
|
|
67
|
+
opts: OutputOptions = {},
|
|
68
|
+
): string {
|
|
69
|
+
if (!ref.from || !ref.output) {
|
|
70
|
+
throw new Error(`${field} must name both an instance (\`from\`) and an output (\`output\`)`)
|
|
71
|
+
}
|
|
72
|
+
const outputs = imports[ref.from]
|
|
73
|
+
if (outputs === undefined) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`${field} references instance "${ref.from}", which is not in this instance's imports`,
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
const value = (outputs as Record<string, unknown> | null)?.[ref.output]
|
|
79
|
+
if (typeof value !== 'string' || (value === '' && !opts.allowBlank)) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`${field} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
return value
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The context the engine hands a module: the three fields plus the two rules. */
|
|
88
|
+
export function createApplyContext(input: ApplyContextInput): ApplyContext {
|
|
89
|
+
return {
|
|
90
|
+
secrets: input.secrets,
|
|
91
|
+
imports: input.imports,
|
|
92
|
+
projectRoot: input.projectRoot,
|
|
93
|
+
secret(key, opts) {
|
|
94
|
+
return resolveSecret(input.secrets, key, opts)
|
|
95
|
+
},
|
|
96
|
+
output(ref, field, opts) {
|
|
97
|
+
return resolveOutput(ref, input.imports, field, opts)
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Upgrade whatever a caller passed into a full context, leaving one that is
|
|
104
|
+
* already full — the engine's destroy context resolves imports on demand, and
|
|
105
|
+
* rebuilding it here would throw that away.
|
|
106
|
+
*
|
|
107
|
+
* `defineModule` calls this on every `apply`/`destroy`, so a module body may
|
|
108
|
+
* assume the methods exist no matter who invoked it.
|
|
109
|
+
*/
|
|
110
|
+
export function ensureApplyContext(ctx: ApplyContextInput | ApplyContext): ApplyContext {
|
|
111
|
+
const candidate = ctx as ApplyContext
|
|
112
|
+
return typeof candidate.secret === 'function' && typeof candidate.output === 'function'
|
|
113
|
+
? candidate
|
|
114
|
+
: createApplyContext(ctx)
|
|
115
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { z } from 'zod'
|
|
2
|
+
import { ensureApplyContext } from './context'
|
|
2
3
|
import type { ApplyFn, DestroyFn, ModuleDefinition, ModuleInstance, InstanceOptions } from './types'
|
|
3
4
|
|
|
4
5
|
interface DefineModuleOptions<TConfig extends z.ZodType, TOutputs extends z.ZodType> {
|
|
@@ -16,8 +17,13 @@ export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodTy
|
|
|
16
17
|
name: opts.name,
|
|
17
18
|
configSchema: opts.configSchema,
|
|
18
19
|
outputsSchema: opts.outputs,
|
|
19
|
-
|
|
20
|
-
|
|
20
|
+
// The context is normalized HERE rather than in the engine, so a module
|
|
21
|
+
// body may assume `ctx.secret`/`ctx.output` exist whoever called it — the
|
|
22
|
+
// engine, another module's test, a consumer's script. A caller that
|
|
23
|
+
// already holds a full context (the destroy path's on-demand one) is
|
|
24
|
+
// passed through untouched.
|
|
25
|
+
apply: (config, ctx) => opts.apply(config, ensureApplyContext(ctx)),
|
|
26
|
+
destroy: opts.destroy && ((config, ctx) => opts.destroy!(config, ensureApplyContext(ctx))),
|
|
21
27
|
instance(instanceOpts: InstanceOptions<TConfig>): ModuleInstance<TOutputs> {
|
|
22
28
|
return {
|
|
23
29
|
name: instanceOpts.name,
|
|
@@ -1,3 +1,13 @@
|
|
|
1
1
|
export { defineModule } from './define-module'
|
|
2
2
|
export { defineConfig } from './config'
|
|
3
|
-
export
|
|
3
|
+
export { createApplyContext, ensureApplyContext, resolveOutput, resolveSecret } from './context'
|
|
4
|
+
export type {
|
|
5
|
+
ModuleDefinition,
|
|
6
|
+
ModuleInstance,
|
|
7
|
+
ApplyContext,
|
|
8
|
+
ApplyContextInput,
|
|
9
|
+
OutputRef,
|
|
10
|
+
OutputOptions,
|
|
11
|
+
SecretOptions,
|
|
12
|
+
InstanceOptions,
|
|
13
|
+
} from './types'
|
|
@@ -4,18 +4,87 @@ export type ApplyFn<TConfig, TOutputs> = (config: TConfig, ctx: ApplyContext) =>
|
|
|
4
4
|
|
|
5
5
|
export type DestroyFn<TConfig> = (config: TConfig, ctx: ApplyContext) => Promise<void>
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The three raw fields a caller has to supply. `defineModule` turns one of
|
|
9
|
+
* these into a full `ApplyContext` before the module body sees it (see
|
|
10
|
+
* `context.ts`), which is why the engine — and a test — may hand `apply` a
|
|
11
|
+
* plain object and the module still gets `secret()` and `output()`.
|
|
12
|
+
*/
|
|
13
|
+
export interface ApplyContextInput {
|
|
8
14
|
secrets: Record<string, string>
|
|
9
15
|
imports: Record<string, unknown>
|
|
10
16
|
projectRoot: string
|
|
11
17
|
}
|
|
12
18
|
|
|
19
|
+
/** A `{ from, output }` reference into an imported instance's outputs. */
|
|
20
|
+
export interface OutputRef {
|
|
21
|
+
from?: string
|
|
22
|
+
output?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SecretOptions {
|
|
26
|
+
/**
|
|
27
|
+
* What wanted the secret, for the error message — e.g.
|
|
28
|
+
* `flySecrets entry "WALGIT_S3_ACCESS_KEY_ID"`. With an alias the env var
|
|
29
|
+
* name and the secrets.yaml key are different strings, and a message naming
|
|
30
|
+
* only one sends the reader to the wrong file.
|
|
31
|
+
*/
|
|
32
|
+
field?: string
|
|
33
|
+
/**
|
|
34
|
+
* Presence is the contract rather than non-emptiness. An intentionally blank
|
|
35
|
+
* placeholder — `KEY:` with no value, or `KEY: ""` — lets a script no-op the
|
|
36
|
+
* step it gates until the real value is filled in.
|
|
37
|
+
*/
|
|
38
|
+
allowBlank?: boolean
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface OutputOptions {
|
|
42
|
+
/** Accept an emitted empty string — for outputs where "nothing to do" is a real answer. */
|
|
43
|
+
allowBlank?: boolean
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What a module's `apply`/`destroy` receives.
|
|
48
|
+
*
|
|
49
|
+
* The two methods are the engine's answer to the same two questions every
|
|
50
|
+
* module used to answer itself: "what is this secret" and "what did the
|
|
51
|
+
* instance I imported emit". Six copies of the second and seventeen of the
|
|
52
|
+
* first is how they failed differently for the same cause.
|
|
53
|
+
*/
|
|
54
|
+
export interface ApplyContext extends ApplyContextInput {
|
|
55
|
+
/**
|
|
56
|
+
* A value from this environment's secrets.yaml. Throws naming the key (and
|
|
57
|
+
* `field`, when given) if the key is absent or blank; `allowBlank` accepts a
|
|
58
|
+
* key that is present but intentionally empty.
|
|
59
|
+
*/
|
|
60
|
+
secret(key: string, opts?: SecretOptions): string
|
|
61
|
+
/**
|
|
62
|
+
* An imported instance's output. Throws naming `field` when the ref is
|
|
63
|
+
* incomplete, when the instance is not among this instance's imports, or
|
|
64
|
+
* when it does not emit that output. `allowBlank` accepts an emitted empty
|
|
65
|
+
* string — "nothing to do" is a real answer for some outputs.
|
|
66
|
+
*/
|
|
67
|
+
output(ref: OutputRef, field: string, opts?: OutputOptions): string
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The shape `defineModule` publishes: it accepts the raw three fields, because
|
|
72
|
+
* it normalizes them itself. A caller holding a full `ApplyContext` may pass
|
|
73
|
+
* that instead — it is already one of these.
|
|
74
|
+
*/
|
|
75
|
+
export type BoundApplyFn<TConfig, TOutputs> = (
|
|
76
|
+
config: TConfig,
|
|
77
|
+
ctx: ApplyContextInput,
|
|
78
|
+
) => Promise<TOutputs>
|
|
79
|
+
|
|
80
|
+
export type BoundDestroyFn<TConfig> = (config: TConfig, ctx: ApplyContextInput) => Promise<void>
|
|
81
|
+
|
|
13
82
|
export interface ModuleDefinition<TConfig extends z.ZodType, TOutputs extends z.ZodType> {
|
|
14
83
|
name: string
|
|
15
84
|
configSchema: TConfig
|
|
16
85
|
outputsSchema: TOutputs
|
|
17
|
-
apply:
|
|
18
|
-
destroy?:
|
|
86
|
+
apply: BoundApplyFn<z.infer<TConfig>, z.infer<TOutputs>>
|
|
87
|
+
destroy?: BoundDestroyFn<z.infer<TConfig>>
|
|
19
88
|
instance: (opts: InstanceOptions<TConfig>) => ModuleInstance<TOutputs>
|
|
20
89
|
}
|
|
21
90
|
|