@brightsideoy/kama 1.0.0-alpha.3 → 1.0.0-alpha.30

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.
Files changed (111) hide show
  1. package/README.md +25 -7
  2. package/bin/cli.js +539 -359
  3. package/content/definitions/blocks/button.yaml +15 -5
  4. package/content/definitions/blocks/form.yaml +20 -0
  5. package/content/definitions/blocks/image-gallery.yaml +34 -0
  6. package/content/definitions/blocks/node-list.yaml +75 -0
  7. package/content/definitions/blocks/youtube.yaml +8 -0
  8. package/content/definitions/field-sets/access.yaml +14 -0
  9. package/content/definitions/field-sets/page-base.yaml +19 -1
  10. package/content/definitions/forms/.gitkeep +0 -0
  11. package/content/definitions/forms/contact.yaml +38 -0
  12. package/content/definitions/forms/subscription.yaml +26 -0
  13. package/content/definitions/nodes/article.yaml +19 -1
  14. package/content/definitions/taxonomies/categories.yaml +5 -2
  15. package/content/definitions/taxonomies/media-tag.yaml +15 -0
  16. package/content/definitions/taxonomies/tags.yaml +5 -2
  17. package/definitions/editor/default.ts +19 -2
  18. package/dist/assets/AssetEditor-CAvQEsBT.js +1 -0
  19. package/dist/assets/AssetEditor-CQtKSOjX.css +1 -0
  20. package/dist/assets/CmsAccordion-91I5Rx5D.css +1 -0
  21. package/dist/assets/CmsAccordion-BgdaB8QZ.js +1 -0
  22. package/dist/assets/CmsBadge-BT2jTJUu.js +1 -0
  23. package/dist/assets/CmsBadge-Ip5hXw8G.css +1 -0
  24. package/dist/assets/CmsButton-DATGQeoC.css +1 -0
  25. package/dist/assets/CmsButton-DnhPsHXA.js +1 -0
  26. package/dist/assets/CmsFieldTaxonomy-CNY3-MbD.js +1 -0
  27. package/dist/assets/CmsFieldTaxonomy-CVlKL-l2.css +1 -0
  28. package/dist/assets/CmsHelp-BO_vWABq.css +1 -0
  29. package/dist/assets/CmsHelp-DtPeURCv.js +1 -0
  30. package/dist/assets/CmsImagePreview-BhM7S_v8.js +1 -0
  31. package/dist/assets/CmsImagePreview-CujwG8r_.css +1 -0
  32. package/dist/assets/CmsPublisher-BcrQAr1m.css +1 -0
  33. package/dist/assets/CmsPublisher-DiQhfPID.js +3 -0
  34. package/dist/assets/CmsUserCenter-CAaiCweN.js +1 -0
  35. package/dist/assets/CmsUserCenter-D3OZYHD0.css +1 -0
  36. package/dist/assets/EditorSplitPreview-BfGni85I.js +1 -0
  37. package/dist/assets/EditorSplitPreview-CMoTjLW5.css +1 -0
  38. package/dist/assets/FormsWorkspace-CGs6eUjz.css +1 -0
  39. package/dist/assets/FormsWorkspace-CUK-y2dR.js +2 -0
  40. package/dist/assets/NodeContextMenu-C5RTK0sr.js +1 -0
  41. package/dist/assets/NodeContextMenu-Cj-2TvQC.css +1 -0
  42. package/dist/assets/NodeEditor-CNj66ogv.js +161 -0
  43. package/dist/assets/NodeEditor-hYW5aA6B.css +1 -0
  44. package/dist/assets/SettingsDashboard-XBOgYUn3.css +1 -0
  45. package/dist/assets/SettingsDashboard-gzHzxsIc.js +1 -0
  46. package/dist/assets/StatusPill-Dlm6uvGe.css +1 -0
  47. package/dist/assets/StatusPill-HY1gCP9c.js +1 -0
  48. package/dist/assets/TrashWorkspace-DtMgxg13.css +1 -0
  49. package/dist/assets/TrashWorkspace-t0lOrFRK.js +1 -0
  50. package/dist/assets/_plugin-vue_export-helper-BK_c4R_m.js +5 -0
  51. package/dist/assets/circle-check-CksZGUB7.js +1 -0
  52. package/dist/assets/database--QlkzG9u.js +1 -0
  53. package/dist/assets/file-U7h4eOhG.js +1 -0
  54. package/dist/assets/globe-TuZP0v6A.js +1 -0
  55. package/dist/assets/history-CIbqkRx3.js +1 -0
  56. package/dist/assets/index-0nWRArpY.js +14 -0
  57. package/dist/assets/index-C171UGo4.css +1 -0
  58. package/dist/assets/layers-BwACvD_U.js +1 -0
  59. package/dist/assets/loader-circle-DYEFqbD4.js +1 -0
  60. package/dist/assets/panel-left-close-Cpq52HZy.js +1 -0
  61. package/dist/assets/plus-7rv1C56N.js +1 -0
  62. package/dist/assets/preload-helper-BB8Wl1va.js +1 -0
  63. package/dist/assets/preload-helper-BxFQpwa9.css +1 -0
  64. package/dist/assets/rotate-ccw-DvjWccJd.js +1 -0
  65. package/dist/assets/save-Dwhm8QNL.js +1 -0
  66. package/dist/assets/schema-helpers-uuDCw8Rb.js +1 -0
  67. package/dist/assets/send-Bs4eROle.js +1 -0
  68. package/dist/assets/smartphone-i429gh5p.js +1 -0
  69. package/dist/assets/trash-2-BbKTm8cC.js +1 -0
  70. package/dist/assets/useCmsState-CDENPbKL.js +1 -0
  71. package/dist/assets/useNodes-D-Vuwq5_.js +1 -0
  72. package/dist/assets/user-DKryA1QU.js +1 -0
  73. package/dist/assets/x-DOWbsdzd.js +1 -0
  74. package/dist/build-seed.js +495 -0
  75. package/dist/{dist-cK3xGnBZ.js → dist-DKRU6nhX.js} +9254 -5762
  76. package/dist/index.html +32 -2
  77. package/dist/index.js +9179 -5689
  78. package/dist/nodemailer-Ccic7tRm-Dw2jwzbm.js +7877 -0
  79. package/dist/nodemailer-Ccic7tRm.js +7908 -0
  80. package/dist/rolldown-runtime-B0aSnxlc.js +20 -0
  81. package/dist/schema-compiler.js +1 -1
  82. package/documentation/FORMS.md +256 -0
  83. package/documentation/SCHEMAS.md +450 -119
  84. package/package.json +14 -6
  85. package/schema.sql +46 -1
  86. package/templates/astro-starter/astro-preview-dev-integration.mjs +83 -0
  87. package/templates/astro-starter/astro.config.mjs +11 -0
  88. package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +17 -0
  89. package/templates/astro-starter/src/components/blocks/Form.astro +313 -0
  90. package/templates/astro-starter/src/components/blocks/HeaderImage.astro +6 -12
  91. package/templates/astro-starter/src/components/blocks/ImageBlock.astro +5 -6
  92. package/templates/astro-starter/src/components/blocks/NodeList.astro +274 -0
  93. package/templates/astro-starter/src/components/global/NavigationMenu.astro +17 -8
  94. package/templates/astro-starter/src/components/ui/KamaImage.astro +13 -5
  95. package/templates/astro-starter/src/layouts/StandardLayout.astro +4 -3
  96. package/templates/astro-starter/src/lib/cms-fetch.ts +22 -0
  97. package/templates/astro-starter/src/lib/cms.ts +18 -9
  98. package/templates/astro-starter/src/lib/media/kama-image-service.ts +15 -4
  99. package/templates/astro-starter/src/lib/media/media-proxy.ts +22 -3
  100. package/templates/astro-starter/src/lib/media/media-url.ts +17 -3
  101. package/templates/astro-starter/src/middleware.ts +199 -71
  102. package/templates/astro-starter/src/pages/[...slug].astro +122 -45
  103. package/templates/astro-starter/src/pages/api/forms/[...path].ts +57 -0
  104. package/templates/astro-starter/src/pages/api/load-nodes.ts +68 -0
  105. package/templates/astro-starter/src/pages/api/partials/node-cards.astro +98 -0
  106. package/templates/astro-starter/src/pages/partials/nav.astro +6 -5
  107. package/templates/kama-worker/index.js +22 -12
  108. package/templates/kama-worker/setup-local-db.mjs +17 -0
  109. package/wrangler.json +19 -0
  110. package/dist/assets/index-C3LzwJjY.css +0 -1
  111. package/dist/assets/index-DhguVxzs.js +0 -164
package/bin/cli.js CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { execSync } from 'node:child_process';
3
- import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, cpSync, unlinkSync, appendFileSync } from 'node:fs';
3
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, cpSync, unlinkSync, appendFileSync, chmodSync } from 'node:fs';
4
4
  import { join, dirname, basename, resolve } from 'node:path';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { fileURLToPath } from 'node:url';
6
+ import crypto from 'node:crypto';
6
7
 
7
- // 🎯 Modern CLI UI Components
8
- import { intro, outro, text, select, confirm, spinner, note, isCancel, cancel } from '@clack/prompts';
8
+ import { intro, outro, text, password, select, confirm, spinner, note, isCancel, cancel } from '@clack/prompts';
9
9
 
