@beechcms/cms 0.7.0 → 0.8.1

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/bin/create.mjs CHANGED
@@ -1,457 +1,391 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
-
4
- import * as p from '@clack/prompts'
5
- import pc from 'picocolors'
6
- import { execSync } from 'node:child_process'
7
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
8
- import { resolve, join } from 'node:path'
9
- import { randomBytes } from 'node:crypto'
10
- import { fileURLToPath } from 'node:url'
11
- import { dirname } from 'node:path'
12
-
13
- const __dirname = dirname(fileURLToPath(import.meta.url))
14
-
15
- // ── Template registry ─────────────────────────────────────────────────────────
16
-
17
- const TEMPLATES = {
18
- blog: {
19
- label: 'Blog',
20
- hint: 'posts with rich text, cover image, tags and authors',
21
- file: 'blog.ts',
22
- registryEntries: ['posts: POST_SEED', 'authors: AUTHOR_SEED'],
23
- },
24
- gallery: {
25
- label: 'Gallery',
26
- hint: 'media items with image, tags and featured flag',
27
- file: 'gallery.ts',
28
- registryEntries: ['gallery: GALLERY_SEED'],
29
- },
30
- contact: {
31
- label: 'Contact',
32
- hint: 'public form submissions with masked email and read status',
33
- file: 'contact.ts',
34
- registryEntries: ['messages: MESSAGE_SEED'],
35
- },
36
- commerce: {
37
- label: 'Commerce',
38
- hint: 'e-commerce product catalog with prices, inventory and ratings',
39
- file: 'commerce.ts',
40
- registryEntries: ['products: PRODUCT_SEED', 'reviews: REVIEW_SEED'],
41
- },
42
- tasks: {
43
- label: 'Tasks',
44
- hint: 'project management tasks with progress slider',
45
- file: 'tasks.ts',
46
- registryEntries: ['tasks: TASK_SEED'],
47
- },
48
- }
49
-
50
- function readTemplate(filename) {
51
- return readFileSync(join(__dirname, 'templates', filename), 'utf8')
52
- }
53
-
54
- function buildSeedsFile(selectedKeys) {
55
- const header = `import type { Seed } from '@beechcms/core'\n\n`
56
-
57
- if (selectedKeys.length === 0) {
58
- const example = readFileSync(join(__dirname, 'templates', 'empty.ts'), 'utf8')
59
- return (
60
- header +
61
- example +
62
- '\nexport const SEED_REGISTRY: Record<string, Seed> = {}\n\n' +
63
- 'export function getSeed(slug: string): Seed | null {\n' +
64
- ' return SEED_REGISTRY[slug] ?? null\n' +
65
- '}\n'
66
- )
67
- }
68
-
69
- const blocks = selectedKeys.map((key) =>
70
- readFileSync(join(__dirname, 'templates', TEMPLATES[key].file), 'utf8')
71
- )
72
-
73
- const registryEntries = selectedKeys.flatMap((key) => TEMPLATES[key].registryEntries)
74
- const registry =
75
- 'export const SEED_REGISTRY: Record<string, Seed> = {\n' +
76
- registryEntries.map((e) => ` ${e},`).join('\n') +
77
- '\n}\n'
78
-
79
- const getSeed =
80
- '\nexport function getSeed(slug: string): Seed | null {\n' +
81
- ' return SEED_REGISTRY[slug] ?? null\n' +
82
- '}\n'
83
-
84
- return header + blocks.join('\n') + '\n' + registry + getSeed
85
- }
86
-
87
- // ── Helpers ───────────────────────────────────────────────────────────────────
88
-
89
- function generateSecret(bytes = 32) {
90
- return randomBytes(bytes).toString('hex')
91
- }
92
-
93
- function writeFile(path, content) {
94
- writeFileSync(path, content, 'utf8')
95
- }
96
-
97
- function buildWorkerTs() {
98
- return `/// <reference types="@cloudflare/workers-types" />
99
- import { createBeechApp } from '@beechcms/api'
100
- import { SEED_REGISTRY } from './seeds'
101
-
102
- export default createBeechApp({ seeds: Object.values(SEED_REGISTRY) })
103
- `
104
- }
105
-
106
- function buildSeedsTs(selectedKeys) {
107
- return buildSeedsFile(selectedKeys)
108
- }
109
-
110
- function getCurrentVersion() {
111
- try {
112
- const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8'))
113
- return `^${pkg.version}`
114
- } catch {
115
- return '^0.6.6'
116
- }
117
- }
118
-
119
- function buildPackageJson(name) {
120
- const version = getCurrentVersion()
121
- return JSON.stringify({
122
- name,
123
- version: '0.1.0',
124
- private: true,
125
- type: 'module',
126
- scripts: {
127
- dev: 'wrangler dev --port 8789',
128
- deploy: 'wrangler deploy --minify',
129
- 'seed:load': 'npx beech seed:load',
130
- 'seed:load:local': 'npx beech seed:load --local',
131
- 'db:migrate:local': 'wrangler d1 migrations apply ' + name + '-db --local',
132
- 'db:reset:local': 'node -e "require(\'fs\').rmSync(\'.wrangler/state\',{recursive:true,force:true})" && npm run db:migrate:local',
133
- },
134
- dependencies: {
135
- '@beechcms/api': version,
136
- '@beechcms/core': version,
137
- },
138
- devDependencies: {
139
- '@cloudflare/workers-types': '^4.0.0',
140
- wrangler: '^4.0.0',
141
- typescript: '^5.0.0',
142
- },
143
- }, null, 2) + '\n'
144
- }
145
-
146
- function buildWranglerJsonc(cfg) {
147
- return `{
148
- "name": "${cfg.name}-api",
149
- "main": "worker.ts",
150
- "compatibility_date": "2025-01-01",
151
-
152
- "vars": {
153
- "JWT_SECRET": "${cfg.jwtSecret}",
154
- "CORS_ORIGINS": "${cfg.corsOrigins}",
155
- "PUBLIC_READ_API_KEY": "${cfg.publicReadKey}",
156
- "PUBLIC_WRITE_API_KEY": "${cfg.publicWriteKey}",
157
- "APP_URL": "${cfg.appUrl || 'http://localhost:5173'}"
158
- },
159
-
160
- "assets": {
161
- "binding": "ASSETS",
162
- "directory": "node_modules/@beechcms/api/assets/dashboard"
163
- },
164
-
165
- "d1_databases": [
166
- {
167
- "binding": "DB",
168
- "database_name": "${cfg.d1Name}",
169
- "database_id": "${cfg.d1Id}",
170
- "migrations_dir": "node_modules/@beechcms/api/migrations"
171
- }
172
- ],
173
-
174
- "r2_buckets": [
175
- {
176
- "binding": "MEDIA_BUCKET",
177
- "bucket_name": "${cfg.r2Bucket}"
178
- }
179
- ]
180
- }
181
- `
182
- }
183
-
184
- function buildDevVars(cloudflare) {
185
- if (cloudflare) {
186
- return [
187
- `R2_ACCESS_KEY_ID=${cloudflare.r2AccessKey}`,
188
- `R2_SECRET_ACCESS_KEY=${cloudflare.r2SecretKey}`,
189
- `R2_ENDPOINT=${cloudflare.r2Endpoint}`,
190
- `R2_BUCKET_NAME=${cloudflare.r2Bucket}`,
191
- ].join('\n') + '\n'
192
- }
193
- return [
194
- '# R2 credentials — only needed if you want production-like S3 media uploads locally.',
195
- '# For local development, media uploads work automatically via the Miniflare R2 binding.',
196
- '# Fill these in only when testing production media behaviour:',
197
- '# Guide: https://developers.cloudflare.com/r2/api/s3/tokens/',
198
- 'R2_ACCESS_KEY_ID=',
199
- 'R2_SECRET_ACCESS_KEY=',
200
- 'R2_ENDPOINT=https://<YOUR_ACCOUNT_ID>.r2.cloudflarestorage.com',
201
- 'R2_BUCKET_NAME=',
202
- ].join('\n') + '\n'
203
- }
204
-
205
- function buildTsConfig() {
206
- return JSON.stringify({
207
- compilerOptions: {
208
- target: 'ES2022',
209
- module: 'ES2022',
210
- moduleResolution: 'bundler',
211
- strict: true,
212
- types: ['@cloudflare/workers-types'],
213
- },
214
- include: ['*.ts'],
215
- }, null, 2) + '\n'
216
- }
217
-
218
- // ── Cloudflare prompts ────────────────────────────────────────────────────────
219
-
220
- async function askCloudflareConfig(name) {
221
- p.note(
222
- [
223
- 'You will need a free Cloudflare account with:',
224
- '',
225
- ` D1 database → ${pc.cyan('npx wrangler d1 create ' + name + '-db')}`,
226
- ` R2 bucket → ${pc.cyan('npx wrangler r2 bucket create ' + name + '-media')}`,
227
- '',
228
- 'Docs: https://developers.cloudflare.com/d1/',
229
- ' https://developers.cloudflare.com/r2/',
230
- ].join('\n'),
231
- 'Prerequisites'
232
- )
233
-
234
- const accountId = await p.text({
235
- message: 'Cloudflare Account ID',
236
- hint: 'dash.cloudflare.com → right sidebar → "Account ID"',
237
- validate: (v) => { if (!v.trim()) return 'Required' },
238
- })
239
- if (p.isCancel(accountId)) return null
240
-
241
- const d1Name = await p.text({
242
- message: 'D1 Database name',
243
- initialValue: `${name}-db`,
244
- validate: (v) => { if (!v.trim()) return 'Required' },
245
- })
246
- if (p.isCancel(d1Name)) return null
247
-
248
- const d1Id = await p.text({
249
- message: 'D1 Database ID',
250
- placeholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
251
- hint: `Run: npx wrangler d1 create ${d1Name} — copy the "database_id" from the output`,
252
- validate: (v) => { if (!v.trim()) return 'Required — create the D1 database first and paste its ID here' },
253
- })
254
- if (p.isCancel(d1Id)) return null
255
-
256
- const r2Bucket = await p.text({
257
- message: 'R2 Bucket name',
258
- initialValue: `${name}-media`,
259
- validate: (v) => { if (!v.trim()) return 'Required' },
260
- })
261
- if (p.isCancel(r2Bucket)) return null
262
-
263
- p.note(
264
- [
265
- 'Create an R2 API token:',
266
- ' Cloudflare Dashboard → R2 → "Manage R2 API Tokens"',
267
- ` → Create Token → Object Read & Write → bucket: ${r2Bucket}`,
268
- ].join('\n'),
269
- 'R2 credentials'
270
- )
271
-
272
- const r2AccessKey = await p.text({
273
- message: 'R2 Access Key ID',
274
- validate: (v) => { if (!v.trim()) return 'Required' },
275
- })
276
- if (p.isCancel(r2AccessKey)) return null
277
-
278
- const r2SecretKey = await p.password({
279
- message: 'R2 Secret Access Key',
280
- validate: (v) => { if (!v.trim()) return 'Required' },
281
- })
282
- if (p.isCancel(r2SecretKey)) return null
283
-
284
- const appUrl = await p.text({
285
- message: 'Production dashboard URL (for CORS)',
286
- placeholder: `https://cms.${name}.com`,
287
- hint: 'Leave empty to configure later in wrangler.jsonc',
288
- })
289
- if (p.isCancel(appUrl)) return null
290
-
291
- return {
292
- accountId: accountId.trim(),
293
- d1Name: d1Name.trim(),
294
- d1Id: d1Id.trim(),
295
- r2Bucket: r2Bucket.trim(),
296
- r2AccessKey: r2AccessKey.trim(),
297
- r2SecretKey: r2SecretKey.trim(),
298
- r2Endpoint: `https://${accountId.trim()}.r2.cloudflarestorage.com`,
299
- appUrl: appUrl?.trim() ?? '',
300
- }
301
- }
302
-
303
- // ── Main ──────────────────────────────────────────────────────────────────────
304
-
305
- async function main() {
306
- const argv = process.argv.slice(2)
307
- const silent = argv.includes('--yes') || argv.includes('-y') || !process.stdout.isTTY
308
-
309
- console.log()
310
- p.intro(pc.bgGreen(pc.black(' @beechcms/cms ')))
311
-
312
- let name, selectedTemplates, cloudflare
313
-
314
- if (silent) {
315
- // Non-interactive: use first positional arg or default name, skip Cloudflare
316
- const positional = argv.find((a) => !a.startsWith('-'))
317
- name = positional ?? 'my-beech-project'
318
- const withExamples = argv.includes('--with-examples') || argv.includes('--examples')
319
- selectedTemplates = withExamples ? ['blog'] : []
320
- cloudflare = null
321
- const examplesNote = withExamples ? ' (with blog example content types)' : ''
322
- console.log(pc.dim(` Running in non-interactive mode. Project name: ${name}${examplesNote}`))
323
- } else {
324
- // Project name
325
- const projectName = await p.text({
326
- message: 'Project name',
327
- placeholder: 'my-website',
328
- validate: (v) => {
329
- if (!v.trim()) return 'Required'
330
- if (!/^[a-z0-9][a-z0-9-]*$/.test(v.trim())) return 'Lowercase letters, numbers and hyphens only'
331
- },
332
- })
333
- if (p.isCancel(projectName)) { p.cancel('Cancelled'); process.exit(0) }
334
- name = projectName.trim()
335
-
336
- // Content types
337
- const tmpl = await p.multiselect({
338
- message: 'Which content types do you need?',
339
- hint: 'Space to select, Enter to confirm. You can add more later in seeds.ts',
340
- options: [
341
- { value: 'blog', label: 'Blog', hint: 'posts with rich text, cover image, tags and authors' },
342
- { value: 'gallery', label: 'Gallery', hint: 'media items with image, tags and featured flag' },
343
- { value: 'contact', label: 'Contact', hint: 'public form submissions with masked email and read status' },
344
- { value: 'commerce',label: 'Commerce',hint: 'e-commerce product catalog with prices, inventory and ratings' },
345
- { value: 'tasks', label: 'Tasks', hint: 'project management tasks with progress slider' },
346
- ],
347
- required: false,
348
- })
349
- if (p.isCancel(tmpl)) { p.cancel('Cancelled'); process.exit(0) }
350
- selectedTemplates = tmpl
351
-
352
- // Cloudflare now or later?
353
- const configureNow = await p.confirm({
354
- message: 'Configure Cloudflare credentials now?',
355
- hint: 'Choose "No" to scaffold the project and fill in the values later',
356
- initialValue: true,
357
- })
358
- if (p.isCancel(configureNow)) { p.cancel('Cancelled'); process.exit(0) }
359
-
360
- if (configureNow) {
361
- cloudflare = await askCloudflareConfig(name)
362
- if (!cloudflare) { p.cancel('Cancelled'); process.exit(0) }
363
- }
364
- }
365
-
366
- const targetDir = resolve(process.cwd(), name)
367
- if (existsSync(targetDir)) {
368
- p.cancel(`Directory '${name}' already exists. Choose a different name or delete the folder.`)
369
- process.exit(1)
370
- }
371
-
372
- const jwtSecret = generateSecret(32)
373
- const publicReadKey = generateSecret(16)
374
- const publicWriteKey = generateSecret(16)
375
-
376
- const corsOrigins = cloudflare
377
- ? ['http://localhost:5173', 'http://localhost:5174', cloudflare.appUrl]
378
- .filter(Boolean).join(',')
379
- : 'http://localhost:5173,http://localhost:5174'
380
-
381
- // Scaffold
382
- const s = p.spinner()
383
- s.start('Scaffolding project…')
384
-
385
- mkdirSync(targetDir, { recursive: true })
386
-
387
- writeFile(join(targetDir, 'seeds.ts'), buildSeedsTs(selectedTemplates))
388
- writeFile(join(targetDir, 'worker.ts'), buildWorkerTs())
389
- writeFile(join(targetDir, 'package.json'), buildPackageJson(name))
390
- writeFile(join(targetDir, 'tsconfig.json'), buildTsConfig())
391
- writeFile(join(targetDir, 'wrangler.jsonc'), buildWranglerJsonc({
392
- name,
393
- d1Name: cloudflare?.d1Name ?? `${name}-db`,
394
- d1Id: cloudflare?.d1Id ?? 'FILL_IN_YOUR_D1_DATABASE_ID',
395
- r2Bucket: cloudflare?.r2Bucket ?? `${name}-media`,
396
- jwtSecret,
397
- corsOrigins,
398
- publicReadKey,
399
- publicWriteKey,
400
- appUrl: cloudflare?.appUrl ?? '',
401
- }))
402
- writeFile(join(targetDir, '.dev.vars'), buildDevVars(cloudflare))
403
- writeFile(join(targetDir, '.gitignore'), '.wrangler\nnode_modules\n.dev.vars\ndist\n')
404
-
405
- s.stop('Project scaffolded')
406
-
407
- // Init git
408
- s.start('Initialising git repository…')
409
- try {
410
- execSync(`git -C "${targetDir}" init -q`, { stdio: 'pipe' })
411
- execSync(`git -C "${targetDir}" add -A`, { stdio: 'pipe' })
412
- execSync(`git -C "${targetDir}" commit -q -m "feat: initialise BeechCMS project"`, { stdio: 'pipe' })
413
- s.stop('Git initialised')
414
- } catch {
415
- s.stop('Git skipped (not available)')
416
- }
417
-
418
- const pendingConfig = !cloudflare
419
- const step = (n) => pc.bold(String(n + (pendingConfig ? 1 : 0)))
420
- console.log()
421
- p.note(
422
- [
423
- `${pc.bold('1. Enter the project')}`,
424
- ` ${pc.cyan('cd ' + name)}`,
425
- '',
426
- `${pc.bold('2. Install dependencies')}`,
427
- ` ${pc.cyan('npm install')}`,
428
- '',
429
- ...(pendingConfig ? [
430
- `${pc.bold('3. Complete Cloudflare configuration')} ${pc.yellow('← pending')}`,
431
- ` Edit ${pc.underline('wrangler.jsonc')} → fill in ${pc.yellow('database_id')} (D1) and ${pc.yellow('bucket_name')} (R2)`,
432
- ` Guide: https://developers.cloudflare.com/d1/`,
433
- ` ${pc.dim('Note: media uploads work locally without R2 credentials (.dev.vars optional)')}`,
434
- '',
435
- ] : []),
436
- `${step(3)}. Run local migrations`,
437
- ` ${pc.cyan('npm run db:migrate:local')}`,
438
- '',
439
- `${step(4)}. Start the dev server`,
440
- ` ${pc.cyan('npx wrangler dev')}`,
441
- ` Then open: ${pc.underline('http://localhost:8789/admin')}`,
442
- '',
443
- `${step(5)}. Deploy to production`,
444
- ` ${pc.cyan('npm run deploy')}`,
445
- '',
446
- `${pc.dim('Your content types are defined in seeds.ts')}`,
447
- `${pc.dim('JWT secret and API keys have been auto-generated.')}`,
448
- ].join('\n'),
449
- 'Next steps'
450
- )
451
- p.outro(pc.green(`✔ BeechCMS project ready — ${name}/`))
452
- }
453
-
454
- main().catch((err) => {
455
- console.error(err)
456
- process.exit(1)
457
- })
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+
4
+ import * as p from '@clack/prompts'
5
+ import pc from 'picocolors'
6
+ import { spawnSync, execSync } from 'node:child_process'
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
8
+ import { resolve, join } from 'node:path'
9
+ import { randomBytes } from 'node:crypto'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { dirname } from 'node:path'
12
+
13
+ const __dirname = dirname(fileURLToPath(import.meta.url))
14
+
15
+ // ── Helpers ───────────────────────────────────────────────────────────────────
16
+
17
+ function generateSecret(bytes = 32) {
18
+ return randomBytes(bytes).toString('hex')
19
+ }
20
+
21
+ function writeFile(path, content) {
22
+ writeFileSync(path, content, 'utf8')
23
+ }
24
+
25
+ function buildWorkerTs() {
26
+ return `/// <reference types="@cloudflare/workers-types" />
27
+ import { createBeechApp } from '@beechcms/api'
28
+
29
+ export default createBeechApp({ seeds: [] })
30
+ `
31
+ }
32
+
33
+ function getCurrentVersion() {
34
+ try {
35
+ const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8'))
36
+ return `^${pkg.version}`
37
+ } catch {
38
+ return '^0.6.6'
39
+ }
40
+ }
41
+
42
+ function buildPackageJson(name) {
43
+ const version = getCurrentVersion()
44
+ return JSON.stringify({
45
+ name,
46
+ version: '0.1.0',
47
+ private: true,
48
+ type: 'module',
49
+ scripts: {
50
+ dev: 'wrangler dev --port 8789',
51
+ deploy: 'wrangler deploy --minify',
52
+ 'db:migrate:local': 'wrangler d1 migrations apply ' + name + '-db --local',
53
+ 'db:reset:local': 'node -e "require(\'fs\').rmSync(\'.wrangler/state\',{recursive:true,force:true})" && npm run db:migrate:local',
54
+ },
55
+ dependencies: {
56
+ '@beechcms/api': version,
57
+ '@beechcms/core': version,
58
+ },
59
+ devDependencies: {
60
+ '@beechcms/cms': version,
61
+ '@cloudflare/workers-types': '^4.0.0',
62
+ wrangler: '^4.0.0',
63
+ typescript: '^5.0.0',
64
+ },
65
+ }, null, 2) + '\n'
66
+ }
67
+
68
+ function buildWranglerJsonc(cfg) {
69
+ return `{
70
+ "name": "${cfg.name}-api",
71
+ "main": "worker.ts",
72
+ "compatibility_date": "2025-01-01",
73
+ "compatibility_flags": ["nodejs_compat"],
74
+
75
+ "vars": {
76
+ "JWT_SECRET": "${cfg.jwtSecret}",
77
+ "CORS_ORIGINS": "${cfg.corsOrigins}",
78
+ "PUBLIC_READ_API_KEY": "${cfg.publicReadKey}",
79
+ "PUBLIC_WRITE_API_KEY": "${cfg.publicWriteKey}",
80
+ "APP_URL": "${cfg.appUrl || 'http://localhost:5173'}"
81
+ },
82
+
83
+ "assets": {
84
+ "binding": "ASSETS",
85
+ "directory": "node_modules/@beechcms/api/assets/dashboard"
86
+ },
87
+
88
+ "d1_databases": [
89
+ {
90
+ "binding": "DB",
91
+ "database_name": "${cfg.d1Name}",
92
+ "database_id": "${cfg.d1Id}",
93
+ "migrations_dir": "node_modules/@beechcms/api/migrations"
94
+ }
95
+ ],
96
+
97
+ "r2_buckets": [
98
+ {
99
+ "binding": "MEDIA_BUCKET",
100
+ "bucket_name": "${cfg.r2Bucket}"
101
+ }
102
+ ]
103
+ }
104
+ `
105
+ }
106
+
107
+ function buildDevVars(cloudflare) {
108
+ if (cloudflare) {
109
+ return [
110
+ `# Cloudflare R2 S3 credentials (required for direct client upload via Presigned URLs)`,
111
+ `# Guide: https://developers.cloudflare.com/r2/api/s3/tokens/`,
112
+ `R2_ACCESS_KEY_ID=${cloudflare.r2AccessKey}`,
113
+ `R2_SECRET_ACCESS_KEY=${cloudflare.r2SecretKey}`,
114
+ `R2_ENDPOINT=${cloudflare.r2Endpoint}`,
115
+ `R2_BUCKET_NAME=${cloudflare.r2Bucket}`,
116
+ ].join('\n') + '\n'
117
+ }
118
+ return [
119
+ '# Cloudflare R2 S3 credentials (required for direct client upload via Presigned URLs)',
120
+ '# Create an R2 API Token: Cloudflare Dashboard → R2 → "Manage R2 API Tokens" (Object Read & Write)',
121
+ '# Guide: https://developers.cloudflare.com/r2/api/s3/tokens/',
122
+ 'R2_ACCESS_KEY_ID=',
123
+ 'R2_SECRET_ACCESS_KEY=',
124
+ 'R2_ENDPOINT=https://<YOUR_ACCOUNT_ID>.r2.cloudflarestorage.com',
125
+ 'R2_BUCKET_NAME=',
126
+ ].join('\n') + '\n'
127
+ }
128
+
129
+ function buildTsConfig() {
130
+ return JSON.stringify({
131
+ compilerOptions: {
132
+ target: 'ES2022',
133
+ module: 'ES2022',
134
+ moduleResolution: 'bundler',
135
+ strict: true,
136
+ types: ['@cloudflare/workers-types'],
137
+ },
138
+ include: ['*.ts'],
139
+ }, null, 2) + '\n'
140
+ }
141
+
142
+ // ── Cloudflare prompts ────────────────────────────────────────────────────────
143
+
144
+ async function askCloudflareConfig(name) {
145
+ p.note(
146
+ [
147
+ 'You will need a free Cloudflare account with:',
148
+ '',
149
+ ` D1 database → ${pc.cyan('npx wrangler d1 create ' + name + '-db')}`,
150
+ ` R2 bucket → ${pc.cyan('npx wrangler r2 bucket create ' + name + '-media')}`,
151
+ '',
152
+ 'Docs: https://developers.cloudflare.com/d1/',
153
+ ' https://developers.cloudflare.com/r2/',
154
+ ].join('\n'),
155
+ 'Prerequisites'
156
+ )
157
+
158
+ const accountId = await p.text({
159
+ message: 'Cloudflare Account ID',
160
+ hint: 'dash.cloudflare.com → right sidebar → "Account ID"',
161
+ validate: (v) => { if (!v.trim()) return 'Required' },
162
+ })
163
+ if (p.isCancel(accountId)) return null
164
+
165
+ const autoCreate = await p.confirm({
166
+ message: `Auto-create Cloudflare D1 (${name}-db) and R2 (${name}-media) now?`,
167
+ hint: 'Runs `wrangler d1 create` and `wrangler r2 bucket create`',
168
+ initialValue: true,
169
+ })
170
+ if (p.isCancel(autoCreate)) return null
171
+
172
+ let d1Id = ''
173
+ const d1Name = `${name}-db`
174
+ const r2Bucket = `${name}-media`
175
+
176
+ if (autoCreate) {
177
+ const s = p.spinner()
178
+ s.start(`Creating D1 database: ${pc.bold(d1Name)}…`)
179
+ const d1Res = spawnSync('npx', ['wrangler', 'd1', 'create', d1Name], { encoding: 'utf-8', shell: true })
180
+ const d1Out = (d1Res.stdout || '') + (d1Res.stderr || '')
181
+ const idMatch = d1Out.match(/database_id\s*=\s*["']?([a-f0-9-]{36})["']?/i) ||
182
+ d1Out.match(/"database_id":\s*"([a-f0-9-]{36})"/i) ||
183
+ d1Out.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i)
184
+ if (idMatch) {
185
+ d1Id = idMatch[1]
186
+ s.stop(pc.green(`✓ D1 database ready (${d1Id})`))
187
+ } else {
188
+ s.stop(pc.yellow(`ℹ D1 status: ${d1Out.trim().slice(0, 100)}`))
189
+ }
190
+
191
+ s.start(`Creating R2 bucket: ${pc.bold(r2Bucket)}…`)
192
+ spawnSync('npx', ['wrangler', 'r2', 'bucket', 'create', r2Bucket], { encoding: 'utf-8', shell: true })
193
+ s.stop(pc.green(`✓ R2 bucket ready (${r2Bucket})`))
194
+ }
195
+
196
+ if (!d1Id) {
197
+ const d1IdInput = await p.text({
198
+ message: 'D1 Database ID',
199
+ placeholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
200
+ hint: `Run: npx wrangler d1 create ${d1Name} — paste the "database_id" here`,
201
+ validate: (v) => { if (!v.trim()) return 'Required — paste database_id from D1' },
202
+ })
203
+ if (p.isCancel(d1IdInput)) return null
204
+ d1Id = d1IdInput.trim()
205
+ }
206
+
207
+ p.note(
208
+ [
209
+ 'Direct client uploads use Presigned URLs (SigV4) to stream files directly to R2.',
210
+ 'Create an R2 API token:',
211
+ ' Cloudflare Dashboard → R2 → "Manage R2 API Tokens"',
212
+ ` → Create Token → Object Read & Write → bucket: ${r2Bucket}`,
213
+ 'Guide: https://developers.cloudflare.com/r2/api/s3/tokens/',
214
+ ].join('\n'),
215
+ 'R2 S3 Credentials (for Presigned URLs)'
216
+ )
217
+
218
+ const r2AccessKey = await p.text({
219
+ message: 'R2 Access Key ID',
220
+ validate: (v) => { if (!v.trim()) return 'Required' },
221
+ })
222
+ if (p.isCancel(r2AccessKey)) return null
223
+
224
+ const r2SecretKey = await p.password({
225
+ message: 'R2 Secret Access Key',
226
+ validate: (v) => { if (!v.trim()) return 'Required' },
227
+ })
228
+ if (p.isCancel(r2SecretKey)) return null
229
+
230
+ const appUrl = await p.text({
231
+ message: 'Production dashboard URL (for CORS)',
232
+ placeholder: `https://cms.${name}.com`,
233
+ hint: 'Leave empty to configure later in wrangler.jsonc',
234
+ })
235
+ if (p.isCancel(appUrl)) return null
236
+
237
+ return {
238
+ accountId: accountId.trim(),
239
+ d1Name: d1Name.trim(),
240
+ d1Id: d1Id.trim(),
241
+ r2Bucket: r2Bucket.trim(),
242
+ r2AccessKey: r2AccessKey.trim(),
243
+ r2SecretKey: r2SecretKey.trim(),
244
+ r2Endpoint: `https://${accountId.trim()}.r2.cloudflarestorage.com`,
245
+ appUrl: appUrl?.trim() ?? '',
246
+ }
247
+ }
248
+
249
+ // ── Main ──────────────────────────────────────────────────────────────────────
250
+
251
+ async function main() {
252
+ const argv = process.argv.slice(2)
253
+ const silent = argv.includes('--yes') || argv.includes('-y') || !process.stdout.isTTY
254
+
255
+ console.log()
256
+ p.intro(pc.bgGreen(pc.black(' @beechcms/cms ')))
257
+
258
+ let name, cloudflare
259
+
260
+ if (silent) {
261
+ // Non-interactive: use first positional arg or default name, skip Cloudflare
262
+ const positional = argv.find((a) => !a.startsWith('-'))
263
+ name = positional ?? 'my-beech-project'
264
+ cloudflare = null
265
+ console.log(pc.dim(` Running in non-interactive mode. Project name: ${name}`))
266
+ } else {
267
+ // Project name
268
+ const projectName = await p.text({
269
+ message: 'Project name',
270
+ placeholder: 'my-website',
271
+ validate: (v) => {
272
+ if (!v.trim()) return 'Required'
273
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(v.trim())) return 'Lowercase letters, numbers and hyphens only'
274
+ },
275
+ })
276
+ if (p.isCancel(projectName)) { p.cancel('Cancelled'); process.exit(0) }
277
+ name = projectName.trim()
278
+
279
+ // Cloudflare now or later?
280
+ const configureNow = await p.confirm({
281
+ message: 'Configure Cloudflare credentials now?',
282
+ hint: 'Choose "No" to scaffold the project and fill in the values later',
283
+ initialValue: true,
284
+ })
285
+ if (p.isCancel(configureNow)) { p.cancel('Cancelled'); process.exit(0) }
286
+
287
+ if (configureNow) {
288
+ cloudflare = await askCloudflareConfig(name)
289
+ if (!cloudflare) { p.cancel('Cancelled'); process.exit(0) }
290
+ }
291
+ }
292
+
293
+ const targetDir = resolve(process.cwd(), name)
294
+ if (existsSync(targetDir)) {
295
+ p.cancel(`Directory '${name}' already exists. Choose a different name or delete the folder.`)
296
+ process.exit(1)
297
+ }
298
+
299
+ const jwtSecret = generateSecret(32)
300
+ const publicReadKey = generateSecret(16)
301
+ const publicWriteKey = generateSecret(16)
302
+
303
+ const corsOrigins = cloudflare
304
+ ? ['http://localhost:5173', 'http://localhost:5174', cloudflare.appUrl]
305
+ .filter(Boolean).join(',')
306
+ : 'http://localhost:5173,http://localhost:5174'
307
+
308
+ // Scaffold
309
+ const s = p.spinner()
310
+ s.start('Scaffolding project…')
311
+
312
+ mkdirSync(targetDir, { recursive: true })
313
+
314
+ writeFile(join(targetDir, 'worker.ts'), buildWorkerTs())
315
+ writeFile(join(targetDir, 'package.json'), buildPackageJson(name))
316
+ writeFile(join(targetDir, 'tsconfig.json'), buildTsConfig())
317
+ writeFile(join(targetDir, 'wrangler.jsonc'), buildWranglerJsonc({
318
+ name,
319
+ d1Name: cloudflare?.d1Name ?? `${name}-db`,
320
+ d1Id: cloudflare?.d1Id ?? 'FILL_IN_YOUR_D1_DATABASE_ID',
321
+ r2Bucket: cloudflare?.r2Bucket ?? `${name}-media`,
322
+ jwtSecret,
323
+ corsOrigins,
324
+ publicReadKey,
325
+ publicWriteKey,
326
+ appUrl: cloudflare?.appUrl ?? '',
327
+ }))
328
+ writeFile(join(targetDir, '.dev.vars'), buildDevVars(cloudflare))
329
+ writeFile(join(targetDir, '.gitignore'), '.wrangler\nnode_modules\n.dev.vars\ndist\n')
330
+
331
+ s.stop('Project scaffolded')
332
+
333
+ // Init git
334
+ s.start('Initialising git repository…')
335
+ try {
336
+ execSync(`git -C "${targetDir}" init -q`, { stdio: 'pipe' })
337
+ execSync(`git -C "${targetDir}" add -A`, { stdio: 'pipe' })
338
+ execSync(`git -C "${targetDir}" commit -q -m "feat: initialise BeechCMS project"`, { stdio: 'pipe' })
339
+ s.stop('Git initialised')
340
+ } catch {
341
+ s.stop('Git skipped (not available)')
342
+ }
343
+
344
+ const pendingConfig = !cloudflare
345
+ const step = (n) => pc.bold(String(n + (pendingConfig ? 1 : 0)))
346
+ console.log()
347
+ p.note(
348
+ [
349
+ `${pc.bold('1. Enter the project')}`,
350
+ ` ${pc.cyan('cd ' + name)}`,
351
+ '',
352
+ `${pc.bold('2. Install dependencies')}`,
353
+ ` ${pc.cyan('npm install')}`,
354
+ '',
355
+ ...(pendingConfig ? [
356
+ `${pc.bold('3. Complete Cloudflare configuration')} ${pc.yellow('← pending')}`,
357
+ ` Edit ${pc.underline('wrangler.jsonc')} → fill in ${pc.yellow('database_id')} (D1) and ${pc.yellow('bucket_name')} (R2)`,
358
+ ` Set R2 S3 secrets for Presigned uploads in ${pc.underline('.dev.vars')} (dev) and via ${pc.cyan('npx wrangler secret put')} (prod)`,
359
+ ` Guide: https://developers.cloudflare.com/r2/api/s3/tokens/`,
360
+ '',
361
+ ] : [
362
+ `${pc.bold('3. Production R2 secrets')} (when deploying to Cloudflare)`,
363
+ ` ${pc.cyan('npx wrangler secret put R2_ACCESS_KEY_ID')}`,
364
+ ` ${pc.cyan('npx wrangler secret put R2_SECRET_ACCESS_KEY')}`,
365
+ ` ${pc.cyan('npx wrangler secret put R2_ENDPOINT')} → ${cloudflare.r2Endpoint}`,
366
+ ` ${pc.cyan('npx wrangler secret put R2_BUCKET_NAME')} → ${cloudflare.r2Bucket}`,
367
+ '',
368
+ ]),
369
+ `${step(3)}. Run local migrations`,
370
+ ` ${pc.cyan('npm run db:migrate:local')}`,
371
+ '',
372
+ `${step(4)}. Start the dev server`,
373
+ ` ${pc.cyan('npx wrangler dev')}`,
374
+ ` Then open: ${pc.underline('http://localhost:8789/admin')}`,
375
+ '',
376
+ `${step(5)}. Deploy to production`,
377
+ ` ${pc.cyan('npm run deploy')}`,
378
+ '',
379
+ `${pc.dim('Manage content types dynamically in the BeechCMS Dashboard at /admin.')}`,
380
+ `${pc.dim('JWT secret and API keys have been auto-generated.')}`,
381
+ ].join('\n'),
382
+ 'Next steps'
383
+ )
384
+ p.outro(pc.green(`✔ BeechCMS project ready — ${name}/`))
385
+ }
386
+
387
+ main().catch((err) => {
388
+ console.error(err)
389
+ process.exit(1)
390
+ })
391
+