@zabaca/zbc 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,137 @@
1
+ import { z } from 'zod'
2
+ import { defineModule } from '../../src/define-module'
3
+
4
+ /**
5
+ * r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
6
+ * token from ctx.secrets, idempotent list→create, console.log progress).
7
+ *
8
+ * Exists so bucket lifecycle is owned by infra instead of being a side effect
9
+ * of `wrangler deploy` prompting to create a missing bucket. A worker wires
10
+ * the bucket in through the cloudflare module's `r2Bindings` config, typically
11
+ * as a `{ binding, from, output }` reference into this instance's outputs.
12
+ *
13
+ * Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
14
+ */
15
+
16
+ const API = 'https://api.cloudflare.com/client/v4'
17
+
18
+ interface CfEnvelope<T> {
19
+ success: boolean
20
+ errors: Array<{ code: number; message: string }>
21
+ result: T
22
+ }
23
+
24
+ async function cfFetch<T>(
25
+ token: string,
26
+ path: string,
27
+ init?: { method?: string; body?: unknown },
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
56
+ }
57
+
58
+ export const r2Module = defineModule({
59
+ name: 'r2',
60
+ configSchema: z.object({
61
+ /** Cloudflare account id (not a secret — it's in the dashboard URL). */
62
+ accountId: z.string(),
63
+ /** Bucket name — account-scoped, so namespace it per project/env. */
64
+ bucketName: z.string(),
65
+ /**
66
+ * Location hint for new buckets (e.g. 'wnam', 'enam', 'weur'). Only
67
+ * applied at creation; Cloudflare doesn't support relocating a bucket.
68
+ */
69
+ locationHint: z.string().optional(),
70
+ /**
71
+ * Destroy+recreate on every apply (preview environments). NOTE: deleting
72
+ * a non-empty bucket fails — the management API has no object purge, so
73
+ * ephemeral only works cleanly for buckets whose objects the app cleans
74
+ * up, or that stay small enough to purge by hand.
75
+ */
76
+ ephemeral: z.boolean().default(false),
77
+ }),
78
+ outputs: z.object({
79
+ bucketName: z.string(),
80
+ }),
81
+ async apply(config, ctx) {
82
+ const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
83
+ if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
84
+ const base = `/accounts/${config.accountId}/r2/buckets`
85
+
86
+ if (config.ephemeral) {
87
+ try {
88
+ await cfFetch(apiToken, `${base}/${encodeURIComponent(config.bucketName)}`, {
89
+ method: 'DELETE',
90
+ })
91
+ console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
92
+ } catch {
93
+ // Didn't exist (or non-empty — creation below will then no-op via the
94
+ // existence check, which for ephemeral means stale objects persist).
95
+ }
96
+ }
97
+
98
+ const listing = await cfFetch<{ buckets: Array<{ name: string }> }>(
99
+ apiToken,
100
+ `${base}?per_page=1000`,
101
+ )
102
+ const exists = listing.buckets.some((b) => b.name === config.bucketName)
103
+
104
+ if (exists) {
105
+ console.log(` Bucket "${config.bucketName}" already exists`)
106
+ } else {
107
+ await cfFetch(apiToken, base, {
108
+ method: 'POST',
109
+ body: {
110
+ name: config.bucketName,
111
+ ...(config.locationHint ? { locationHint: config.locationHint } : {}),
112
+ },
113
+ })
114
+ console.log(
115
+ ` Created bucket "${config.bucketName}"${config.locationHint ? ` (${config.locationHint})` : ''}`,
116
+ )
117
+ }
118
+
119
+ return { bucketName: config.bucketName }
120
+ },
121
+ async destroy(config, ctx) {
122
+ const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
123
+ if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
124
+ try {
125
+ await cfFetch(
126
+ apiToken,
127
+ `/accounts/${config.accountId}/r2/buckets/${encodeURIComponent(config.bucketName)}`,
128
+ { method: 'DELETE' },
129
+ )
130
+ console.log(` Deleted bucket "${config.bucketName}"`)
131
+ } catch (err) {
132
+ // Most common cause: bucket not empty (the API refuses). Surface it —
133
+ // silent skips here would strand storage.
134
+ console.log(` Bucket delete skipped: ${(err as Error).message}`)
135
+ }
136
+ },
137
+ })
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "r2",
3
+ "description": "Cloudflare R2 bucket, provisioned via the REST API. Pair with the cloudflare module's r2Bindings to wire the bucket into a Worker at deploy time.",
4
+ "files": [{ "path": "index.ts" }],
5
+ "secrets": ["CLOUDFLARE_API_TOKEN"],
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' }] }"
8
+ }