@zabaca/zbc 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/commands/add.ts +3 -1
- package/src/commands/destroy.ts +8 -9
- package/src/engine/destroy.ts +22 -2
- package/templates/infra/modules/cloudflare/index.ts +163 -0
- package/templates/infra/modules/cloudflare/registry.json +15 -0
- package/templates/workflows/preview.yml +31 -2
package/package.json
CHANGED
package/src/commands/add.ts
CHANGED
|
@@ -28,7 +28,9 @@ async function resolveBundledModuleDir(name: string): Promise<string> {
|
|
|
28
28
|
const registry = path.join(dir, 'registry.json')
|
|
29
29
|
if (await Bun.file(registry).exists()) return dir
|
|
30
30
|
}
|
|
31
|
-
throw new Error(
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Module "${name}" not found in built-in registry. Available: cloudflare, nats-server, turso, vercel.`,
|
|
33
|
+
)
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
function bunAdd(
|
package/src/commands/destroy.ts
CHANGED
|
@@ -15,6 +15,11 @@ export const destroyCommand = defineCommand({
|
|
|
15
15
|
description: 'Environment name (e.g., preview)',
|
|
16
16
|
required: true,
|
|
17
17
|
},
|
|
18
|
+
instance: {
|
|
19
|
+
type: 'positional',
|
|
20
|
+
description: 'Specific instance to destroy (omit to destroy the whole environment)',
|
|
21
|
+
required: false,
|
|
22
|
+
},
|
|
18
23
|
},
|
|
19
24
|
async run({ args }) {
|
|
20
25
|
const projectRoot = await findProjectRoot()
|
|
@@ -27,16 +32,10 @@ export const destroyCommand = defineCommand({
|
|
|
27
32
|
process.exit(1)
|
|
28
33
|
}
|
|
29
34
|
|
|
30
|
-
const envDir = path.join(
|
|
31
|
-
projectRoot,
|
|
32
|
-
'packages',
|
|
33
|
-
'infra',
|
|
34
|
-
'environments',
|
|
35
|
-
args.env,
|
|
36
|
-
)
|
|
35
|
+
const envDir = path.join(projectRoot, 'packages', 'infra', 'environments', args.env)
|
|
37
36
|
|
|
38
|
-
console.log(`Destroying ${args.env}...`)
|
|
39
|
-
await destroyEnvironment(projectRoot, envDir)
|
|
37
|
+
console.log(`Destroying ${args.env}${args.instance ? ` (instance: ${args.instance})` : ''}...`)
|
|
38
|
+
await destroyEnvironment(projectRoot, envDir, args.instance)
|
|
40
39
|
console.log('\nDone.')
|
|
41
40
|
},
|
|
42
41
|
})
|
package/src/engine/destroy.ts
CHANGED
|
@@ -3,10 +3,30 @@ import { discoverInstances } from './discover'
|
|
|
3
3
|
import { resolveOrder } from './resolve'
|
|
4
4
|
import { loadSecrets } from './secrets'
|
|
5
5
|
|
|
6
|
-
export async function destroyEnvironment(
|
|
6
|
+
export async function destroyEnvironment(
|
|
7
|
+
projectRoot: string,
|
|
8
|
+
envDir: string,
|
|
9
|
+
target?: string,
|
|
10
|
+
): Promise<void> {
|
|
7
11
|
const instances = await discoverInstances(envDir)
|
|
8
12
|
const sorted = resolveOrder(instances)
|
|
9
|
-
|
|
13
|
+
let reversed = [...sorted].reverse()
|
|
14
|
+
|
|
15
|
+
// Targeted destroy: tear down ONLY the named instance. Unlike apply, we do
|
|
16
|
+
// NOT pull in the dependency closure, since a thing's dependencies are
|
|
17
|
+
// usually shared infra you don't want destroyed alongside it. Without this filter,
|
|
18
|
+
// `zbc destroy <env> <instance>` silently ignored the instance arg and
|
|
19
|
+
// destroyed the entire environment.
|
|
20
|
+
if (target) {
|
|
21
|
+
const found = reversed.find((i) => i.name === target)
|
|
22
|
+
if (!found) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`Instance "${target}" not found. Available: ${instances.map((i) => i.name).join(', ')}`,
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
reversed = [found]
|
|
28
|
+
}
|
|
29
|
+
|
|
10
30
|
const secrets = await loadSecrets(envDir)
|
|
11
31
|
|
|
12
32
|
for (const instance of reversed) {
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import * as fs from 'node:fs'
|
|
3
|
+
import { execFileSync, execSync } from 'node:child_process'
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
import { defineModule } from '../../src/define-module'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* cloudflare — deploys a Cloudflare Worker (optionally with static assets, a
|
|
9
|
+
* Durable Object, and a Container) via `wrangler deploy`.
|
|
10
|
+
*
|
|
11
|
+
* This is a THIN orchestrator, the same shape as the vercel/turso/lima-engine
|
|
12
|
+
* modules: `apply` runs on the operator machine, reads CF creds from
|
|
13
|
+
* `ctx.secrets`, runs an optional local build, then shells `wrangler deploy` in
|
|
14
|
+
* the package's own directory. The Worker TOPOLOGY (name, assets binding,
|
|
15
|
+
* durable_objects, containers, migrations) lives in that package's
|
|
16
|
+
* `wrangler.jsonc` — wrangler is the source of truth for it, not this module.
|
|
17
|
+
* That keeps the module reusable for the eventual Astro-off-Vercel migration
|
|
18
|
+
* (a plain assets Worker) as well as the container-backed payloads.
|
|
19
|
+
*
|
|
20
|
+
* Auth is non-interactive: wrangler reads `CLOUDFLARE_API_TOKEN` +
|
|
21
|
+
* `CLOUDFLARE_ACCOUNT_ID` from the environment, so no `wrangler login` is
|
|
22
|
+
* needed. Worker secrets (e.g. CLAUDE_CODE_OAUTH_TOKEN) are pushed via
|
|
23
|
+
* `wrangler secret put`, piped through stdin so no secret value is ever
|
|
24
|
+
* interpolated into a command string.
|
|
25
|
+
*
|
|
26
|
+
* NOTE on containers (Phase B): `wrangler deploy` builds the container image
|
|
27
|
+
* with Docker, so Docker must be running locally at apply time, and the account
|
|
28
|
+
* must be on a Workers Paid plan with Containers enabled. A plain assets Worker
|
|
29
|
+
* (Phase A) has neither requirement.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** Resolve the wrangler binary: prefer the package-local one, else `bunx`. */
|
|
33
|
+
function resolveWrangler(workdir: string): { cmd: string; pre: string[] } {
|
|
34
|
+
const local = path.join(workdir, 'node_modules', '.bin', 'wrangler')
|
|
35
|
+
if (fs.existsSync(local)) return { cmd: local, pre: [] }
|
|
36
|
+
// Fall back to bunx; --bun keeps it on the bun runtime already in use.
|
|
37
|
+
return { cmd: 'bunx', pre: ['--bun', 'wrangler'] }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Run wrangler in `workdir` with CF creds in the env; return captured stdout. */
|
|
41
|
+
function wrangler(workdir: string, args: string[], env: NodeJS.ProcessEnv, input?: string): string {
|
|
42
|
+
const { cmd, pre } = resolveWrangler(workdir)
|
|
43
|
+
try {
|
|
44
|
+
const out = execFileSync(cmd, [...pre, ...args], {
|
|
45
|
+
cwd: workdir,
|
|
46
|
+
env,
|
|
47
|
+
input,
|
|
48
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
49
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
50
|
+
})
|
|
51
|
+
return out.toString()
|
|
52
|
+
} catch (err: unknown) {
|
|
53
|
+
const stderr = (err as { stderr?: Buffer }).stderr?.toString() ?? ''
|
|
54
|
+
const stdout = (err as { stdout?: Buffer }).stdout?.toString() ?? ''
|
|
55
|
+
throw new Error(
|
|
56
|
+
`wrangler ${args.join(' ')} failed:\n${stderr || stdout || (err as Error).message}`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const buildSchema = z.object({
|
|
62
|
+
command: z.string(),
|
|
63
|
+
cwd: z.string().optional(),
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
export const cloudflareModule = defineModule({
|
|
67
|
+
name: 'cloudflare',
|
|
68
|
+
configSchema: z.object({
|
|
69
|
+
/** Package dir (relative to projectRoot) that holds wrangler.jsonc. */
|
|
70
|
+
workdir: z.string(),
|
|
71
|
+
/**
|
|
72
|
+
* Cloudflare account id. Not a secret (it appears in the dashboard URL), so
|
|
73
|
+
* it lives in config — only the API token is held in secrets.yaml.
|
|
74
|
+
*/
|
|
75
|
+
accountId: z.string(),
|
|
76
|
+
/** Optional local build run before deploy (e.g. `vite build` for assets). */
|
|
77
|
+
build: buildSchema.optional(),
|
|
78
|
+
/**
|
|
79
|
+
* Worker secrets to push after deploy. Each entry names a key in this
|
|
80
|
+
* environment's secrets.yaml; the same name becomes a Worker secret
|
|
81
|
+
* binding (read at runtime as `env.<NAME>`). Pushed via `wrangler secret
|
|
82
|
+
* put` with the value piped through stdin.
|
|
83
|
+
*/
|
|
84
|
+
workerSecrets: z.array(z.string()).default([]),
|
|
85
|
+
/**
|
|
86
|
+
* For container-backed Workers: roll the running container to the new image
|
|
87
|
+
* IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
|
|
88
|
+
* default is a GRADUAL rollout, which never drains a single always-warm,
|
|
89
|
+
* DO-bound container — so a redeployed image silently never takes effect
|
|
90
|
+
* until the container idle-sleeps. Set true whenever the image matters at
|
|
91
|
+
* deploy time. No-op for asset-only Workers.
|
|
92
|
+
*/
|
|
93
|
+
immediateContainerRollout: z.boolean().default(false),
|
|
94
|
+
}),
|
|
95
|
+
outputs: z.object({
|
|
96
|
+
deployUrl: z.string(),
|
|
97
|
+
}),
|
|
98
|
+
async apply(config, ctx) {
|
|
99
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
100
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
101
|
+
|
|
102
|
+
const env: NodeJS.ProcessEnv = {
|
|
103
|
+
...process.env,
|
|
104
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
105
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
109
|
+
|
|
110
|
+
// 1. Optional local build (assets). Inherit stdio so build output streams.
|
|
111
|
+
if (config.build) {
|
|
112
|
+
const buildCwd = path.resolve(ctx.projectRoot, config.build.cwd ?? config.workdir)
|
|
113
|
+
console.log(
|
|
114
|
+
` Building: ${config.build.command} (in ${path.relative(ctx.projectRoot, buildCwd) || '.'})`,
|
|
115
|
+
)
|
|
116
|
+
execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 2. Deploy. Creates/updates the Worker script (+ assets, DO, container).
|
|
120
|
+
const deployArgs = ['deploy']
|
|
121
|
+
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
122
|
+
console.log(
|
|
123
|
+
` Deploying via wrangler (in ${config.workdir})${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}`,
|
|
124
|
+
)
|
|
125
|
+
const out = wrangler(workdir, deployArgs, env)
|
|
126
|
+
const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
|
|
127
|
+
const deployUrl = urlMatch?.[0] ?? ''
|
|
128
|
+
console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
|
|
129
|
+
|
|
130
|
+
// 3. Push Worker secrets (after deploy: the script must exist first). Value
|
|
131
|
+
// piped via stdin so it never lands in a command string or the log.
|
|
132
|
+
for (const name of config.workerSecrets) {
|
|
133
|
+
const value = ctx.secrets[name]
|
|
134
|
+
if (!value) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`workerSecrets references "${name}" but it's missing from this environment's secrets.yaml`,
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
wrangler(workdir, ['secret', 'put', name], env, value)
|
|
140
|
+
console.log(` Set Worker secret: ${name}`)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return { deployUrl }
|
|
144
|
+
},
|
|
145
|
+
async destroy(config, ctx) {
|
|
146
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
147
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
148
|
+
const env: NodeJS.ProcessEnv = {
|
|
149
|
+
...process.env,
|
|
150
|
+
CLOUDFLARE_API_TOKEN: apiToken,
|
|
151
|
+
CLOUDFLARE_ACCOUNT_ID: config.accountId,
|
|
152
|
+
}
|
|
153
|
+
const workdir = path.resolve(ctx.projectRoot, config.workdir)
|
|
154
|
+
// `wrangler delete` removes the Worker (and its DO/container). Non-fatal if
|
|
155
|
+
// already gone.
|
|
156
|
+
try {
|
|
157
|
+
wrangler(workdir, ['delete', '--force'], env)
|
|
158
|
+
console.log(' Deleted Worker')
|
|
159
|
+
} catch (err) {
|
|
160
|
+
console.log(` Worker delete skipped: ${(err as Error).message}`)
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cloudflare",
|
|
3
|
+
"description": "Cloudflare Worker deploy module (optional static assets, Durable Object, Container)",
|
|
4
|
+
"files": [{ "path": "index.ts" }],
|
|
5
|
+
"dependencies": {
|
|
6
|
+
"zod": "^3.24.0"
|
|
7
|
+
},
|
|
8
|
+
"devDependencies": {
|
|
9
|
+
"wrangler": "^4.0.0"
|
|
10
|
+
},
|
|
11
|
+
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
12
|
+
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
13
|
+
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
14
|
+
"instructions": "Add CLOUDFLARE_API_TOKEN to packages/infra/environments/<env>/secrets.yaml; set accountId in the instance config (not a secret). The Worker topology lives in the package's own wrangler.jsonc, which is the source of truth for it. Container-backed Workers need Docker running locally at apply time and a Workers Paid plan with Containers enabled."
|
|
15
|
+
}
|
|
@@ -27,10 +27,39 @@ jobs:
|
|
|
27
27
|
|
|
28
28
|
- run: bun install
|
|
29
29
|
|
|
30
|
-
- name: Apply preview
|
|
30
|
+
- name: Apply preview + comment URLs
|
|
31
31
|
env:
|
|
32
32
|
SOPS_AGE_KEY: ${{ secrets.SOPS_AGE_KEY }}
|
|
33
|
-
|
|
33
|
+
GH_TOKEN: ${{ github.token }}
|
|
34
|
+
run: |
|
|
35
|
+
set -o pipefail
|
|
36
|
+
OUTPUT=$(bunx @zabaca/zbc apply preview 2>&1)
|
|
37
|
+
STATUS=$?
|
|
38
|
+
echo "$OUTPUT"
|
|
39
|
+
|
|
40
|
+
# Pair each "Deployed:" URL with the most recent "→ vercel:<name>" header
|
|
41
|
+
LIST=$(echo "$OUTPUT" | awk '
|
|
42
|
+
/^→ vercel:/{name=$2; sub(/vercel:/, "", name)}
|
|
43
|
+
/Deployed:/{print "- **" name "**: " $NF}
|
|
44
|
+
')
|
|
45
|
+
|
|
46
|
+
if [ -z "$LIST" ]; then
|
|
47
|
+
LIST="(no deployments captured — see logs)"
|
|
48
|
+
fi
|
|
49
|
+
|
|
50
|
+
BODY=$(printf '### Preview deployed :rocket:\n\n%s\n' "$LIST")
|
|
51
|
+
|
|
52
|
+
# Update existing comment if present, else create a new one
|
|
53
|
+
EXISTING=$(gh api "repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
|
|
54
|
+
--jq '.[] | select(.body | startswith("### Preview deployed")) | .id' | head -1)
|
|
55
|
+
|
|
56
|
+
if [ -n "$EXISTING" ]; then
|
|
57
|
+
gh api -X PATCH "repos/${{ github.repository }}/issues/comments/$EXISTING" -f body="$BODY"
|
|
58
|
+
else
|
|
59
|
+
gh pr comment ${{ github.event.pull_request.number }} --body "$BODY"
|
|
60
|
+
fi
|
|
61
|
+
|
|
62
|
+
exit $STATUS
|
|
34
63
|
|
|
35
64
|
cleanup:
|
|
36
65
|
if: github.event.action == 'closed'
|