@beechcms/cli 0.4.0-preview.9 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beechcms/cli",
3
- "version": "0.4.0-preview.9",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {
@@ -11,7 +11,7 @@
11
11
  "dev": "esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --outfile=dist/index.js --watch"
12
12
  },
13
13
  "dependencies": {
14
- "@beechcms/core": "^0.4.0-preview.9",
14
+ "@beechcms/core": "^0.4.0",
15
15
  "picocolors": "^1.1.1"
16
16
  },
17
17
  "devDependencies": {
@@ -0,0 +1,123 @@
1
+ import pc from 'picocolors'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { readFileSync } from 'node:fs'
4
+ import { findWranglerConfig } from '../lib/wrangler.js'
5
+
6
+ export interface DeployOptions {
7
+ skipSeed?: boolean
8
+ skipCheck?: boolean
9
+ }
10
+
11
+ function readWorkerName(configPath: string | null): string | null {
12
+ if (!configPath) return null
13
+ try {
14
+ const raw = readFileSync(configPath, 'utf-8')
15
+ const stripped = raw
16
+ .replace(/\/\/[^\n]*/g, '')
17
+ .replace(/\/\*[\s\S]*?\*\//g, '')
18
+ const parsed = JSON.parse(stripped)
19
+ return (parsed?.name as string) ?? null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ // Extracts the first workers.dev URL from wrangler deploy stdout.
26
+ // wrangler writes progress to stderr (shown live) and the summary to stdout (captured).
27
+ function extractWorkerUrl(output: string): string | null {
28
+ const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.workers\.dev\b/)
29
+ return match?.[0] ?? null
30
+ }
31
+
32
+ async function checkAdmin(url: string): Promise<{ ok: boolean; status: number | null }> {
33
+ try {
34
+ const res = await fetch(`${url}/admin`, {
35
+ method: 'HEAD',
36
+ redirect: 'follow',
37
+ signal: AbortSignal.timeout(12_000),
38
+ })
39
+ return { ok: res.status < 500, status: res.status }
40
+ } catch {
41
+ return { ok: false, status: null }
42
+ }
43
+ }
44
+
45
+ export async function deploy(args: DeployOptions): Promise<void> {
46
+ console.log(pc.cyan('\n beech deploy\n'))
47
+
48
+ // Step 1: wrangler deploy via npm run deploy.
49
+ // stdout captured to extract the deployed URL; stderr stays on the terminal for live progress.
50
+ console.log(pc.dim(' [1/3] Deploying Worker…\n'))
51
+ const deployResult = spawnSync('npm', ['run', 'deploy'], {
52
+ stdio: ['inherit', 'pipe', 'inherit'],
53
+ encoding: 'utf-8',
54
+ cwd: process.cwd(),
55
+ shell: true,
56
+ })
57
+
58
+ const deployStdout = deployResult.stdout ?? ''
59
+ if (deployStdout) process.stdout.write(deployStdout)
60
+
61
+ if (deployResult.status !== 0) {
62
+ console.log(pc.red('\n ✗ Worker deploy failed\n'))
63
+ console.log(pc.dim(' Check the wrangler output above for details.'))
64
+ console.log(pc.cyan('\n → Run: npx wrangler login # if not authenticated'))
65
+ console.log(pc.cyan(' → Or: Update wrangler.jsonc # if database_id is wrong\n'))
66
+ process.exit(1)
67
+ }
68
+
69
+ const deployedUrl = extractWorkerUrl(deployStdout)
70
+ console.log(pc.green('\n ✓ Worker deployed'))
71
+
72
+ // Step 2: seed:load --remote as a subprocess so that wrangler failures
73
+ // (which call process.exit internally) don't abort our own process.
74
+ if (args.skipSeed) {
75
+ console.log(pc.dim('\n [2/3] Skipping seed:load (--skip-seed)'))
76
+ } else {
77
+ console.log(pc.dim('\n [2/3] Syncing content schema to remote D1…\n'))
78
+ const seedResult = spawnSync('npx', ['beech', 'seed:load'], {
79
+ stdio: 'inherit',
80
+ cwd: process.cwd(),
81
+ shell: true,
82
+ })
83
+ if (seedResult.status !== 0) {
84
+ console.log(pc.yellow('\n ⚠ seed:load failed\n'))
85
+ console.log(pc.dim(' Sync the remote content schema manually:'))
86
+ console.log(pc.cyan(' → Run: npx beech seed:load\n'))
87
+ } else {
88
+ console.log(pc.green('\n ✓ Content schema synced'))
89
+ }
90
+ }
91
+
92
+ // Step 3: check /admin reachability.
93
+ // Use URL extracted from deploy output; fall back to worker name from wrangler.jsonc.
94
+ if (args.skipCheck) {
95
+ console.log(pc.dim('\n [3/3] Skipping admin check (--skip-check)\n'))
96
+ return
97
+ }
98
+
99
+ const adminBase = deployedUrl ?? (() => {
100
+ const workerName = readWorkerName(findWranglerConfig())
101
+ // We can't reliably construct the full workers.dev subdomain without knowing the account,
102
+ // so only use the name-based URL as a fallback when nothing better is available.
103
+ return workerName ? `https://${workerName}.workers.dev` : null
104
+ })()
105
+
106
+ if (!adminBase) {
107
+ console.log(pc.dim('\n [3/3] Could not determine worker URL — skipping admin check\n'))
108
+ console.log(pc.dim(' The deployed URL is printed by wrangler above. Open <url>/admin to verify.\n'))
109
+ return
110
+ }
111
+
112
+ console.log(pc.dim(`\n [3/3] Checking ${adminBase}/admin…\n`))
113
+ const { ok, status } = await checkAdmin(adminBase)
114
+
115
+ if (ok) {
116
+ console.log(pc.green(` ✓ Admin reachable at: ${adminBase}/admin\n`))
117
+ } else {
118
+ const statusStr = status != null ? ` (HTTP ${status})` : ''
119
+ console.log(pc.yellow(` ⚠ Admin returned an error${statusStr} at: ${adminBase}/admin\n`))
120
+ console.log(pc.dim(' The database may not be fully initialized.'))
121
+ console.log(pc.cyan(' → Run: npx beech init --db --remote\n'))
122
+ }
123
+ }
@@ -0,0 +1,540 @@
1
+ import pc from 'picocolors'
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { createInterface } from 'node:readline/promises'
4
+ import { resolve, basename } from 'node:path'
5
+ import { spawnSync } from 'node:child_process'
6
+ import { findWranglerConfig, resolveDbName, executeD1File, queryD1, type WranglerOptions } from '../lib/wrangler.js'
7
+
8
+ // System tables created by the base schema migration (0000_v040_base.sql).
9
+ // Used to detect whether the DB has been initialised.
10
+ const SYSTEM_TABLES = [
11
+ 'users',
12
+ 'refresh_tokens',
13
+ 'password_reset_tokens',
14
+ 'public_idempotency_keys',
15
+ 'analytics',
16
+ 'system_stats',
17
+ 'activity_logs',
18
+ 'notifications',
19
+ 'media_objects',
20
+ 'content_event_log',
21
+ ]
22
+
23
+ // Embedded copy of 0000_v040_base.sql — all DDL uses CREATE TABLE IF NOT EXISTS,
24
+ // so this is safe to re-run against an already-initialised database.
25
+ const BASE_SCHEMA_SQL = `
26
+ CREATE TABLE IF NOT EXISTS users (
27
+ id TEXT NOT NULL PRIMARY KEY,
28
+ email TEXT NOT NULL UNIQUE,
29
+ password_hash TEXT NOT NULL,
30
+ role TEXT NOT NULL DEFAULT 'editor' CHECK (role IN ('admin', 'editor')),
31
+ name TEXT,
32
+ avatar_url TEXT,
33
+ notification_prefs TEXT NOT NULL DEFAULT '{}',
34
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
35
+ );
36
+
37
+ CREATE TABLE IF NOT EXISTS refresh_tokens (
38
+ id TEXT NOT NULL PRIMARY KEY,
39
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
40
+ token_hash TEXT NOT NULL,
41
+ expires_at INTEGER NOT NULL,
42
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
43
+ revoked_at INTEGER DEFAULT NULL
44
+ );
45
+
46
+ CREATE INDEX IF NOT EXISTS idx_refresh_user ON refresh_tokens(user_id);
47
+ CREATE INDEX IF NOT EXISTS idx_refresh_hash ON refresh_tokens(token_hash);
48
+ CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens(expires_at);
49
+
50
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
51
+ id TEXT NOT NULL PRIMARY KEY,
52
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
53
+ token_hash TEXT NOT NULL,
54
+ expires_at INTEGER NOT NULL,
55
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
56
+ used_at INTEGER DEFAULT NULL
57
+ );
58
+
59
+ CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
60
+ CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
61
+
62
+ CREATE TABLE IF NOT EXISTS public_idempotency_keys (
63
+ idempotency_key TEXT NOT NULL PRIMARY KEY,
64
+ request_fingerprint TEXT NOT NULL,
65
+ response_status INTEGER NOT NULL,
66
+ response_body TEXT NOT NULL,
67
+ created_at INTEGER NOT NULL,
68
+ expires_at INTEGER NOT NULL
69
+ );
70
+
71
+ CREATE INDEX IF NOT EXISTS idx_idempotency_expires ON public_idempotency_keys(expires_at);
72
+
73
+ CREATE TABLE IF NOT EXISTS analytics (
74
+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
75
+ day_ts INTEGER NOT NULL,
76
+ metric TEXT NOT NULL,
77
+ seed TEXT NOT NULL DEFAULT '',
78
+ value INTEGER NOT NULL DEFAULT 0,
79
+ UNIQUE(day_ts, metric, seed)
80
+ );
81
+
82
+ CREATE INDEX IF NOT EXISTS idx_analytics_day ON analytics(day_ts);
83
+ CREATE INDEX IF NOT EXISTS idx_analytics_seed ON analytics(seed, day_ts);
84
+
85
+ CREATE TABLE IF NOT EXISTS system_stats (
86
+ id TEXT NOT NULL PRIMARY KEY,
87
+ value TEXT NOT NULL
88
+ );
89
+
90
+ INSERT OR IGNORE INTO system_stats (id, value) VALUES ('total_storage_bytes', '0');
91
+
92
+ CREATE TABLE IF NOT EXISTS activity_logs (
93
+ id TEXT NOT NULL PRIMARY KEY,
94
+ user_id TEXT NOT NULL,
95
+ user_email TEXT NOT NULL,
96
+ user_name TEXT,
97
+ action TEXT NOT NULL,
98
+ entity_type TEXT NOT NULL,
99
+ entity_id TEXT NOT NULL,
100
+ entity_slug TEXT,
101
+ details TEXT,
102
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
103
+ );
104
+
105
+ CREATE INDEX IF NOT EXISTS idx_activity_user ON activity_logs(user_id);
106
+ CREATE INDEX IF NOT EXISTS idx_activity_created ON activity_logs(created_at);
107
+
108
+ CREATE TABLE IF NOT EXISTS notifications (
109
+ id TEXT NOT NULL PRIMARY KEY,
110
+ title TEXT NOT NULL,
111
+ message TEXT NOT NULL,
112
+ type TEXT NOT NULL DEFAULT 'info' CHECK (type IN ('info', 'warning', 'error')),
113
+ is_read INTEGER NOT NULL DEFAULT 0 CHECK (is_read IN (0, 1)),
114
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
115
+ );
116
+
117
+ CREATE INDEX IF NOT EXISTS idx_notifications_created ON notifications(created_at);
118
+ CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(is_read);
119
+
120
+ CREATE TABLE IF NOT EXISTS media_objects (
121
+ key TEXT NOT NULL PRIMARY KEY,
122
+ filename TEXT NOT NULL,
123
+ mime_type TEXT NOT NULL,
124
+ size_bytes INTEGER NOT NULL,
125
+ uploaded_by TEXT NOT NULL DEFAULT '',
126
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
127
+ );
128
+
129
+ CREATE INDEX IF NOT EXISTS idx_media_user ON media_objects(uploaded_by);
130
+ CREATE INDEX IF NOT EXISTS idx_media_created ON media_objects(created_at DESC);
131
+
132
+ CREATE TABLE IF NOT EXISTS content_event_log (
133
+ id TEXT NOT NULL PRIMARY KEY,
134
+ schema_slug TEXT NOT NULL,
135
+ entry_id TEXT NOT NULL,
136
+ action TEXT NOT NULL CHECK (action IN ('create', 'update', 'delete')),
137
+ user_id TEXT,
138
+ details TEXT,
139
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
140
+ );
141
+
142
+ CREATE INDEX IF NOT EXISTS idx_event_log_schema_slug ON content_event_log(schema_slug);
143
+ CREATE INDEX IF NOT EXISTS idx_event_log_created_at ON content_event_log(created_at DESC);
144
+ CREATE INDEX IF NOT EXISTS idx_event_log_entry_id ON content_event_log(entry_id);
145
+ `.trim()
146
+
147
+ const PLACEHOLDER_DB_IDS = [
148
+ 'INCOLLA_QUI_IL_TUO_ID_D1',
149
+ 'FILL_IN_YOUR_D1_DATABASE_ID',
150
+ 'YOUR_D1_DATABASE_ID',
151
+ ]
152
+
153
+ export interface InitOptions {
154
+ initDb: boolean
155
+ local: boolean
156
+ db?: string
157
+ }
158
+
159
+ function checkWranglerAuth(): boolean {
160
+ const result = spawnSync('npx', ['wrangler', 'whoami', '--json'], {
161
+ encoding: 'utf-8',
162
+ cwd: process.cwd(),
163
+ shell: true,
164
+ })
165
+ return result.status === 0
166
+ }
167
+
168
+ function checkWranglerPlaceholders(configPath: string): string[] {
169
+ try {
170
+ const raw = readFileSync(configPath, 'utf-8')
171
+ const stripped = raw
172
+ .replace(/\/\/[^\n]*/g, '')
173
+ .replace(/\/\*[\s\S]*?\*\//g, '')
174
+ const parsed = JSON.parse(stripped)
175
+ const bindings: { database_id?: string; database_name?: string }[] = parsed?.d1_databases ?? []
176
+ const issues: string[] = []
177
+ for (const b of bindings) {
178
+ const id = b.database_id ?? ''
179
+ if (!id || PLACEHOLDER_DB_IDS.includes(id)) {
180
+ issues.push(`d1_databases[0].database_id is "${id || '(empty)'}"`)
181
+ }
182
+ }
183
+ return issues
184
+ } catch {
185
+ return []
186
+ }
187
+ }
188
+
189
+ function readProjectName(configPath: string | null): string {
190
+ if (!configPath) return basename(process.cwd())
191
+ try {
192
+ const raw = readFileSync(configPath, 'utf-8')
193
+ const stripped = raw.replace(/\/\/[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '')
194
+ const parsed = JSON.parse(stripped)
195
+ return (parsed?.name as string | undefined) || basename(process.cwd())
196
+ } catch {
197
+ return basename(process.cwd())
198
+ }
199
+ }
200
+
201
+ function readBucketName(configPath: string | null): string | null {
202
+ if (!configPath) return null
203
+ try {
204
+ const raw = readFileSync(configPath, 'utf-8')
205
+ const stripped = raw.replace(/\/\/[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '')
206
+ const parsed = JSON.parse(stripped)
207
+ const buckets: { bucket_name?: string }[] = parsed?.r2_buckets ?? []
208
+ return buckets[0]?.bucket_name ?? null
209
+ } catch {
210
+ return null
211
+ }
212
+ }
213
+
214
+ function createD1Database(dbName: string): string | null {
215
+ const result = spawnSync('npx', ['wrangler', 'd1', 'create', dbName, '--json'], {
216
+ encoding: 'utf-8',
217
+ cwd: process.cwd(),
218
+ shell: true,
219
+ stdio: ['inherit', 'pipe', 'pipe'],
220
+ })
221
+ if (result.status !== 0) return null
222
+ try {
223
+ const parsed = JSON.parse(result.stdout)
224
+ return (parsed?.uuid ?? parsed?.database_id ?? null) as string | null
225
+ } catch {
226
+ return null
227
+ }
228
+ }
229
+
230
+ function createR2Bucket(bucketName: string): boolean {
231
+ const result = spawnSync('npx', ['wrangler', 'r2', 'bucket', 'create', bucketName], {
232
+ stdio: 'inherit',
233
+ cwd: process.cwd(),
234
+ shell: true,
235
+ })
236
+ return result.status === 0
237
+ }
238
+
239
+ function patchWranglerConfig(configPath: string, dbId: string): boolean {
240
+ try {
241
+ let raw = readFileSync(configPath, 'utf-8')
242
+ for (const placeholder of PLACEHOLDER_DB_IDS) {
243
+ raw = raw.split(placeholder).join(dbId)
244
+ }
245
+ raw = raw.replace(/"database_id"\s*:\s*""/g, `"database_id": "${dbId}"`)
246
+ writeFileSync(configPath, raw, 'utf-8')
247
+ return true
248
+ } catch {
249
+ return false
250
+ }
251
+ }
252
+
253
+ function printManualDbInstructions(): void {
254
+ console.log(pc.dim('\n Update your D1 database_id in wrangler.jsonc,'))
255
+ console.log(pc.dim(' or create a new database with:'))
256
+ console.log(pc.cyan('\n → Run: npx wrangler d1 create my-project-db'))
257
+ console.log(pc.cyan(' → Then: npx beech init --db\n'))
258
+ }
259
+
260
+ function echoApiKeys(configPath: string | null | undefined): void {
261
+ if (!configPath) return
262
+ try {
263
+ const raw = readFileSync(configPath, 'utf-8')
264
+ const stripped = raw
265
+ .replace(/\/\/[^\n]*/g, '')
266
+ .replace(/\/\*[\s\S]*?\*\//g, '')
267
+ const parsed = JSON.parse(stripped)
268
+ const vars: Record<string, string> = parsed?.vars ?? {}
269
+ const readKey = vars['PUBLIC_READ_API_KEY']
270
+ const writeKey = vars['PUBLIC_WRITE_API_KEY']
271
+ if (!readKey && !writeKey) return
272
+ console.log(pc.dim(' API keys detected in wrangler.jsonc:\n'))
273
+ if (readKey) {
274
+ const masked = readKey.length > 8 ? readKey.slice(0, 4) + '****' + readKey.slice(-4) : '****'
275
+ console.log(pc.dim(` PUBLIC_READ_API_KEY = ${masked}`))
276
+ }
277
+ if (writeKey) {
278
+ const masked = writeKey.length > 8 ? writeKey.slice(0, 4) + '****' + writeKey.slice(-4) : '****'
279
+ console.log(pc.dim(` PUBLIC_WRITE_API_KEY = ${masked}`))
280
+ }
281
+ console.log(pc.dim('\n Use these in your frontend as the X-API-Key header.\n'))
282
+ } catch {
283
+ // wrangler.jsonc may be missing or malformed — skip silently
284
+ }
285
+ }
286
+
287
+ function checkFiles(cwd: string, checkDevVars: boolean): boolean {
288
+ let ok = true
289
+
290
+ const workerExists = existsSync(resolve(cwd, 'worker.ts')) || existsSync(resolve(cwd, 'worker.js'))
291
+ if (!workerExists) {
292
+ console.log(pc.red(' ✗ worker.ts — missing (required)'))
293
+ ok = false
294
+ } else {
295
+ console.log(pc.green(' ✓ worker.ts'))
296
+ }
297
+
298
+ const configPath = findWranglerConfig()
299
+ const configInCwd = configPath &&
300
+ (configPath === resolve(cwd, 'wrangler.jsonc') ||
301
+ configPath === resolve(cwd, 'wrangler.json') ||
302
+ configPath === resolve(cwd, 'wrangler.toml'))
303
+
304
+ if (!configInCwd) {
305
+ console.log(pc.red(' ✗ wrangler.jsonc — missing (required)'))
306
+ ok = false
307
+ } else {
308
+ console.log(pc.green(` ✓ ${basename(configPath!)}`))
309
+ }
310
+
311
+ const seedsExists =
312
+ existsSync(resolve(cwd, 'seeds.ts')) ||
313
+ existsSync(resolve(cwd, 'seeds.js')) ||
314
+ existsSync(resolve(cwd, 'seed.ts')) ||
315
+ existsSync(resolve(cwd, 'seed.js'))
316
+
317
+ if (!seedsExists) {
318
+ console.log(pc.yellow(' ⚠ seeds.ts — missing (create it, then run beech seed:load)'))
319
+ } else {
320
+ console.log(pc.green(' ✓ seeds.ts'))
321
+ }
322
+
323
+ if (checkDevVars) {
324
+ if (!existsSync(resolve(cwd, '.dev.vars'))) {
325
+ console.log(pc.dim(' ○ .dev.vars — not found (optional: only needed for production R2 credentials)'))
326
+ } else {
327
+ console.log(pc.green(' ✓ .dev.vars'))
328
+ }
329
+ }
330
+
331
+ return ok
332
+ }
333
+
334
+ function printNextSteps(local: boolean): void {
335
+ const localFlag = local ? ' --local' : ''
336
+ console.log(pc.dim(' Next steps:'))
337
+ console.log(pc.cyan(` 1. npx beech seed:load${localFlag}`))
338
+ console.log(pc.dim(' → create content tables from seeds.ts'))
339
+ console.log(pc.cyan(' 2. npx wrangler dev'))
340
+ console.log(pc.dim(' → start API + dashboard'))
341
+ console.log(pc.dim(' 3. Open http://localhost:8789/admin\n'))
342
+ }
343
+
344
+ function getExistingTables(options: WranglerOptions): string[] | null {
345
+ try {
346
+ const rows = queryD1<{ name: string }>(
347
+ `SELECT name FROM sqlite_master WHERE type='table'`,
348
+ options
349
+ )
350
+ return rows.map(r => r.name)
351
+ } catch {
352
+ return null
353
+ }
354
+ }
355
+
356
+ export async function init(args: InitOptions): Promise<void> {
357
+ const cwd = process.cwd()
358
+
359
+ console.log(pc.cyan('\n beech init — project check\n'))
360
+
361
+ const filesOk = checkFiles(cwd, args.local)
362
+
363
+ if (!filesOk) {
364
+ console.log(pc.red('\n ✗ Required files missing\n'))
365
+ console.log(pc.dim(' Fix the errors above before initialising the database.'))
366
+ console.log(pc.cyan('\n → See: https://beechcms.dev/docs/getting-started\n'))
367
+ process.exit(1)
368
+ }
369
+
370
+ console.log(pc.green('\n All required files present.\n'))
371
+
372
+ if (!args.initDb) {
373
+ echoApiKeys(findWranglerConfig())
374
+ const localFlag = args.local ? ' --local' : ''
375
+ console.log(pc.dim(' Next steps:'))
376
+ console.log(pc.dim(` 1. npx beech init --db${localFlag} # initialise D1 database`))
377
+ console.log(pc.dim(` 2. npx beech seed:load${localFlag} # create content tables`))
378
+ console.log(pc.dim(' 3. npx wrangler dev # start API + dashboard'))
379
+ console.log(pc.dim(' 4. Open http://localhost:8789/admin\n'))
380
+ return
381
+ }
382
+
383
+ // --- Database initialisation ---
384
+ const configPath = findWranglerConfig()
385
+
386
+ // Check for placeholder database_id before touching the DB
387
+ if (configPath) {
388
+ const placeholders = checkWranglerPlaceholders(configPath)
389
+ if (placeholders.length > 0) {
390
+ console.log(pc.yellow(' ⚠ wrangler.jsonc contains placeholder values:\n'))
391
+ for (const issue of placeholders) {
392
+ console.log(pc.yellow(` - ${issue}`))
393
+ }
394
+
395
+ if (process.stdin.isTTY) {
396
+ // Interactive: offer auto-creation of D1 + R2
397
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
398
+ let autoCreate = false
399
+ try {
400
+ const answer = (await rl.question(
401
+ pc.cyan('\n → Create a new D1 database (and R2 bucket) on Cloudflare automatically? (Y/n): ')
402
+ )).trim().toLowerCase()
403
+ autoCreate = !answer || answer === 'y' || answer === 'yes'
404
+ } finally {
405
+ rl.close()
406
+ }
407
+
408
+ if (autoCreate) {
409
+ // Auth required for resource creation
410
+ const authed = checkWranglerAuth()
411
+ if (!authed) {
412
+ console.log(pc.red('\n ✗ Not logged in to Cloudflare\n'))
413
+ console.log(pc.dim(' BeechCMS needs access to your Cloudflare account to create the database.'))
414
+ console.log(pc.cyan('\n → Run: npx wrangler login'))
415
+ console.log(pc.cyan(' → Then: npx beech init --db\n'))
416
+ process.exit(1)
417
+ }
418
+
419
+ const projectName = readProjectName(configPath)
420
+ const dbName = `${projectName}-db`
421
+ const bucketName = readBucketName(configPath) || `${projectName}-media`
422
+
423
+ console.log(pc.dim(`\n Creating D1 database "${dbName}"…`))
424
+ const dbId = createD1Database(dbName)
425
+ if (!dbId) {
426
+ console.log(pc.red('\n ✗ Failed to create D1 database\n'))
427
+ console.log(pc.dim(' Create it manually and retry:'))
428
+ console.log(pc.cyan(`\n → Run: npx wrangler d1 create ${dbName}`))
429
+ console.log(pc.cyan(' → Then: npx beech init --db\n'))
430
+ process.exit(1)
431
+ }
432
+ console.log(pc.green(` ✓ D1 database created (id: ${dbId})`))
433
+
434
+ console.log(pc.dim(`\n Creating R2 bucket "${bucketName}"…`))
435
+ const r2Ok = createR2Bucket(bucketName)
436
+ if (r2Ok) {
437
+ console.log(pc.green(` ✓ R2 bucket "${bucketName}" created`))
438
+ } else {
439
+ console.log(pc.yellow(` ⚠ R2 bucket creation failed (may already exist — continuing)`))
440
+ }
441
+
442
+ console.log(pc.dim('\n Updating wrangler.jsonc…'))
443
+ const patched = patchWranglerConfig(configPath, dbId)
444
+ if (patched) {
445
+ console.log(pc.green(' ✓ wrangler.jsonc updated\n'))
446
+ } else {
447
+ console.log(pc.yellow(` ⚠ Could not update wrangler.jsonc automatically\n`))
448
+ console.log(pc.dim(` Set database_id = "${dbId}" in wrangler.jsonc manually, then retry:`))
449
+ console.log(pc.cyan(' → Run: npx beech init --db\n'))
450
+ process.exit(1)
451
+ }
452
+ // Fall through to continue DB initialization with the newly created database
453
+ } else {
454
+ printManualDbInstructions()
455
+ process.exit(1)
456
+ }
457
+ } else {
458
+ printManualDbInstructions()
459
+ process.exit(1)
460
+ }
461
+ }
462
+ }
463
+
464
+ // For remote operations, verify Cloudflare auth before attempting any wrangler calls
465
+ if (!args.local) {
466
+ const authed = checkWranglerAuth()
467
+ if (!authed) {
468
+ console.log(pc.red(' ✗ Not logged in to Cloudflare\n'))
469
+ console.log(pc.dim(' BeechCMS needs access to your Cloudflare account to manage the D1 database.'))
470
+ console.log(pc.cyan('\n → Run: npx wrangler login'))
471
+ console.log(pc.cyan(' → Then: npx beech init --db\n'))
472
+ process.exit(1)
473
+ }
474
+ }
475
+
476
+ const db = args.db ?? resolveDbName(configPath)
477
+ const options: WranglerOptions = { db, local: args.local, configPath }
478
+
479
+ console.log(pc.cyan(` Checking database "${db}" (${args.local ? 'local' : 'remote'})…\n`))
480
+
481
+ const existingTables = getExistingTables(options)
482
+ const missingTables = SYSTEM_TABLES.filter(t => !existingTables?.includes(t))
483
+
484
+ // Remote mode: verification only — do not auto-apply schema.
485
+ // In production, system tables are created by `wrangler deploy` migrations.
486
+ if (!args.local) {
487
+ if (existingTables === null) {
488
+ console.log(pc.red(' ✗ Remote database unreachable\n'))
489
+ console.log(pc.dim(' Most likely causes:'))
490
+ console.log(pc.dim(' - Wrong database_id in wrangler.jsonc'))
491
+ console.log(pc.dim(' - Worker not yet deployed'))
492
+ console.log(pc.cyan('\n → Fix: Update d1_databases.database_id in wrangler.jsonc'))
493
+ console.log(pc.cyan(' → Then: npm run deploy\n'))
494
+ process.exit(1)
495
+ }
496
+
497
+ if (missingTables.length > 0) {
498
+ console.log(pc.yellow(` ⚠ Missing system tables: ${missingTables.join(', ')}\n`))
499
+ console.log(pc.dim(' Most likely causes:'))
500
+ console.log(pc.dim(' - Wrong database_id in wrangler.jsonc'))
501
+ console.log(pc.dim(' - Migrations did not run during deploy'))
502
+ console.log(pc.cyan('\n → Fix: Update d1_databases.database_id in wrangler.jsonc'))
503
+ console.log(pc.cyan(' → Then: npm run deploy\n'))
504
+ process.exit(1)
505
+ }
506
+
507
+ for (const table of SYSTEM_TABLES) {
508
+ console.log(pc.green(` ✓ ${table}`))
509
+ }
510
+ console.log(pc.green('\n All system tables present. Remote database is initialized.\n'))
511
+ return
512
+ }
513
+
514
+ // Local mode: apply schema if tables are missing.
515
+ if (existingTables === null) {
516
+ console.log(pc.yellow(' Database unreachable or not yet created — applying base schema…\n'))
517
+ } else if (missingTables.length === 0) {
518
+ console.log(pc.green(' ✓ All system tables present. Database already initialised.\n'))
519
+ printNextSteps(args.local)
520
+ return
521
+ } else {
522
+ console.log(pc.yellow(` Missing system tables: ${missingTables.join(', ')}`))
523
+ console.log(pc.cyan('\n Applying base schema…\n'))
524
+ }
525
+
526
+ const ok = executeD1File(BASE_SCHEMA_SQL, options)
527
+ if (!ok) {
528
+ console.log(pc.red('\n ✗ Database initialisation failed\n'))
529
+ console.log(pc.dim(' wrangler reported an error above.'))
530
+ console.log(pc.cyan('\n → Run: npx beech init --db --local\n'))
531
+ process.exit(1)
532
+ }
533
+
534
+ console.log(pc.green('\n ✓ worker.ts'))
535
+ console.log(pc.green(` ✓ ${configPath ? basename(configPath) : 'wrangler.jsonc'}`))
536
+ console.log(pc.green(' ✓ seeds.ts'))
537
+ console.log(pc.green(' ✓ Local D1 system tables ready\n'))
538
+ echoApiKeys(configPath)
539
+ printNextSteps(args.local)
540
+ }