10
- // --- UI HELPERS (Zero Dependency Colors) ---
11
10
  const pc = {
12
11
  green: (t) => `\x1b[32m${t}\x1b[0m`,
13
12
  cyan: (t) => `\x1b[36m${t}\x1b[0m`,
@@ -19,7 +18,6 @@ const pc = {
19
18
  reset: '\x1b[0m'
20
19
  };
21
20
 
22
- // Graceful exit handler for Ctrl+C
23
21
  function handleCancel(value) {
24
22
  if (isCancel(value)) {
25
23
  cancel('Operation cancelled.');
@@ -28,13 +26,29 @@ function handleCancel(value) {
28
26
  return value;
29
27
  }
30
28
 
31
- // 🎯 Always use the absolute newest ecosystem
32
29
  const ASTRO_LATEST = "latest";
33
30
  const ASTRO_NODE_LATEST = "latest";
34
31
  const ASTRO_CF_LATEST = "latest";
35
32
  const WRANGLER_LATEST = "latest";
36
33
 
37
- // Dynamically resolve current package version
34
+ const defaultCloudflareObservability = () => ({
35
+ enabled: true,
36
+ redact_query_string: true,
37
+ logs: { enabled: true, head_sampling_rate: 0.1 },
38
+ traces: { enabled: true, head_sampling_rate: 0.02 }
39
+ });
40
+
41
+ const applyDefaultCloudflareObservability = (config) => {
42
+ const defaults = defaultCloudflareObservability();
43
+ const existing = config.observability || {};
44
+ config.observability = {
45
+ ...defaults,
46
+ ...existing,
47
+ logs: { ...defaults.logs, ...(existing.logs || {}) },
48
+ traces: { ...defaults.traces, ...(existing.traces || {}) }
49
+ };
50
+ };
51
+
38
52
  const __filename = fileURLToPath(import.meta.url);
39
53
  const __dirname = dirname(__filename);
40
54
  let currentKamaVersion = 'alpha';
@@ -48,28 +62,307 @@ try {
48
62
  console.warn("⚠️ Could not detect Kama version, defaulting to 'alpha'");
49
63
  }
50
64
 
65
+ function getOrGenerateWorkspaceSecret(workerDir) {
66
+ const envPath = join(workerDir, '.env');
67
+ const devVarsPath = join(workerDir, '.dev.vars');
68
+
69
+ let secret = null;
70
+
71
+ if (existsSync(envPath)) {
72
+ const match = readFileSync(envPath, 'utf-8').match(/^FRONTEND_API_SECRET=["']?([^"'\n]+)/m);
73
+ if (match) secret = match[1];
74
+ }
75
+
76
+ if (!secret && existsSync(devVarsPath)) {
77
+ const match = readFileSync(devVarsPath, 'utf-8').match(/^FRONTEND_API_SECRET=["']?([^"'\n]+)/m);
78
+ if (match) secret = match[1];
79
+ }
80
+
81
+ if (!secret) {
82
+ secret = crypto.randomBytes(32).toString('hex');
83
+ const secretLine = `\n# KAMA Auto-Generated Server-to-Server Security\nFRONTEND_API_SECRET="${secret}"\n`;
84
+
85
+ if (existsSync(devVarsPath)) {
86
+ appendFileSync(devVarsPath, secretLine);
87
+ } else if (existsSync(envPath)) {
88
+ appendFileSync(envPath, secretLine);
89
+ } else {
90
+ writeFileSync(devVarsPath, secretLine);
91
+ }
92
+ }
93
+
94
+ return secret;
95
+ }
96
+
97
+ function getWranglerCmd() {
98
+ try {
99
+ execSync('wrangler --version', { stdio: 'ignore' });
100
+ return 'wrangler';
101
+ } catch (e) {
102
+ return 'npx --yes --package=wrangler wrangler';
103
+ }
104
+ }
105
+
106
+ function runWrangler(cmd, options = {}) {
107
+ const baseWrangler = getWranglerCmd();
108
+ try {
109
+ const result = execSync(`${baseWrangler} ${cmd}`, {
110
+ encoding: 'utf-8',
111
+ stdio: options.stdio || 'pipe',
112
+ input: options.input,
113
+ cwd: options.cwd || process.cwd(),
114
+ env: {
115
+ ...process.env,
116
+ PATH: process.env.PATH
117
+ }
118
+ });
119
+ return typeof result === 'string' ? result : '';
120
+ } catch (e) {
121
+ if (options.throw) throw new Error(`Wrangler command failed: ${cmd}\n${e.stderr || e.message}`);
122
+ return null;
123
+ }
124
+ }
125
+
126
+ function shellQuote(value) {
127
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
128
+ }
129
+
130
+ function getOrCreateKV(title, cwd = process.cwd()) {
131
+ const listOut = runWrangler('kv namespace list', { cwd });
132
+ if (listOut) {
133
+ try {
134
+ const namespaces = JSON.parse(listOut);
135
+ const found = namespaces.find(n => n.title === title);
136
+ if (found) return found.id;
137
+ } catch (err) { }
138
+ }
139
+
140
+ const createOut = runWrangler(`kv namespace create ${shellQuote(title)}`, { cwd, throw: true });
141
+ const match = createOut.match(/"id":\s*"([a-fA-F0-9]{32})"/);
142
+ if (match) return match[1];
143
+
144
+ throw new Error(`Unable to create or find Cloudflare KV namespace "${title}". Check Wrangler authentication and permissions.`);
145
+ }
146
+
147
+ function getOrCreateD1(name, cwd = process.cwd()) {
148
+ const listOutput = runWrangler('d1 list --json', { cwd, throw: true });
149
+ let databases;
150
+ try {
151
+ databases = JSON.parse(listOutput);
152
+ } catch (error) {
153
+ throw new Error('Wrangler returned invalid JSON while listing D1 databases.');
154
+ }
155
+
156
+ const existing = databases.find(database => database.name === name);
157
+ if (existing?.uuid) return existing.uuid;
158
+
159
+ const createOutput = runWrangler(`d1 create ${shellQuote(name)}`, { cwd, throw: true });
160
+ const created = createOutput.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
161
+ if (created) return created[0];
162
+
163
+ throw new Error(`Cloudflare D1 database "${name}" was not created or returned a valid ID.`);
164
+ }
165
+
166
+ function ensureR2Bucket(name, cwd = process.cwd()) {
167
+ if (runWrangler(`r2 bucket info ${shellQuote(name)} --json`, { cwd })) return;
168
+
169
+ const createOutput = runWrangler(`r2 bucket create ${shellQuote(name)}`, { cwd });
170
+ if (createOutput || runWrangler(`r2 bucket info ${shellQuote(name)} --json`, { cwd })) return;
171
+
172
+ throw new Error(`Unable to create or find Cloudflare R2 bucket "${name}". Check Wrangler authentication and permissions.`);
173
+ }
174
+
175
+ function ensureCloudflareAuth(cwd) {
176
+ if (runWrangler('whoami', { cwd })) return;
177
+
178
+ console.log(pc.dim('Launching browser for Cloudflare login...'));
179
+ runWrangler('login', { cwd, stdio: 'inherit', throw: true });
180
+ if (!runWrangler('whoami', { cwd })) {
181
+ throw new Error('Cloudflare authentication could not be verified after login.');
182
+ }
183
+ }
184
+
185
+ function writeWorkerSecrets(workerDir, secret, cloudflareApiToken = '', additionalSecrets = {}) {
186
+ const values = [`FRONTEND_API_SECRET=${secret}`];
187
+ if (cloudflareApiToken) values.push(`CLOUDFLARE_API_TOKEN=${cloudflareApiToken}`);
188
+ for (const [key, value] of Object.entries(additionalSecrets)) {
189
+ if (value) values.push(`${key}=${value}`);
190
+ }
191
+ writeFileSync(join(workerDir, '.secrets'), `${values.join('\n')}\n`, { mode: 0o600 });
192
+ }
193
+
194
+ function readEnvValue(filePath, key) {
195
+ if (!existsSync(filePath)) return '';
196
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
197
+ const match = readFileSync(filePath, 'utf8').match(new RegExp(`^${escapedKey}=["']?([^"'\\r\\n]*)`, 'm'));
198
+ return match?.[1]?.trim() || '';
199
+ }
200
+
201
+ function readKeyValueFile(filePath) {
202
+ if (!existsSync(filePath)) return {};
203
+ return Object.fromEntries(readFileSync(filePath, 'utf8').split(/\r?\n/).flatMap(line => {
204
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
205
+ if (!match) return [];
206
+ let value = match[2].trim();
207
+ if (value.startsWith('"') && value.endsWith('"')) {
208
+ try { value = JSON.parse(value); } catch { value = value.slice(1, -1); }
209
+ } else if (value.startsWith("'") && value.endsWith("'")) {
210
+ value = value.slice(1, -1);
211
+ }
212
+ return [[match[1], value]];
213
+ }));
214
+ }
215
+
216
+ async function resolveCloudflareZoneId(domain, token) {
217
+ if (!token) return '';
218
+
219
+ const labels = domain.split('.');
220
+ for (let index = 0; index < labels.length - 1; index++) {
221
+ const zoneName = labels.slice(index).join('.');
222
+ const response = await fetch(`https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(zoneName)}&per_page=50`, {
223
+ headers: { Authorization: `Bearer ${token}` }
224
+ });
225
+ const data = await response.json();
226
+ if (!response.ok || !data.success) {
227
+ throw new Error(`Could not look up Cloudflare zone for ${domain}. Check the token's Zone Read permission.`);
228
+ }
229
+ const zone = data.result?.find(item => item.name === zoneName && item.status === 'active');
230
+ if (zone?.id) return zone.id;
231
+ }
232
+
233
+ throw new Error(`No active Cloudflare zone was found for ${domain}. Add the domain to Cloudflare or enter its Zone ID manually.`);
234
+ }
235
+
236
+ async function promptForCloudflareApiToken(existingToken = '') {
237
+ const token = handleCancel(await password({
238
+ message: `Optional Cloudflare API token (Zone Read + Zone Cache Purge${existingToken ? '; leave blank to keep existing token' : ''}):`,
239
+ mask: '*'
240
+ }));
241
+ return token.trim() || existingToken;
242
+ }
243
+
244
+ function normalizeCloudflareDomain(value, label) {
245
+ const input = String(value || '').trim();
246
+ if (!input) throw new Error(`${label} is required for Cloudflare deployment.`);
247
+
248
+ try {
249
+ const url = new URL(input.includes('://') ? input : `https://${input}`);
250
+ if (!url.hostname.includes('.') || url.hostname === 'localhost') throw new Error();
251
+ return url.host.toLowerCase();
252
+ } catch {
253
+ throw new Error(`${label} must be a valid Cloudflare domain, for example example.com.`);
254
+ }
255
+ }
256
+
257
+ function ensureGitIgnoreEntries(rootDir, entries) {
258
+ const gitignorePath = join(rootDir, '.gitignore');
259
+ const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf8') : '';
260
+ const lines = new Set(existing.split(/\r?\n/));
261
+ const missing = entries.filter(line => !lines.has(line));
262
+ if (missing.length > 0) appendFileSync(gitignorePath, `${existing && !existing.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
263
+ }
264
+
265
+ function ignoreSecretFiles(rootDir) {
266
+ ensureGitIgnoreEntries(rootDir, ['kama-worker/.secrets', 'kama-worker/.dev.vars', 'sites/*/.secrets', 'sites/*/.dev.vars']);
267
+ }
268
+
269
+ function updateEnvFile(filePath, values, removeKeys = []) {
270
+ const existing = existsSync(filePath) ? readFileSync(filePath, 'utf8') : '';
271
+ const keys = new Set(Object.keys(values));
272
+ const found = new Set();
273
+ const lines = existing.split(/\r?\n/).filter(line => {
274
+ const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)=/);
275
+ return !match || !removeKeys.includes(match[1]);
276
+ }).map(line => {
277
+ const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)=/);
278
+ if (!match || !keys.has(match[1])) return line;
279
+ found.add(match[1]);
280
+ return `${match[1]}=${JSON.stringify(values[match[1]])}`;
281
+ });
282
+
283
+ for (const key of keys) {
284
+ if (!found.has(key)) lines.push(`${key}=${JSON.stringify(values[key])}`);
285
+ }
286
+
287
+ writeFileSync(filePath, `${lines.filter((line, index) => line || index < lines.length - 1).join('\n')}\n`);
288
+ }
289
+
290
+ async function promptForAdminCredentials() {
291
+ let email = '';
292
+ while (!email.includes('@')) {
293
+ email = String(handleCancel(await text({
294
+ message: 'CMS administrator email:',
295
+ defaultValue: 'admin@example.com',
296
+ placeholder: 'admin@example.com'
297
+ }))).trim().toLowerCase();
298
+ if (!email.includes('@')) console.error('Enter a valid email address.');
299
+ }
300
+
301
+ let passwordValue = '';
302
+ while (passwordValue.length < 12) {
303
+ passwordValue = String(handleCancel(await password({
304
+ message: 'CMS administrator password (at least 12 characters):',
305
+ mask: '*'
306
+ })));
307
+ if (passwordValue.length < 12) console.error('The password must be at least 12 characters.');
308
+ }
309
+
310
+ const confirmation = String(handleCancel(await password({
311
+ message: 'Confirm CMS administrator password:',
312
+ mask: '*'
313
+ })));
314
+ if (passwordValue !== confirmation) throw new Error('Administrator passwords do not match.');
315
+
316
+ return { email, password: passwordValue };
317
+ }
318
+
319
+ async function configureAdminAuth() {
320
+ const cwd = process.cwd();
321
+ const workerDir = existsSync(join(cwd, 'kama-worker'))
322
+ ? join(cwd, 'kama-worker')
323
+ : basename(cwd) === 'kama-worker' ? cwd : null;
324
+ if (!workerDir) throw new Error('Run "npx kama auth setup" from a workspace root or its kama-worker directory.');
325
+
326
+ const credentials = await promptForAdminCredentials();
327
+ const cloudflare = existsSync(join(workerDir, 'wrangler.json')) || existsSync(join(workerDir, 'wrangler.jsonc'));
328
+ const targetPath = join(workerDir, cloudflare ? '.dev.vars' : '.env');
329
+ const values = {
330
+ CMS_ADMIN_EMAIL: credentials.email,
331
+ CMS_ADMIN_PASSWORD: credentials.password,
332
+ };
333
+
334
+ updateEnvFile(targetPath, values);
335
+ chmodSync(targetPath, 0o600);
336
+
337
+ if (cloudflare) {
338
+ const currentSecrets = readKeyValueFile(join(workerDir, '.secrets'));
339
+ const frontendApiSecret = currentSecrets.FRONTEND_API_SECRET || getOrGenerateWorkspaceSecret(workerDir);
340
+ const cloudflareApiToken = currentSecrets.CLOUDFLARE_API_TOKEN || '';
341
+ delete currentSecrets.FRONTEND_API_SECRET;
342
+ delete currentSecrets.CLOUDFLARE_API_TOKEN;
343
+ writeWorkerSecrets(workerDir, frontendApiSecret, cloudflareApiToken, { ...currentSecrets, ...values });
344
+ }
345
+
346
+ console.log(`Administrator credentials saved to ${targetPath}. Restart the CMS to bootstrap the account.`);
347
+ }
348
+
51
349
  function showHelp() {
52
350
  console.log(`\n${pc.bgCyan(' KAMA • ENGINE CLI ')}\n`);
53
351
  console.log('Usage: npx kama <command> [options]\n');
54
-
55
352
  console.log(pc.cyan('Commands:'));
56
353
  console.log(' init Kickstart a new Monorepo (CMS Worker + Optional Astro Site)');
57
354
  console.log(' add site Add a new Astro Frontend Site to the current workspace (sites/)');
355
+ console.log(' auth setup Configure the initial CMS administrator credentials');
58
356
  console.log(' bundle Compile and bundle YAML schemas into bundled-definitions.js for Edge deployment');
59
357
  console.log(' promote Promote the current Local workspace to Cloudflare Edge');
60
358
  console.log(' help, -h Show this help message\n');
61
-
62
359
  console.log(pc.cyan('Workspace Scripts (Run from project root):'));
63
- console.log(' npm update Update to latest KAMA version');
64
- console.log(' npm run setup Initialize database schema and seed data (Run Once)');
65
- console.log(' npm run dev Boot up the CMS backend and Astro frontend concurrently');
66
- console.log(' npm run deploy:cms Deploy the backend worker and database to Cloudflare');
67
- console.log(' npm run deploy:site Deploy the Astro frontend site to Cloudflare\n');
68
-
69
- console.log(pc.cyan('Examples:'));
70
- console.log(' npx kama init');
71
- console.log(' npx kama add site');
72
- console.log(' npx kama bundle\n');
360
+ console.log(' npm update Update to latest KAMA version');
361
+ console.log(' npm run setup Initialize database schema (Run Once)');
362
+ console.log(' npm run seed -w kama-worker Seed the database with mock test data');
363
+ console.log(' npm run dev Boot up the CMS backend and Astro frontend concurrently');
364
+ console.log(' npm run deploy:kama Deploy the backend worker and database to Cloudflare');
365
+ console.log(' npm run deploy:site Deploy the Astro frontend site to Cloudflare\n');
73
366
  }
74
367
 
75
368
  async function main() {
@@ -89,6 +382,8 @@ async function main() {
89
382
  await createFullWorkspace();
90
383
  } else if (command === 'add' && subCommand === 'site') {
91
384
  await createNewSiteOnly();
385
+ } else if (command === 'auth' && subCommand === 'setup') {
386
+ await configureAdminAuth();
92
387
  } else if (command === 'promote') {
93
388
  await promoteLocalToCloudflare();
94
389
  } else if (command === 'bundle') {
@@ -124,9 +419,6 @@ async function main() {
124
419
  }
125
420
  }
126
421
 
127
- /**
128
- * Helper to update astro.config.mjs for Cloudflare
129
- */
130
422
  function convertAstroConfigToCloudflare(siteDir) {
131
423
  const configPath = join(siteDir, 'astro.config.mjs');
132
424
  if (existsSync(configPath)) {
@@ -138,10 +430,6 @@ function convertAstroConfigToCloudflare(siteDir) {
138
430
  }
139
431
  }
140
432
 
141
- /**
142
- * COMMAND: npx kama init
143
- * Kickstart full Monorepo Workspace
144
- */
145
433
  async function createFullWorkspace() {
146
434
  const cwdName = basename(process.cwd());
147
435
  const hasExistingPkg = existsSync(join(process.cwd(), 'package.json'));
@@ -166,6 +454,8 @@ async function createFullWorkspace() {
166
454
  ]
167
455
  }));
168
456
 
457
+ const adminCredentials = await promptForAdminCredentials();
458
+
169
459
  const shouldCreateSite = handleCancel(await confirm({
170
460
  message: 'Do you want to scaffold an initial Astro frontend site?',
171
461
  initialValue: true
@@ -194,11 +484,19 @@ async function createFullWorkspace() {
194
484
  defaultValue: ''
195
485
  }));
196
486
  }
487
+
488
+ cmsDomain = normalizeCloudflareDomain(cmsDomain, 'CMS Admin Domain');
489
+ if (shouldCreateSite) siteDomain = normalizeCloudflareDomain(siteDomain, 'Frontend Website Domain');
197
490
  }
198
491
 
492
+ const cloudflareApiToken = isCloudflare ? await promptForCloudflareApiToken() : '';
493
+ const cloudflareZoneId = isCloudflare ? await resolveCloudflareZoneId(cmsDomain, cloudflareApiToken) : '';
494
+
199
495
  const cmsProtocol = isCloudflare ? 'https://' : 'http://';
200
496
  const cmsFullUrl = cmsDomain ? `${cmsProtocol}${cmsDomain.replace(/^https?:\/\//, '')}` : 'http://localhost:8787';
201
497
 
498
+ const frontendApiSecret = crypto.randomBytes(32).toString('hex');
499
+
202
500
  const workerName = `${projName}-worker`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
203
501
  let dbName = `${projName}-db`.replace(/[^a-zA-Z0-9_-]/g, '_');
204
502
  const bucketName = `${projName}-media-prod`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
@@ -206,111 +504,47 @@ async function createFullWorkspace() {
206
504
  const s = spinner();
207
505
  s.start('Provisioning workspace...');
208
506
 
209
- if (!isCurrentDir) {
210
- mkdirSync(rootDir, { recursive: true });
211
- }
507
+ if (!isCurrentDir) mkdirSync(rootDir, { recursive: true });
212
508
 
213
- writeFileSync(
214
- join(rootDir, '.gitignore'),
215
- `node_modules/\n.env\n.DS_Store\nkama-worker/.dev.vars\nkama-worker/.env\nkama-worker/.wrangler/\nkama-worker/public/\nkama-worker/*.db\nsites/*/.env\nsites/*/.astro/\nsites/*/dist/\nkama-worker/bundled-definitions.js\n`
216
- );
509
+ ensureGitIgnoreEntries(rootDir, [
510
+ 'node_modules/', '.env', '.DS_Store', 'kama-worker/.dev.vars', 'kama-worker/.secrets',
511
+ 'kama-worker/.env', 'kama-worker/.wrangler/', 'kama-worker/public/', 'kama-worker/*.db',
512
+ 'sites/*/.env', 'sites/*/.secrets', 'sites/*/.astro/', 'sites/*/dist/',
513
+ 'kama-worker/bundled-definitions.js'
514
+ ]);
217
515
 
218
516
  const sourceDefsDir = join(__dirname, '../content/definitions');
219
517
  const targetDefsDir = join(rootDir, 'content', 'definitions');
220
- if (existsSync(sourceDefsDir)) {
221
- cpSync(sourceDefsDir, targetDefsDir, { recursive: true });
222
- }
518
+ if (existsSync(sourceDefsDir)) cpSync(sourceDefsDir, targetDefsDir, { recursive: true });
223
519
 
224
520
  let d1DatabaseId = '00000000-0000-0000-0000-000000000000';
225
- let isAuthenticated = false;
226
-
521
+ let backendCacheId = '';
227
522
  if (isCloudflare) {
228
- s.message('Checking Cloudflare authentication...');
229
- try {
230
- execSync('npx wrangler whoami', { stdio: 'ignore' });
231
- isAuthenticated = true;
232
- } catch (error) {
233
- s.stop('Not authenticated with Cloudflare.', true);
234
- console.log(pc.dim('Launching browser for Cloudflare login...'));
235
- try {
236
- execSync('npx wrangler login', { stdio: 'inherit' });
237
- isAuthenticated = true;
238
- } catch (loginError) {
239
- // Ignore
240
- }
241
- s.start('Resuming provisioning...');
242
- }
243
-
244
- if (isAuthenticated) {
245
- try {
246
- s.message('Checking existing Cloudflare D1 databases...');
247
- const listOutput = execSync(`npx wrangler d1 list --json`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
248
- const jsonStart = listOutput.indexOf('[');
249
- const jsonEnd = listOutput.lastIndexOf(']') + 1;
250
- let databases = [];
251
-
252
- if (jsonStart !== -1 && jsonEnd !== -1) {
253
- databases = JSON.parse(listOutput.substring(jsonStart, jsonEnd));
254
- }
255
-
256
- const existingDb = databases.find(db => db.name === dbName);
257
-
258
- if (existingDb) {
259
- s.stop(`Database '${dbName}' already exists on your account.`);
260
- const useExisting = handleCancel(await confirm({
261
- message: 'Do you want to link this existing database?',
262
- initialValue: true
263
- }));
264
-
265
- if (useExisting) {
266
- d1DatabaseId = existingDb.uuid;
267
- s.start(`Linked existing database ID: ${d1DatabaseId}`);
268
- } else {
269
- dbName = handleCancel(await text({
270
- message: 'Enter a new database name:'
271
- }));
272
- s.start(`Creating new database '${dbName}'...`);
273
- const d1Output = execSync(`npx wrangler d1 create ${dbName}`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
274
- const match = d1Output.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
275
- if (match) {
276
- d1DatabaseId = match[0];
277
- }
278
- }
279
- } else {
280
- s.message(`Attempting to auto-create Cloudflare D1 Database '${dbName}'...`);
281
- const d1Output = execSync(`npx wrangler d1 create ${dbName}`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
282
- const match = d1Output.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
283
- if (match) {
284
- d1DatabaseId = match[0];
285
- }
286
- }
287
- } catch (error) {
288
- // Placeholder
289
- }
290
- }
523
+ s.message('Authenticating with Cloudflare...');
524
+ ensureCloudflareAuth(process.cwd());
525
+ s.message('Provisioning D1, KV, and R2 resources...');
526
+ backendCacheId = getOrCreateKV(`CACHE_KV_${workerName.toUpperCase().replace(/-/g, '_')}`, rootDir);
527
+ d1DatabaseId = getOrCreateD1(dbName, rootDir);
528
+ ensureR2Bucket(bucketName, rootDir);
291
529
  }
292
530
 
293
531
  s.message('Writing configuration files...');
294
532
 
295
- const rootScripts = {
296
- 'setup': 'npm run setup:local -w kama-worker',
297
- };
298
-
533
+ const rootPkgPath = join(rootDir, 'package.json');
534
+ const existingRootPkg = existsSync(rootPkgPath) ? JSON.parse(readFileSync(rootPkgPath, 'utf-8')) : {};
535
+ const existingWorkspaces = Array.isArray(existingRootPkg.workspaces) ? existingRootPkg.workspaces : [];
299
536
  const rootPkg = {
300
- name: projName,
537
+ ...existingRootPkg,
538
+ name: existingRootPkg.name || projName,
301
539
  private: true,
302
- type: 'module',
303
- workspaces: ['kama-worker', 'sites/*'],
304
- scripts: rootScripts,
305
- dependencies: {
306
- '@brightsideoy/kama': currentKamaVersion,
307
- },
308
- devDependencies: {}
540
+ type: existingRootPkg.type || 'module',
541
+ workspaces: [...new Set([...existingWorkspaces, 'kama-worker', 'sites/*'])],
542
+ scripts: { ...existingRootPkg.scripts, 'setup': 'npx kama bundle && npm run setup:local -w kama-worker' },
543
+ dependencies: { ...existingRootPkg.dependencies, '@brightsideoy/kama': currentKamaVersion },
544
+ devDependencies: { ...existingRootPkg.devDependencies }
309
545
  };
310
546
 
311
- if (isCloudflare) {
312
- rootPkg.devDependencies['wrangler'] = WRANGLER_LATEST;
313
- }
547
+ if (isCloudflare) rootPkg.devDependencies['wrangler'] = WRANGLER_LATEST;
314
548
 
315
549
  if (shouldCreateSite) {
316
550
  rootPkg.devDependencies['concurrently'] = '^9.0.0';
@@ -318,28 +552,23 @@ async function createFullWorkspace() {
318
552
  rootPkg.scripts['predev'] = 'npx kama bundle';
319
553
  rootPkg.scripts['dev'] = 'npx concurrently "npm run dev -w kama-worker" "npm run dev -w sites/' + siteFolderName + '"';
320
554
  rootPkg.scripts['deploy:site'] = `npm run deploy -w sites/${siteFolderName}`;
321
- rootPkg.scripts['deploy:cms'] = `npm run deploy -w kama-worker`;
555
+ rootPkg.scripts['deploy:kama'] = `npm run deploy -w kama-worker`;
322
556
  } else {
323
557
  rootPkg.scripts['predev'] = 'npx kama bundle';
324
558
  rootPkg.scripts['dev'] = 'npm run dev -w kama-worker';
325
- rootPkg.scripts['deploy:cms'] = `npm run deploy -w kama-worker`;
559
+ rootPkg.scripts['deploy:kama'] = `npm run deploy -w kama-worker`;
326
560
  }
327
561
 
328
- writeFileSync(join(rootDir, 'package.json'), JSON.stringify(rootPkg, null, 2));
562
+ writeFileSync(rootPkgPath, JSON.stringify(rootPkg, null, 2));
329
563
 
330
564
  const cmsDir = join(rootDir, 'kama-worker');
331
565
  mkdirSync(cmsDir, { recursive: true });
332
566
 
333
- writeFileSync(join(cmsDir, 'seed.sql'), '-- Kama Auto-Generated Seed File\nSELECT 1;\n');
334
-
335
567
  const emptyDefs = `{ nodes: {}, trees: {}, blocks: {}, nodeLayouts: {}, blockLayouts: {}, channels: {} }`;
336
568
  writeFileSync(join(cmsDir, 'bundled-definitions.js'), `const defs = ${emptyDefs};\nexport const BUNDLED_DEFINITIONS = defs;\nexport default defs;\n`);
337
-
338
569
  if (isCloudflare) {
339
570
  const templateIndexPath = join(__dirname, '../templates/kama-worker/index.js');
340
- if (existsSync(templateIndexPath)) {
341
- cpSync(templateIndexPath, join(cmsDir, 'index.js'));
342
- }
571
+ if (existsSync(templateIndexPath)) cpSync(templateIndexPath, join(cmsDir, 'index.js'));
343
572
 
344
573
  writeFileSync(
345
574
  join(cmsDir, 'package.json'),
@@ -348,18 +577,16 @@ async function createFullWorkspace() {
348
577
  type: 'module',
349
578
  version: '1.0.0',
350
579
  scripts: {
351
- "setup:local": `wrangler d1 execute ${dbName} --local --file=../node_modules/@brightsideoy/kama/schema.sql > /dev/null 2>&1 && wrangler d1 execute ${dbName} --local --file=seed.sql > /dev/null 2>&1`,
352
- "setup:remote": `wrangler d1 execute ${dbName} --remote --file=../node_modules/@brightsideoy/kama/schema.sql && wrangler d1 execute ${dbName} --remote --file=seed.sql`,
580
+ "seed": "npm run seed:local",
581
+ "seed:local": "node ../node_modules/@brightsideoy/kama/dist/build-seed.js && for f in seed-*.sql; do wrangler d1 execute " + dbName + " --local --file=\"$f\"; done",
582
+ "seed:remote": "node ../node_modules/@brightsideoy/kama/dist/build-seed.js && for f in seed-*.sql; do wrangler d1 execute " + dbName + " --remote --file=\"$f\"; done",
583
+ "setup:local": `wrangler d1 execute ${dbName} --local --file=../node_modules/@brightsideoy/kama/schema.sql`,
584
+ "setup:remote": `wrangler d1 execute ${dbName} --remote --file=../node_modules/@brightsideoy/kama/schema.sql`,
353
585
  "dev": "wrangler dev --port 8787 --inspector-port 9239",
354
- "deploy": "npm run setup:remote && wrangler deploy"
355
- },
356
- dependencies: {
357
- '@brightsideoy/kama': currentKamaVersion,
358
- '@libsql/client': '^0.14.0'
359
- },
360
- devDependencies: {
361
- "wrangler": WRANGLER_LATEST
586
+ "deploy": "npm run setup:remote && wrangler deploy --secrets-file .secrets"
362
587
  },
588
+ dependencies: { '@brightsideoy/kama': currentKamaVersion, 'hono': '^4.13.0', '@libsql/client': '^0.14.0' },
589
+ devDependencies: { "wrangler": WRANGLER_LATEST },
363
590
  }, null, 2)
364
591
  );
365
592
 
@@ -369,14 +596,15 @@ async function createFullWorkspace() {
369
596
  main: 'index.js',
370
597
  compatibility_date: '2024-09-23',
371
598
  compatibility_flags: ['nodejs_compat'],
599
+ observability: defaultCloudflareObservability(),
372
600
  dev: { host: 'localhost', port: 8787 },
373
- cache: { enabled: true },
374
601
  assets: { directory: '../node_modules/@brightsideoy/kama/dist', binding: 'ASSETS' },
375
602
  images: { binding: 'IMAGES' },
603
+ kv_namespaces: [{ binding: 'CACHE_KV', id: backendCacheId }],
376
604
  vars: {
377
605
  CDN_DOMAIN: cmsDomain || 'localhost:8787',
378
606
  PUBLIC_FRONTEND_URL: (shouldCreateSite) ? (siteDomain && siteDomain !== 'localhost:4321' ? `https://${siteDomain}` : 'http://localhost:4321') : 'http://localhost:4321',
379
- CLOUDFLARE_ZONE_ID: "REPLACE_WITH_YOUR_32_CHAR_ZONE_ID",
607
+ CLOUDFLARE_ZONE_ID: cloudflareZoneId,
380
608
  KAMA_RUNTIME: 'cloudflare'
381
609
  },
382
610
  d1_databases: [{ binding: 'DB', database_name: dbName, database_id: d1DatabaseId }],
@@ -386,12 +614,17 @@ async function createFullWorkspace() {
386
614
 
387
615
  writeFileSync(join(cmsDir, 'wrangler.json'), JSON.stringify(cmsWranglerConfig, null, 2));
388
616
 
389
- writeFileSync(join(cmsDir, '.dev.vars'), `# Cloudflare Edge Cache Purging Secrets\nCLOUDFLARE_API_TOKEN=cfut_YOUR_CUSTOM_PURGE_TOKEN\n\n# Local Development Overrides\nCDN_DOMAIN=\nPUBLIC_FRONTEND_URL=http://localhost:4321\n`);
617
+ const publicFrontendUrl = (shouldCreateSite) ? (siteDomain && siteDomain !== 'localhost:4321' ? `https://${siteDomain}` : 'http://localhost:4321') : 'http://localhost:4321';
618
+ const devVars = [`# Local Development Overrides`, `CDN_DOMAIN=`, `PUBLIC_FRONTEND_URL=${publicFrontendUrl}`, ``, `# Server-to-Server API Security`, `FRONTEND_API_SECRET="${frontendApiSecret}"`, ``, `# Initial CMS administrator`, `CMS_ADMIN_EMAIL=${JSON.stringify(adminCredentials.email)}`, `CMS_ADMIN_PASSWORD=${JSON.stringify(adminCredentials.password)}`];
619
+ if (cloudflareApiToken) devVars.push(`CLOUDFLARE_API_TOKEN="${cloudflareApiToken}"`);
620
+ writeFileSync(join(cmsDir, '.dev.vars'), `${devVars.join('\n')}\n`, { mode: 0o600 });
621
+ writeWorkerSecrets(cmsDir, frontendApiSecret, cloudflareApiToken, {
622
+ CMS_ADMIN_EMAIL: adminCredentials.email,
623
+ CMS_ADMIN_PASSWORD: adminCredentials.password,
624
+ });
390
625
  } else {
391
626
  const templateServerPath = join(__dirname, '../templates/kama-worker/server.js');
392
- if (existsSync(templateServerPath)) {
393
- cpSync(templateServerPath, join(cmsDir, 'server.js'));
394
- }
627
+ if (existsSync(templateServerPath)) cpSync(templateServerPath, join(cmsDir, 'server.js'));
395
628
 
396
629
  writeFileSync(
397
630
  join(cmsDir, 'package.json'),
@@ -400,24 +633,20 @@ async function createFullWorkspace() {
400
633
  type: 'module',
401
634
  version: '1.0.0',
402
635
  scripts: {
403
- "setup:local": "sqlite3 kama.db < ../node_modules/@brightsideoy/kama/schema.sql && sqlite3 kama.db < seed.sql",
636
+ "seed": "npm run seed:local",
637
+ "seed:local": "node ../node_modules/@brightsideoy/kama/dist/build-seed.js && node setup-local-db.mjs seed",
638
+ "setup:local": "node setup-local-db.mjs schema",
404
639
  "dev": "tsx server.js",
405
640
  "start": "node server.js"
406
641
  },
407
- dependencies: {
408
- '@brightsideoy/kama': currentKamaVersion,
409
- '@hono/node-server': '^1.13.0',
410
- '@libsql/client': '^0.14.0',
411
- 'sharp': '^0.33.5',
412
- 'dotenv': '^16.4.5'
413
- },
414
- devDependencies: {
415
- "tsx": "^4.19.0"
416
- },
642
+ dependencies: { '@brightsideoy/kama': currentKamaVersion, 'hono': '^4.13.0', '@hono/node-server': '^1.13.0', '@libsql/client': '^0.14.0', 'sharp': '^0.33.5', 'dotenv': '^16.4.5' },
643
+ devDependencies: { "tsx": "^4.19.0" },
417
644
  }, null, 2)
418
645
  );
419
646
 
420
- writeFileSync(join(cmsDir, '.env'), `PORT=8787\nKAMA_RUNTIME=node\nDB_PATH=./kama.db\nLOCAL_MEDIA_PATH=./public/media\nPUBLIC_CMS_URL=http://127.0.0.1:8787\nPUBLIC_API_URL=http://127.0.0.1:8787\nPUBLIC_FRONTEND_URL=http://127.0.0.1:4321\n`);
647
+ writeFileSync(join(cmsDir, '.env'), `PORT=8787\nKAMA_RUNTIME=node\nDB_PATH=./kama.db\nLOCAL_MEDIA_PATH=./public/media\nPUBLIC_CMS_URL=http://127.0.0.1:8787\nPUBLIC_API_URL=http://127.0.0.1:8787\nPUBLIC_FRONTEND_URL=http://127.0.0.1:4321\n\n# Server-to-Server API Security\nFRONTEND_API_SECRET="${frontendApiSecret}"\n\n# Initial CMS administrator\nCMS_ADMIN_EMAIL=${JSON.stringify(adminCredentials.email)}\nCMS_ADMIN_PASSWORD=${JSON.stringify(adminCredentials.password)}\n`);
648
+ chmodSync(join(cmsDir, '.env'), 0o600);
649
+ cpSync(join(__dirname, '../templates/kama-worker/setup-local-db.mjs'), join(cmsDir, 'setup-local-db.mjs'));
421
650
  }
422
651
 
423
652
  s.message('Bundling schemas...');
@@ -425,31 +654,32 @@ async function createFullWorkspace() {
425
654
 
426
655
  if (shouldCreateSite) {
427
656
  s.message(`Scaffolding Astro site (${siteFolderName})...`);
428
- await generateAstroSite(rootDir, siteFolderName, siteDomain, cmsFullUrl, workerName, isCloudflare);
657
+ await generateAstroSite(rootDir, siteFolderName, siteDomain, cmsFullUrl, workerName, isCloudflare, frontendApiSecret);
429
658
  }
430
659
 
431
- s.stop('Workspace provisioned successfully.');
660
+ s.message('Installing workspace dependencies...');
661
+ execSync('npm install', { cwd: rootDir, stdio: 'inherit' });
662
+ s.message('Bundling schemas and initializing the local database...');
663
+ execSync('npm run setup', { cwd: rootDir, stdio: 'inherit' });
664
+
665
+ s.stop('Workspace installed and initialized successfully.');
432
666
 
433
667
  let nextSteps = '';
434
668
  let stepCount = 1;
435
669
  if (!isCurrentDir) nextSteps += `${stepCount++}. cd ${projName}\n`;
436
- nextSteps += `${stepCount++}. npm install\n`;
437
- nextSteps += `${stepCount++}. npm run setup ${pc.dim('<- Run this once to init the database!')}\n`;
438
670
  nextSteps += `${stepCount++}. npm run dev\n`;
439
671
 
440
672
  if (isCloudflare) {
441
673
  nextSteps += `\n${pc.dim('Cloudflare Note:')}\n`;
442
- nextSteps += `${pc.dim('Update CLOUDFLARE_ZONE_ID in wrangler.json')}\n`;
443
- nextSteps += `${pc.dim('Set API token: npx wrangler secret put CLOUDFLARE_API_TOKEN')}`;
674
+ nextSteps += cloudflareApiToken
675
+ ? `${pc.dim('Zone ID was discovered automatically; the purge token is stored as an ignored Worker secret.')}`
676
+ : `${pc.dim('Zone-level cache purging is disabled. Run kama promote with a token to enable it.')}`;
444
677
  }
445
678
 
446
679
  note(nextSteps, 'Next steps');
447
680
  outro(`KAMA • ENGINE is ready! 🚀`);
448
681
  }
449
682
 
450
- /**
451
- * COMMAND: npx kama add site
452
- */
453
683
  async function createNewSiteOnly() {
454
684
  const rootDir = process.cwd();
455
685
 
@@ -460,8 +690,9 @@ async function createNewSiteOnly() {
460
690
 
461
691
  let targetWorkerName = 'kama-worker';
462
692
  let detectedCmsDomain = '';
693
+ const workerDir = join(rootDir, 'kama-worker');
463
694
 
464
- const cmsWranglerPath = join(rootDir, 'kama-worker', 'wrangler.json');
695
+ const cmsWranglerPath = join(workerDir, 'wrangler.json');
465
696
  if (existsSync(cmsWranglerPath)) {
466
697
  try {
467
698
  const cmsWrangler = JSON.parse(readFileSync(cmsWranglerPath, 'utf-8'));
@@ -471,6 +702,8 @@ async function createNewSiteOnly() {
471
702
  } catch (e) { }
472
703
  }
473
704
 
705
+ const frontendApiSecret = existsSync(workerDir) ? getOrGenerateWorkspaceSecret(workerDir) : crypto.randomBytes(32).toString('hex');
706
+
474
707
  const isCloudflare = handleCancel(await select({
475
708
  message: 'Deployment Architecture for this site:',
476
709
  options: [
@@ -489,33 +722,33 @@ async function createNewSiteOnly() {
489
722
  let cmsFullUrl = 'http://localhost:8787';
490
723
 
491
724
  if (isCloudflare) {
492
- siteDomain = handleCancel(await text({
493
- message: 'Website Domain (e.g., brand.com):',
494
- defaultValue: ''
495
- }));
725
+ siteDomain = handleCancel(await text({ message: 'Website Domain (e.g., brand.com):', defaultValue: '' }));
726
+ siteDomain = normalizeCloudflareDomain(siteDomain, 'Frontend Website Domain');
496
727
  if (detectedCmsDomain) {
497
728
  cmsFullUrl = detectedCmsDomain.startsWith('http') ? detectedCmsDomain : `https://${detectedCmsDomain.replace(/^https?:\/\//, '')}`;
498
729
  } else {
499
- const cmsDomainInput = handleCancel(await text({
500
- message: 'CMS API Domain (e.g., admin.brand.com):',
501
- defaultValue: ''
502
- }));
503
- cmsFullUrl = `https://${cmsDomainInput.replace(/^https?:\/\//, '')}`;
730
+ const cmsDomainInput = handleCancel(await text({ message: 'CMS API Domain (e.g., admin.brand.com):', defaultValue: '' }));
731
+ cmsFullUrl = `https://${normalizeCloudflareDomain(cmsDomainInput, 'CMS API Domain')}`;
504
732
  }
733
+ ensureCloudflareAuth(rootDir);
505
734
  }
506
735
 
736
+ ignoreSecretFiles(rootDir);
737
+
507
738
  const s = spinner();
508
739
  s.start(`Generating Astro site...`);
509
- await generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, targetWorkerName, isCloudflare);
740
+
741
+ await generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, targetWorkerName, isCloudflare, frontendApiSecret);
742
+ ignoreSecretFiles(rootDir);
743
+ s.message('Installing workspace dependencies...');
744
+ execSync('npm install', { cwd: rootDir, stdio: 'inherit' });
745
+
510
746
  s.stop(`Site created in sites/${siteFolder}!`);
511
747
 
512
- note(`1. npm install\n2. npm run setup ${pc.dim('<- Re-run to register the new site seed data')}`, 'Next steps');
748
+ note('Run `npm run dev` from the workspace root to start the new site.', 'Next steps');
513
749
  outro('Site added successfully! 🚀');
514
750
  }
515
751
 
516
- /**
517
- * COMMAND: npx kama bundle
518
- */
519
752
  async function bundleWorkspaceSchemas(targetRootDir, silent = false) {
520
753
  let rootDir = targetRootDir || process.cwd();
521
754
  if (basename(rootDir) === 'kama-worker') rootDir = resolve(rootDir, '..');
@@ -525,43 +758,39 @@ async function bundleWorkspaceSchemas(targetRootDir, silent = false) {
525
758
  try {
526
759
  let compilerPath = join(__dirname, '../dist/schema-compiler.js');
527
760
  if (!existsSync(compilerPath)) compilerPath = join(__dirname, '../scripts/schema-compiler.ts');
528
- await import(pathToFileURL(compilerPath).href);
761
+ execSync(`${shellQuote(process.execPath)} ${shellQuote(compilerPath)}`, { cwd: rootDir, stdio: 'inherit' });
762
+
529
763
  if (!silent) s.stop('Schemas bundled successfully.');
530
764
  } catch (e) {
531
- if (!silent) s.stop(`Schema compilation failed: ${e.message}`, true);
765
+ if (!silent) s.stop(`Compilation failed: ${e.message}`, true);
766
+ else throw e;
532
767
  }
533
768
  }
534
769
 
535
- /**
536
- * COMMAND: npx kama promote
537
- */
538
770
  async function promoteLocalToCloudflare() {
539
771
  const rootDir = process.cwd();
540
772
  const workerDir = join(rootDir, 'kama-worker');
541
773
  const rootPkgPath = join(rootDir, 'package.json');
542
774
 
543
775
  if (!existsSync(workerDir) || !existsSync(rootPkgPath)) {
544
- cancel('Error: Could not find kama-worker folder or package.json. Run this command inside your workspace root.');
776
+ cancel('Error: Could not find kama-worker folder or package.json.');
545
777
  process.exit(1);
546
778
  }
547
779
 
780
+ const frontendApiSecret = getOrGenerateWorkspaceSecret(workerDir);
781
+
548
782
  const s = spinner();
549
783
  s.start('Checking Cloudflare authentication...');
784
+ ensureCloudflareAuth(rootDir);
785
+ s.stop('Cloudflare authentication verified.');
550
786
 
551
- try {
552
- execSync('npx wrangler whoami', { stdio: 'ignore' });
553
- s.stop('Logged in to Cloudflare.');
554
- } catch (e) {
555
- s.stop('Not logged in to Cloudflare.', true);
556
- console.log(pc.dim('Launching browser for Cloudflare login...'));
557
- try { execSync('npx wrangler login', { stdio: 'ignore' }); }
558
- catch (loginError) { cancel('Cloudflare login failed.'); process.exit(1); }
559
- }
560
-
561
- const cmsDomain = handleCancel(await text({
562
- message: 'CMS Admin Domain (e.g., admin.yourdomain.com):',
563
- defaultValue: ''
564
- }));
787
+ const cmsDomain = normalizeCloudflareDomain(
788
+ handleCancel(await text({ message: 'CMS Admin Domain (e.g., admin.yourdomain.com):', defaultValue: '' })),
789
+ 'CMS Admin Domain'
790
+ );
791
+ const existingCloudflareToken = readEnvValue(join(workerDir, '.dev.vars'), 'CLOUDFLARE_API_TOKEN') || readEnvValue(join(workerDir, '.secrets'), 'CLOUDFLARE_API_TOKEN');
792
+ const cloudflareApiToken = await promptForCloudflareApiToken(existingCloudflareToken);
793
+ const cloudflareZoneId = await resolveCloudflareZoneId(cmsDomain, cloudflareApiToken);
565
794
 
566
795
  const sitesFolderDir = join(rootDir, 'sites');
567
796
  let siteDomain = '';
@@ -570,92 +799,101 @@ async function promoteLocalToCloudflare() {
570
799
  const sites = readdirSync(sitesFolderDir);
571
800
  if (sites.length > 0) {
572
801
  siteDir = join(sitesFolderDir, sites[0]);
573
- siteDomain = handleCancel(await text({
574
- message: `Frontend Website Domain for ${sites[0]} (e.g., yourdomain.com):`,
575
- defaultValue: ''
576
- }));
802
+ siteDomain = normalizeCloudflareDomain(
803
+ handleCancel(await text({ message: `Frontend Website Domain for ${sites[0]}:`, defaultValue: '' })),
804
+ 'Frontend Website Domain'
805
+ );
577
806
  }
578
807
  }
579
808
 
809
+ ignoreSecretFiles(rootDir);
810
+
580
811
  s.start('Upgrading workspace to Cloudflare Edge...');
581
812
 
582
813
  const projName = basename(rootDir);
583
- let dbName = `${projName}-db`.replace(/[^a-zA-Z0-9_-]/g, '_');
584
- let d1DatabaseId = '00000000-0000-0000-0000-000000000000';
585
-
586
- try {
587
- const d1Output = execSync(`npx wrangler d1 create ${dbName}`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
588
- const match = d1Output.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
589
- if (match) d1DatabaseId = match[0];
590
- } catch (err) { }
814
+ const workerName = `${projName}-worker`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
815
+ const bucketName = `${projName}-media-prod`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
816
+ const dbName = `${projName}-db`.replace(/[^a-zA-Z0-9_-]/g, '_');
817
+ const d1DatabaseId = getOrCreateD1(dbName, rootDir);
818
+ const backendCacheId = getOrCreateKV(`CACHE_KV_${workerName.toUpperCase().replace(/-/g, '_')}`, rootDir);
819
+ ensureR2Bucket(bucketName, rootDir);
591
820
 
592
821
  const rootPkg = JSON.parse(readFileSync(rootPkgPath, 'utf-8'));
593
822
  rootPkg.devDependencies = rootPkg.devDependencies || {};
594
823
  rootPkg.devDependencies['wrangler'] = WRANGLER_LATEST;
595
824
  writeFileSync(rootPkgPath, JSON.stringify(rootPkg, null, 2));
596
825
 
597
- const workerName = `${projName}-worker`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
598
- const bucketName = `${projName}-media-prod`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
599
826
  const workerWranglerPath = join(workerDir, 'wrangler.json');
827
+ let currentConfig = existsSync(workerWranglerPath) ? JSON.parse(readFileSync(workerWranglerPath, 'utf-8')) : {
828
+ $schema: '../node_modules/wrangler/config-schema.json',
829
+ name: workerName,
830
+ main: 'index.js',
831
+ compatibility_date: '2024-09-23',
832
+ compatibility_flags: ['nodejs_compat'],
833
+ observability: defaultCloudflareObservability(),
834
+ assets: { directory: '../node_modules/@brightsideoy/kama/dist', binding: 'ASSETS' },
835
+ images: { binding: 'IMAGES' },
836
+ vars: { CLOUDFLARE_ZONE_ID: '', KAMA_RUNTIME: 'cloudflare' }
837
+ };
600
838
 
601
- let currentConfig = existsSync(workerWranglerPath)
602
- ? JSON.parse(readFileSync(workerWranglerPath, 'utf-8'))
603
- : {
604
- $schema: '../node_modules/wrangler/config-schema.json',
605
- name: workerName,
606
- main: 'index.js',
607
- compatibility_date: '2024-09-23',
608
- compatibility_flags: ['nodejs_compat'],
609
- assets: { directory: '../node_modules/@brightsideoy/kama/dist', binding: 'ASSETS' },
610
- images: { binding: 'IMAGES' },
611
- vars: { CLOUDFLARE_ZONE_ID: "REPLACE_WITH_YOUR_32_CHAR_ZONE_ID", KAMA_RUNTIME: 'cloudflare' }
612
- };
839
+ const cloudflareEntryPath = join(workerDir, 'index.js');
840
+ if (!existsSync(cloudflareEntryPath)) {
841
+ cpSync(join(__dirname, '../templates/kama-worker/index.js'), cloudflareEntryPath);
842
+ }
613
843
 
844
+ currentConfig.main = 'index.js';
614
845
  currentConfig.dev = currentConfig.dev || { host: 'localhost', port: 8787 };
615
- currentConfig.cache = { enabled: true };
846
+ currentConfig.assets = currentConfig.assets || { directory: '../node_modules/@brightsideoy/kama/dist', binding: 'ASSETS' };
847
+ currentConfig.images = currentConfig.images || { binding: 'IMAGES' };
848
+ currentConfig.vars = currentConfig.vars || {};
849
+ if (String(currentConfig.vars.CLOUDFLARE_ZONE_ID || '').startsWith('REPLACE_WITH_')) {
850
+ currentConfig.vars.CLOUDFLARE_ZONE_ID = '';
851
+ }
852
+ currentConfig.vars.CLOUDFLARE_ZONE_ID = cloudflareZoneId || currentConfig.vars.CLOUDFLARE_ZONE_ID || '';
616
853
  currentConfig.vars.CDN_DOMAIN = cmsDomain;
617
854
  if (siteDomain) currentConfig.vars.PUBLIC_FRONTEND_URL = `https://${siteDomain}`;
618
855
  currentConfig.routes = [{ pattern: cmsDomain, custom_domain: true }];
856
+ applyDefaultCloudflareObservability(currentConfig);
619
857
  currentConfig.d1_databases = [{ binding: 'DB', database_name: dbName, database_id: d1DatabaseId }];
620
858
  currentConfig.r2_buckets = [{ binding: 'MEDIA_BUCKET', bucket_name: bucketName }];
859
+ currentConfig.kv_namespaces = [{ binding: 'CACHE_KV', id: backendCacheId }];
621
860
 
622
861
  writeFileSync(workerWranglerPath, JSON.stringify(currentConfig, null, 2));
623
862
 
624
- if (!existsSync(join(workerDir, '.dev.vars'))) {
625
- writeFileSync(join(workerDir, '.dev.vars'), `CLOUDFLARE_API_TOKEN=cfut_YOUR_CUSTOM_PURGE_TOKEN\nCDN_DOMAIN=\nPUBLIC_FRONTEND_URL=http://localhost:4321\n`);
626
- }
627
-
628
- const workerIndexPath = join(workerDir, 'index.js');
629
- if (!existsSync(workerIndexPath)) {
630
- const templateIndexPath = join(__dirname, '../templates/kama-worker/index.js');
631
- if (existsSync(templateIndexPath)) {
632
- cpSync(templateIndexPath, workerIndexPath);
633
- }
634
- }
863
+ updateEnvFile(join(workerDir, '.dev.vars'), {
864
+ CDN_DOMAIN: '',
865
+ PUBLIC_FRONTEND_URL: 'http://localhost:4321',
866
+ FRONTEND_API_SECRET: frontendApiSecret,
867
+ ...(cloudflareApiToken ? { CLOUDFLARE_API_TOKEN: cloudflareApiToken } : {})
868
+ });
869
+ writeWorkerSecrets(workerDir, frontendApiSecret, cloudflareApiToken);
635
870
 
636
871
  const workerPkgPath = join(workerDir, 'package.json');
637
872
  if (existsSync(workerPkgPath)) {
638
873
  const workerPkg = JSON.parse(readFileSync(workerPkgPath, 'utf-8'));
639
874
  workerPkg.scripts.dev = "wrangler dev --port 8787 --inspector-port 9239";
640
- workerPkg.scripts.deploy = "npm run setup:remote && wrangler deploy";
641
- workerPkg.scripts["setup:local"] = `wrangler d1 execute ${dbName} --local --file=../node_modules/@brightsideoy/kama/schema.sql && wrangler d1 execute ${dbName} --local --file=seed.sql`;
642
- workerPkg.scripts["setup:remote"] = `wrangler d1 execute ${dbName} --remote --file=../node_modules/@brightsideoy/kama/schema.sql && wrangler d1 execute ${dbName} --remote --file=seed.sql`;
875
+ workerPkg.scripts.deploy = "npm run setup:remote && wrangler deploy --secrets-file .secrets";
876
+ workerPkg.scripts["setup:local"] = `wrangler d1 execute ${dbName} --local --file=../node_modules/@brightsideoy/kama/schema.sql`;
877
+ workerPkg.scripts["setup:remote"] = `wrangler d1 execute ${dbName} --remote --file=../node_modules/@brightsideoy/kama/schema.sql`;
878
+
879
+ workerPkg.scripts["seed"] = "npm run seed:local";
880
+ workerPkg.scripts["seed:local"] = `node ../node_modules/@brightsideoy/kama/dist/build-seed.js && for f in seed-*.sql; do wrangler d1 execute ${dbName} --local --file="$f"; done`;
881
+ workerPkg.scripts["seed:remote"] = `node ../node_modules/@brightsideoy/kama/dist/build-seed.js && for f in seed-*.sql; do wrangler d1 execute ${dbName} --remote --file="$f"; done`;
882
+
883
+ workerPkg.dependencies = workerPkg.dependencies || {};
884
+ workerPkg.dependencies.hono = '^4.13.0';
885
+
643
886
  workerPkg.devDependencies = workerPkg.devDependencies || {};
644
887
  workerPkg.devDependencies.wrangler = WRANGLER_LATEST;
888
+ if (workerPkg.devDependencies.tsx) delete workerPkg.devDependencies.tsx;
889
+
645
890
  writeFileSync(workerPkgPath, JSON.stringify(workerPkg, null, 2));
646
891
  }
647
892
 
648
893
  if (siteDir && siteDomain) {
649
- let sessionId = "REPLACE_WITH_YOUR_SESSION_KV_ID";
650
- let htmlCacheId = "REPLACE_WITH_YOUR_HTML_CACHE_KV_ID";
651
894
  const prefix = basename(siteDir).replace(/[^a-zA-Z0-9]/g, '_').toUpperCase();
652
-
653
- try {
654
- const sessionOut = execSync(`npx wrangler kv namespace create "SESSION_${prefix}"`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
655
- if (sessionOut.match(/"id":\s*"([a-f0-9]{32})"/)) sessionId = sessionOut.match(/"id":\s*"([a-f0-9]{32})"/)[1];
656
- const cacheOut = execSync(`npx wrangler kv namespace create "HTML_CACHE_${prefix}"`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
657
- if (cacheOut.match(/"id":\s*"([a-f0-9]{32})"/)) htmlCacheId = cacheOut.match(/"id":\s*"([a-f0-9]{32})"/)[1];
658
- } catch (err) { }
895
+ const sessionId = getOrCreateKV(`SESSION_${prefix}`, rootDir);
896
+ const htmlCacheId = getOrCreateKV(`HTML_CACHE_${prefix}`, rootDir);
659
897
 
660
898
  const siteWranglerPath = join(siteDir, 'wrangler.json');
661
899
  const siteConfig = {
@@ -663,12 +901,13 @@ async function promoteLocalToCloudflare() {
663
901
  name: `${basename(siteDir).toLowerCase().replace(/[^a-z0-9-]/g, '-')}-site`,
664
902
  compatibility_date: "2024-09-23",
665
903
  compatibility_flags: ["nodejs_compat"],
904
+ observability: defaultCloudflareObservability(),
666
905
  dev: { host: 'localhost', port: 4321 },
667
906
  cache: { enabled: true },
668
907
  assets: { directory: "./dist/client", binding: "ASSETS", run_worker_first: true },
669
908
  kv_namespaces: [{ binding: "SESSION", id: sessionId }, { binding: "HTML_CACHE", id: htmlCacheId }],
670
909
  services: [{ binding: "CMS_WORKER", service: currentConfig.name }],
671
- routes: [{ pattern: siteDomain, zone_name: siteDomain, custom_domain: true, enabled: true, previews_enabled: false }],
910
+ routes: [{ pattern: siteDomain, custom_domain: true, enabled: true, previews_enabled: false }],
672
911
  vars: { PUBLIC_CMS_URL: `https://${cmsDomain}`, PUBLIC_API_URL: `https://${cmsDomain}` }
673
912
  };
674
913
  writeFileSync(siteWranglerPath, JSON.stringify(siteConfig, null, 2));
@@ -678,48 +917,50 @@ async function promoteLocalToCloudflare() {
678
917
  const sitePkg = JSON.parse(readFileSync(sitePkgPath, 'utf-8'));
679
918
  sitePkg.dependencies = sitePkg.dependencies || {};
680
919
  sitePkg.dependencies['astro'] = ASTRO_LATEST;
681
-
682
920
  if (sitePkg.dependencies['@astrojs/node']) delete sitePkg.dependencies['@astrojs/node'];
683
921
  sitePkg.dependencies['@astrojs/cloudflare'] = ASTRO_CF_LATEST;
684
-
685
922
  sitePkg.devDependencies = sitePkg.devDependencies || {};
686
923
  sitePkg.devDependencies['wrangler'] = WRANGLER_LATEST;
687
-
924
+ sitePkg.scripts = sitePkg.scripts || {};
925
+ sitePkg.scripts.deploy = 'astro build && wrangler deploy --secrets-file .secrets';
688
926
  writeFileSync(sitePkgPath, JSON.stringify(sitePkg, null, 2));
689
927
  }
690
928
 
929
+ writeWorkerSecrets(siteDir, frontendApiSecret);
930
+ updateEnvFile(join(siteDir, '.env'), {
931
+ PUBLIC_CMS_URL: `https://${cmsDomain}`,
932
+ PUBLIC_API_URL: `https://${cmsDomain}`
933
+ }, ['FRONTEND_API_SECRET']);
934
+ updateEnvFile(join(siteDir, '.dev.vars'), { FRONTEND_API_SECRET: frontendApiSecret });
691
935
  convertAstroConfigToCloudflare(siteDir);
936
+ }
692
937
 
693
- const tsConfigPath = join(siteDir, 'tsconfig.json');
694
- if (existsSync(tsConfigPath)) {
695
- const tsConfig = JSON.parse(readFileSync(tsConfigPath, 'utf-8'));
696
- tsConfig.compilerOptions = tsConfig.compilerOptions || {};
697
- tsConfig.compilerOptions.types = ["@cloudflare/workers-types"];
698
- writeFileSync(tsConfigPath, JSON.stringify(tsConfig, null, 2));
699
- }
938
+ s.message('Installing Cloudflare dependencies...');
939
+ execSync('npm install', { cwd: rootDir, stdio: 'inherit' });
940
+ s.message('Bundling workspace schemas...');
941
+ await bundleWorkspaceSchemas(rootDir, true);
942
+ s.message('Deploying CMS and initializing the remote database...');
943
+ execSync('npm run deploy -w kama-worker', { cwd: rootDir, stdio: 'inherit' });
944
+
945
+ if (siteDir && siteDomain) {
946
+ const siteFolder = basename(siteDir);
947
+ s.message(`Building and deploying ${siteFolder}...`);
948
+ execSync(`npm run deploy -w sites/${shellQuote(siteFolder)}`, { cwd: rootDir, stdio: 'inherit' });
700
949
  }
701
950
 
702
- s.stop('Workspace successfully upgraded to Cloudflare Edge!');
703
- outro('Promotion complete. 🚀');
951
+ s.stop('Workspace provisioned and deployed to Cloudflare.');
952
+ outro('Promotion complete.');
704
953
  }
705
954
 
706
- /**
707
- * Helper: Copies the Astro starter template and hydrates runtime tokens
708
- */
709
- async function generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, workerName = 'kama-worker', isCloudflare = false) {
955
+ async function generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, workerName = 'kama-worker', isCloudflare = false, frontendApiSecret = '') {
710
956
  const siteDir = join(rootDir, 'sites', siteFolder);
711
957
  const templateDir = join(__dirname, '../templates/astro-starter');
712
958
 
713
- if (!existsSync(templateDir)) {
714
- return;
715
- }
959
+ if (!existsSync(templateDir)) return;
716
960
 
717
961
  cpSync(templateDir, siteDir, { recursive: true });
718
962
 
719
- const tsConfig = {
720
- extends: "astro/tsconfigs/strict",
721
- compilerOptions: { baseUrl: ".", paths: { "@/*": ["src/*"] } }
722
- };
963
+ const tsConfig = { extends: "astro/tsconfigs/strict", compilerOptions: { baseUrl: ".", paths: { "@/*": ["src/*"] } } };
723
964
  if (isCloudflare) tsConfig.compilerOptions.types = ["@cloudflare/workers-types"];
724
965
  writeFileSync(join(siteDir, 'tsconfig.json'), JSON.stringify(tsConfig, null, 2));
725
966
 
@@ -728,7 +969,6 @@ async function generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, wo
728
969
  const rawContent = readFileSync(templatePkgPath, 'utf-8')
729
970
  .replace(/\{\{SITE_NAME\}\}/g, siteFolder)
730
971
  .replace(/\{\{KAMA_VERSION\}\}/g, currentKamaVersion);
731
-
732
972
  const sitePkg = JSON.parse(rawContent);
733
973
 
734
974
  sitePkg.dependencies = sitePkg.dependencies || {};
@@ -738,14 +978,13 @@ async function generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, wo
738
978
  if (sitePkg.dependencies['@astrojs/cloudflare']) delete sitePkg.dependencies['@astrojs/cloudflare'];
739
979
  if (sitePkg.dependencies['wrangler']) delete sitePkg.dependencies['wrangler'];
740
980
  if (sitePkg.devDependencies && sitePkg.devDependencies['wrangler']) delete sitePkg.devDependencies['wrangler'];
741
-
742
981
  sitePkg.dependencies['@astrojs/node'] = ASTRO_NODE_LATEST;
743
982
  } else {
744
983
  sitePkg.dependencies['@astrojs/cloudflare'] = ASTRO_CF_LATEST;
745
984
  if (sitePkg.dependencies['wrangler']) delete sitePkg.dependencies['wrangler'];
746
985
  sitePkg.devDependencies = sitePkg.devDependencies || {};
747
986
  sitePkg.devDependencies['wrangler'] = WRANGLER_LATEST;
748
-
987
+ sitePkg.scripts.deploy = 'astro build && wrangler deploy --secrets-file .secrets';
749
988
  convertAstroConfigToCloudflare(siteDir);
750
989
  }
751
990
 
@@ -754,114 +993,55 @@ async function generateAstroSite(rootDir, siteFolder, siteDomain, cmsFullUrl, wo
754
993
  }
755
994
 
756
995
  const siteLabel = siteFolder.split(/[-_]/).map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
757
- const safeSiteLabel = siteLabel.replace(/'/g, "''");
758
996
  const channelKey = siteFolder.replace(/[^a-z0-9_-]/gi, '-').toLowerCase();
759
- const homeSlug = `welcome-to-${channelKey}`;
760
997
  const treeKey = 'main-tree';
761
998
  const safeWorkerName = `${siteFolder.toLowerCase().replace(/[^a-z0-9-]/g, '-')}-site`;
762
999
 
763
1000
  if (isCloudflare) {
764
- let sessionId = "REPLACE_WITH_YOUR_SESSION_KV_ID";
765
- let htmlCacheId = "REPLACE_WITH_YOUR_HTML_CACHE_KV_ID";
766
-
767
- try {
768
- const prefix = siteFolder.replace(/[^a-zA-Z0-9]/g, '_').toUpperCase();
769
- const sessionOut = execSync(`npx wrangler kv namespace create "SESSION_${prefix}"`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
770
- if (sessionOut.match(/"id":\s*"([a-f0-9]{32})"/)) sessionId = sessionOut.match(/"id":\s*"([a-f0-9]{32})"/)[1];
771
- const cacheOut = execSync(`npx wrangler kv namespace create "HTML_CACHE_${prefix}"`, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
772
- if (cacheOut.match(/"id":\s*"([a-f0-9]{32})"/)) htmlCacheId = cacheOut.match(/"id":\s*"([a-f0-9]{32})"/)[1];
773
- } catch (err) { }
1001
+ const prefix = siteFolder.replace(/[^a-zA-Z0-9]/g, '_').toUpperCase();
1002
+ const sessionId = getOrCreateKV(`SESSION_${prefix}`);
1003
+ const htmlCacheId = getOrCreateKV(`HTML_CACHE_${prefix}`);
774
1004
 
775
1005
  const siteConfig = {
776
1006
  $schema: "node_modules/wrangler/config-schema.json",
777
1007
  name: safeWorkerName,
778
1008
  compatibility_date: "2024-09-23",
779
1009
  compatibility_flags: ["nodejs_compat"],
1010
+ observability: defaultCloudflareObservability(),
780
1011
  dev: { host: "localhost", port: 4321 },
781
1012
  cache: { enabled: true },
782
1013
  assets: { directory: "./dist/client", binding: "ASSETS", run_worker_first: true },
783
1014
  kv_namespaces: [{ binding: "SESSION", id: sessionId }, { binding: "HTML_CACHE", id: htmlCacheId }],
784
1015
  services: [{ binding: "CMS_WORKER", service: workerName }],
1016
+ routes: [{ pattern: siteDomain, custom_domain: true, enabled: true, previews_enabled: false }],
785
1017
  vars: { PUBLIC_CMS_URL: cmsFullUrl, PUBLIC_API_URL: cmsFullUrl, PUBLIC_CHANNEL_ID: channelKey, PUBLIC_TREE_ID: treeKey, PUBLIC_SITE_NAME: siteLabel }
786
1018
  };
787
1019
 
788
1020
  if (siteDomain !== 'localhost:4321') siteConfig.routes = [{ pattern: siteDomain, custom_domain: true, enabled: true, previews_enabled: false }];
789
1021
  writeFileSync(join(siteDir, 'wrangler.json'), JSON.stringify(siteConfig, null, 2));
1022
+ writeWorkerSecrets(siteDir, frontendApiSecret);
790
1023
  }
791
1024
 
792
- const siteUrl = (siteDomain === 'localhost:4321' || !isCloudflare) ? `http://${siteDomain}` : `https://${siteDomain}`;
793
-
794
- const seedSql = `
795
- -- Seed data for site: ${safeSiteLabel}
796
-
797
- -- 1. Create content node
798
- INSERT INTO content_nodes (contentType, title, slug, language, status, hasUnpublishedChanges, disabledRegionsJson, dataJson, draftDataJson, publishedDataJson, publishedAt)
799
- SELECT 'page', 'Welcome to ${safeSiteLabel}', '${homeSlug}', '', 'published', 0, '{}',
800
- '{"titleSuffix":"– ${safeSiteLabel}","layoutId":"single-column","subpageLayoutId":"two-column","logoText":"${safeSiteLabel}","schemaType":"WebPage"}',
801
- '{"titleSuffix":"– ${safeSiteLabel}","layoutId":"single-column","subpageLayoutId":"two-column","logoText":"${safeSiteLabel}","schemaType":"WebPage"}',
802
- '{"titleSuffix":"– ${safeSiteLabel}","layoutId":"single-column","subpageLayoutId":"two-column","logoText":"${safeSiteLabel}","schemaType":"WebPage"}',
803
- CURRENT_TIMESTAMP
804
- WHERE NOT EXISTS (SELECT 1 FROM content_nodes WHERE slug = '${homeSlug}' AND title = 'Welcome to ${safeSiteLabel}');
805
-
806
- -- 2. Create channel
807
- INSERT OR IGNORE INTO channels (key, label, channelType, baseUrl, defaultLanguage, isHidden, dataJson)
808
- VALUES ('${channelKey}', '${safeSiteLabel}', 'website', '${siteUrl}', '', 0, '{}');
809
-
810
- -- 3. Link channelRoot in channel JSON
811
- UPDATE channels
812
- SET dataJson = json_patch(
813
- COALESCE(NULLIF(dataJson, ''), '{}'),
814
- json_object(
815
- 'channelRoot', json_object(
816
- 'href', '#node:' || (SELECT id FROM content_nodes WHERE slug = '${homeSlug}' AND title = 'Welcome to ${safeSiteLabel}' ORDER BY id DESC LIMIT 1),
817
- 'kind', 'node',
818
- 'target', '_self',
819
- 'label', 'Welcome to ${safeSiteLabel}',
820
- 'nodeId', (SELECT id FROM content_nodes WHERE slug = '${homeSlug}' AND title = 'Welcome to ${safeSiteLabel}' ORDER BY id DESC LIMIT 1)
821
- )
822
- )
823
- )
824
- WHERE key = '${channelKey}';
825
-
826
- -- 4. Create Trees & Relations
827
- INSERT OR IGNORE INTO trees (key, label, treeType, channelId, isHidden, dataJson)
828
- VALUES ('${treeKey}', 'Main Tree', 'navigation', (SELECT id FROM channels WHERE key = '${channelKey}'), 0, '{}');
829
-
830
- INSERT OR IGNORE INTO channel_trees (channelId, treeId, key)
831
- VALUES ((SELECT id FROM channels WHERE key = '${channelKey}'), (SELECT id FROM trees WHERE key = '${treeKey}'), 'main');
832
-
833
- INSERT OR IGNORE INTO node_channels (nodeId, channelId)
834
- VALUES ((SELECT id FROM content_nodes WHERE slug = '${homeSlug}' ORDER BY id DESC LIMIT 1), (SELECT id FROM channels WHERE key = '${channelKey}'));
835
-
836
- INSERT OR IGNORE INTO tree_nodes (treeId, contentId, parentId, sortOrder)
837
- VALUES ((SELECT id FROM trees WHERE key = '${treeKey}'), (SELECT id FROM content_nodes WHERE slug = '${homeSlug}' ORDER BY id DESC LIMIT 1), NULL, 0);
838
-
839
- -- 5. Node Routing (TWO records: Canonical '/' and Redirect '/slug' -> '/')
840
- INSERT OR IGNORE INTO node_routes (path, channelId, nodeId, treeId, isCanonical, redirectUrl)
841
- VALUES (
842
- '/',
843
- (SELECT id FROM channels WHERE key = '${channelKey}'),
844
- (SELECT id FROM content_nodes WHERE slug = '${homeSlug}' ORDER BY id DESC LIMIT 1),
845
- (SELECT id FROM trees WHERE key = '${treeKey}'),
846
- 1,
847
- NULL
848
- );
849
-
850
- INSERT OR IGNORE INTO node_routes (path, channelId, nodeId, treeId, isCanonical, redirectUrl)
851
- VALUES (
852
- '/${homeSlug}',
853
- (SELECT id FROM channels WHERE key = '${channelKey}'),
854
- (SELECT id FROM content_nodes WHERE slug = '${homeSlug}' ORDER BY id DESC LIMIT 1),
855
- NULL,
856
- 0,
857
- '/'
858
- );
859
- `;
1025
+ const localCmsUrl = 'http://127.0.0.1:8787';
1026
+ let envContent = `# Local Development Overrides\nPUBLIC_CMS_URL="${localCmsUrl}"\nPUBLIC_API_URL="${localCmsUrl}"\nPUBLIC_CHANNEL_ID="${channelKey}"\nPUBLIC_TREE_ID="${treeKey}"\nPUBLIC_SITE_NAME="${siteLabel.replace(/"/g, '\\"')}"\n`;
860
1027
 
861
- const workerDir = join(rootDir, 'kama-worker');
862
- if (existsSync(workerDir)) appendFileSync(join(workerDir, 'seed.sql'), seedSql);
1028
+ if (frontendApiSecret && !isCloudflare) {
1029
+ envContent += `\n# Server-to-Server API Security\nFRONTEND_API_SECRET="${frontendApiSecret}"\n`;
1030
+ }
863
1031
 
864
- writeFileSync(join(siteDir, '.env'), `# Local Development Overrides\nPUBLIC_CMS_URL="http://127.0.0.1:8787"\nPUBLIC_API_URL="http://127.0.0.1:8787"\nPUBLIC_CHANNEL_ID="${channelKey}"\nPUBLIC_TREE_ID="${treeKey}"\nPUBLIC_SITE_NAME="${siteLabel.replace(/"/g, '\\"')}"\n`);
1032
+ const productionEnvContent = isCloudflare
1033
+ ? envContent.replaceAll(localCmsUrl, cmsFullUrl)
1034
+ : envContent;
1035
+ writeFileSync(join(siteDir, '.env'), productionEnvContent);
1036
+ if (isCloudflare) {
1037
+ writeFileSync(join(siteDir, '.env.development'), envContent);
1038
+ }
1039
+ if (isCloudflare && frontendApiSecret) {
1040
+ writeFileSync(join(siteDir, '.dev.vars'), `FRONTEND_API_SECRET="${frontendApiSecret}"\n`, { mode: 0o600 });
1041
+ }
865
1042
  }
866
1043
 
867
- main().catch(console.error);
1044
+ main().catch(error => {
1045
+ console.error(error);
1046
+ process.exitCode = 1;
1047
+ });