@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.2

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 (114) hide show
  1. package/CHANGELOG.md +578 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +29 -0
  9. package/dist/admin/BookingAdmin.js +338 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +47 -0
  14. package/dist/admin/booking-detail.js +159 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +41 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +7 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +184 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1112 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,575 @@
1
+ #!/usr/bin/env node
2
+ // booking-engine — project setup and safety checks for @profitstudio/booking-engine.
3
+ // init [--preset <id>] add engine migrations, the booking-mailer Edge Function, lock file,
4
+ // .env.example and BOOKING_ENGINE.md
5
+ // sync after upgrading the package: add new migrations, update the mailer
6
+ // doctor [--dist <dir>] check versions, engine files, keys and build output
7
+ // connect [--admin <email>] [--site-url <https://…>] [--yes] [--check] connect the site to its Supabase project, turn on emails
8
+ // photos [manifest] crop and export the site's photos (needs the project's sharp)
9
+ // mailer-sql [--url <project-url>] print the one-time SQL that lets the database send emails
10
+ // migrations list engine migrations and their status
11
+ // version print versions
12
+ // No network access and no telemetry, except `connect`, which drives the Supabase CLI
13
+ // for the project in .env.local. Never reads or prints secret keys.
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
+ const MANIFEST = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'engine.manifest.json'), 'utf8'));
21
+ const LOCK_FILE = 'booking-engine.lock.json';
22
+ const MIGRATIONS_DIR = path.join('supabase', 'migrations');
23
+ const FUNCTIONS_DIR = path.join('supabase', 'functions');
24
+ const CONFIG_TOML = path.join('supabase', 'config.toml');
25
+ // The Supabase CLI line this engine is verified with (3.x changed its confirmations and is not verified yet).
26
+ const SUPABASE = 'npx supabase@2';
27
+ // --use-api bundles on Supabase's servers: no Docker needed on the owner's computer.
28
+ const DEPLOY = `${SUPABASE} functions deploy booking-mailer --no-verify-jwt --use-api`;
29
+ const ENV_KEYS = ['VITE_SUPABASE_URL', 'VITE_SUPABASE_PUBLISHABLE_KEY'];
30
+
31
+ const color = (code) => (s) => (process.stdout.isTTY ? `\x1b[${code}m${s}\x1b[0m` : s);
32
+ const green = color(32);
33
+ const yellow = color(33);
34
+ const red = color(31);
35
+ const bold = color(1);
36
+
37
+ function sha256(text) {
38
+ return crypto.createHash('sha256').update(text).digest('hex');
39
+ }
40
+
41
+ function readLock(cwd) {
42
+ const file = path.join(cwd, LOCK_FILE);
43
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
44
+ }
45
+
46
+ function writeLock(cwd, lock) {
47
+ fs.writeFileSync(path.join(cwd, LOCK_FILE), JSON.stringify(lock, null, 2) + '\n');
48
+ }
49
+
50
+ function timestamp(date) {
51
+ const p = (n) => String(n).padStart(2, '0');
52
+ return `${date.getUTCFullYear()}${p(date.getUTCMonth() + 1)}${p(date.getUTCDate())}${p(date.getUTCHours())}${p(date.getUTCMinutes())}${p(date.getUTCSeconds())}`;
53
+ }
54
+
55
+ /** Next migration version: now, but always after every existing migration file. */
56
+ function nextVersions(cwd, count) {
57
+ const dir = path.join(cwd, MIGRATIONS_DIR);
58
+ const existing = fs.existsSync(dir)
59
+ ? fs.readdirSync(dir).map((f) => /^(\d{14})_/.exec(f)?.[1]).filter(Boolean).sort()
60
+ : [];
61
+ let t = new Date();
62
+ const latest = existing.at(-1);
63
+ if (latest && timestamp(t) <= latest) {
64
+ const y = Number(latest.slice(0, 4));
65
+ const mo = Number(latest.slice(4, 6)) - 1;
66
+ const d = Number(latest.slice(6, 8));
67
+ t = new Date(Date.UTC(y, mo, d, Number(latest.slice(8, 10)), Number(latest.slice(10, 12)), Number(latest.slice(12, 14)) + 1));
68
+ }
69
+ return Array.from({ length: count }, (_, i) => timestamp(new Date(t.getTime() + i * 1000)));
70
+ }
71
+
72
+ /** Verify installed engine migrations are byte-identical to what the engine shipped. */
73
+ function verifyInstalled(cwd, lock) {
74
+ const problems = [];
75
+ for (const m of lock?.migrations ?? []) {
76
+ const file = path.join(cwd, m.file);
77
+ if (!fs.existsSync(file)) {
78
+ problems.push(`${m.file} is missing (engine migration ${m.id}).`);
79
+ continue;
80
+ }
81
+ const actual = sha256(fs.readFileSync(file, 'utf8'));
82
+ const shipped = MANIFEST.migrations.find((x) => x.id === m.id)?.sha256 ?? m.sha256;
83
+ if (actual !== m.sha256 || actual !== shipped) {
84
+ problems.push(`${m.file} was modified. Engine migrations must not be edited — restore it from the package.`);
85
+ }
86
+ }
87
+ return problems;
88
+ }
89
+
90
+ function installMigrations(cwd, lock) {
91
+ const have = new Set((lock?.migrations ?? []).map((m) => m.id));
92
+ const pending = MANIFEST.migrations.filter((m) => !have.has(m.id));
93
+ if (!pending.length) return [];
94
+ fs.mkdirSync(path.join(cwd, MIGRATIONS_DIR), { recursive: true });
95
+ const versions = nextVersions(cwd, pending.length);
96
+ return pending.map((m, i) => {
97
+ const sql = fs.readFileSync(path.join(PKG_ROOT, m.file), 'utf8');
98
+ if (sha256(sql) !== m.sha256) throw new Error(`Package file ${m.file} does not match its manifest. Reinstall the package.`);
99
+ const rel = path.join(MIGRATIONS_DIR, `${versions[i]}_booking_engine_${m.id}.sql`);
100
+ fs.writeFileSync(path.join(cwd, rel), sql);
101
+ return { id: m.id, file: rel.split(path.sep).join('/'), sha256: m.sha256, schemaVersion: m.schemaVersion };
102
+ });
103
+ }
104
+
105
+ /** Every file this package ships must match its manifest — checked before anything is written. */
106
+ function verifyPackage() {
107
+ const bad = [];
108
+ for (const m of MANIFEST.migrations) {
109
+ if (sha256(fs.readFileSync(path.join(PKG_ROOT, m.file), 'utf8')) !== m.sha256) bad.push(m.file);
110
+ }
111
+ for (const fn of MANIFEST.functions ?? []) {
112
+ for (const f of fn.files) {
113
+ const file = path.join(PKG_ROOT, 'functions', fn.name, f.path);
114
+ if (!fs.existsSync(file) || sha256(fs.readFileSync(file, 'utf8')) !== f.sha256) bad.push(`functions/${fn.name}/${f.path}`);
115
+ }
116
+ }
117
+ if (bad.length) fail(`This copy of ${MANIFEST.package} is damaged (${bad.join(', ')}). Reinstall the package; nothing was changed.`);
118
+ }
119
+
120
+ /** Engine function files whose content no longer matches the lock (edited by hand). */
121
+ function verifyFunctions(cwd, lock) {
122
+ const problems = [];
123
+ for (const [name, entry] of Object.entries(lock?.functions ?? {})) {
124
+ for (const [file, hash] of Object.entries(entry.files ?? {})) {
125
+ const target = path.join(cwd, FUNCTIONS_DIR, name, file);
126
+ if (fs.existsSync(target) && sha256(fs.readFileSync(target, 'utf8')) !== hash) {
127
+ problems.push(`${path.join(FUNCTIONS_DIR, name, file)} was modified. Engine function files must not be edited — delete it and run "npx booking-engine sync" to restore it.`);
128
+ }
129
+ }
130
+ }
131
+ return problems;
132
+ }
133
+
134
+ /**
135
+ * Copy the engine's Edge Functions into supabase/functions/. Unlike migrations
136
+ * (history, never rewritten), function files are replaced by newer versions;
137
+ * a file edited by hand is never overwritten (verifyFunctions runs first).
138
+ */
139
+ function installFunctions(cwd, lock) {
140
+ const changed = [];
141
+ const next = {};
142
+ for (const fn of MANIFEST.functions ?? []) {
143
+ next[fn.name] = { files: {} };
144
+ for (const f of fn.files) {
145
+ const content = fs.readFileSync(path.join(PKG_ROOT, 'functions', fn.name, f.path), 'utf8');
146
+ if (sha256(content) !== f.sha256) throw new Error(`Package file functions/${fn.name}/${f.path} does not match its manifest. Reinstall the package.`);
147
+ const rel = path.join(FUNCTIONS_DIR, fn.name, f.path);
148
+ const target = path.join(cwd, rel);
149
+ next[fn.name].files[f.path] = f.sha256;
150
+ if (fs.existsSync(target) && sha256(fs.readFileSync(target, 'utf8')) === f.sha256) continue;
151
+ fs.mkdirSync(path.dirname(target), { recursive: true });
152
+ fs.writeFileSync(target, content);
153
+ changed.push(rel.split(path.sep).join('/'));
154
+ }
155
+ // Files a newer engine no longer ships (unmodified, so safe to remove).
156
+ for (const old of Object.keys(lock?.functions?.[fn.name]?.files ?? {})) {
157
+ if (next[fn.name].files[old]) continue;
158
+ const target = path.join(cwd, FUNCTIONS_DIR, fn.name, old);
159
+ if (fs.existsSync(target)) {
160
+ fs.rmSync(target);
161
+ changed.push(`${path.join(FUNCTIONS_DIR, fn.name, old).split(path.sep).join('/')} (removed)`);
162
+ }
163
+ }
164
+ }
165
+ return { changed, functions: next };
166
+ }
167
+
168
+ const CONFIG_COMMENT = '# Booking Engine: the mailer checks its own token (secret BOOKING_MAILER_TOKEN), not a Supabase JWT (see supabase/functions/booking-mailer/index.ts).';
169
+ // Written by 2.0.0-alpha.4; no longer true (ADR 0003). Replaced on sync.
170
+ const OLD_CONFIG_COMMENT = '# Booking Engine: the mailer accepts only a project secret key (see supabase/functions/booking-mailer/index.ts).';
171
+
172
+ /** Supabase CLI config: the mailer checks its caller's token itself, so the platform JWT check is off. */
173
+ function ensureFunctionConfig(cwd) {
174
+ const file = path.join(cwd, CONFIG_TOML);
175
+ if (!fs.existsSync(file)) return 'missing';
176
+ const text = fs.readFileSync(file, 'utf8');
177
+ if (/^\[functions\.booking-mailer\]/m.test(text)) {
178
+ if (text.includes(OLD_CONFIG_COMMENT)) fs.writeFileSync(file, text.replace(OLD_CONFIG_COMMENT, CONFIG_COMMENT));
179
+ return 'present';
180
+ }
181
+ const prefix = text.endsWith('\n') ? '' : '\n';
182
+ fs.writeFileSync(file, `${text}${prefix}\n${CONFIG_COMMENT}\n[functions.booking-mailer]\nverify_jwt = false\n`);
183
+ return 'added';
184
+ }
185
+
186
+ function ensureLines(file, lines, header) {
187
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
188
+ const keys = new Set(existing.split(/\r?\n/).map((l) => l.split('=')[0].trim()));
189
+ const missing = lines.filter((l) => !keys.has(l.split('=')[0].trim()));
190
+ if (!missing.length) return false;
191
+ const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
192
+ fs.writeFileSync(file, existing + prefix + (header ? `${header}\n` : '') + missing.join('\n') + '\n');
193
+ return true;
194
+ }
195
+
196
+ function cmdInit(cwd, args) {
197
+ if (!fs.existsSync(path.join(cwd, 'package.json'))) {
198
+ fail('No package.json here. Run this inside your project folder (after creating the Vite app).');
199
+ }
200
+ const presetIndex = args.indexOf('--preset');
201
+ const preset = presetIndex >= 0 ? args[presetIndex + 1] : null;
202
+ if (preset && !MANIFEST.presets.includes(preset)) {
203
+ fail(`Unknown preset "${preset}". Available: ${MANIFEST.presets.join(', ')}`);
204
+ }
205
+ verifyPackage();
206
+ const lock = readLock(cwd);
207
+ const problems = [...verifyInstalled(cwd, lock), ...verifyFunctions(cwd, lock)];
208
+ if (problems.length) fail(problems.join('\n'));
209
+ const added = installMigrations(cwd, lock);
210
+ const fns = installFunctions(cwd, lock);
211
+ const next = {
212
+ package: MANIFEST.package,
213
+ version: MANIFEST.version,
214
+ schemaVersion: MANIFEST.schemaVersion,
215
+ ...(preset ? { preset } : lock?.preset ? { preset: lock.preset } : {}),
216
+ migrations: [...(lock?.migrations ?? []), ...added],
217
+ functions: fns.functions,
218
+ };
219
+ writeLock(cwd, next);
220
+ const config = ensureFunctionConfig(cwd);
221
+ ensureLines(
222
+ path.join(cwd, '.env.example'),
223
+ ENV_KEYS.map((k) => `${k}=`),
224
+ '# Booking Engine — copy to .env.local and fill in from Supabase (Project URL + publishable key). Never put a secret key here.',
225
+ );
226
+ ensureLines(path.join(cwd, '.gitignore'), ['.env', '.env.local', '.env.*.local'], '# Booking Engine: never commit keys');
227
+ ensureLines(path.join(cwd, '.gitignore'), ['supabase/.temp/'], "# Supabase CLI: this computer's link to the project");
228
+ fs.copyFileSync(path.join(PKG_ROOT, 'templates', 'BOOKING_ENGINE.md'), path.join(cwd, 'BOOKING_ENGINE.md'));
229
+
230
+ console.log(bold(`Booking Engine ${MANIFEST.version} (database schema ${MANIFEST.schemaVersion})`));
231
+ for (const m of added) console.log(green(` + ${m.file}`));
232
+ if (!added.length) console.log(' Migrations already installed.');
233
+ for (const f of fns.changed) console.log(green(` + ${f}`));
234
+ if (config === 'added') console.log(green(` ✓ ${CONFIG_TOML}: [functions.booking-mailer] verify_jwt = false`));
235
+ console.log(green(` ✓ ${LOCK_FILE}`));
236
+ console.log(green(' ✓ .env.example, .gitignore'));
237
+ console.log(green(' ✓ BOOKING_ENGINE.md (the rules for this project)'));
238
+ if (preset) console.log(` Preset: ${preset}`);
239
+ console.log(
240
+ '\nNext: build the site — node_modules/@profitstudio/booking-engine/docs/BUILD-A-SITE.md.\n' +
241
+ 'Then connect Supabase and email (INTEGRATION.md §11):\n' +
242
+ ' 1. .env.local: VITE_SUPABASE_URL and VITE_SUPABASE_PUBLISHABLE_KEY (Supabase → Project Settings → API Keys)\n' +
243
+ ` 2. ${SUPABASE} login\n` +
244
+ ' 3. npx booking-engine connect --admin you@example.com (it says what else is yours to do)',
245
+ );
246
+ }
247
+
248
+ function cmdSync(cwd) {
249
+ const lock = readLock(cwd);
250
+ if (!lock) fail(`No ${LOCK_FILE}. Run "npx booking-engine init" first.`);
251
+ verifyPackage();
252
+ const problems = [...verifyInstalled(cwd, lock), ...verifyFunctions(cwd, lock)];
253
+ if (problems.length) fail(problems.join('\n'));
254
+ const added = installMigrations(cwd, lock);
255
+ const fns = installFunctions(cwd, lock);
256
+ writeLock(cwd, {
257
+ ...lock,
258
+ version: MANIFEST.version,
259
+ schemaVersion: MANIFEST.schemaVersion,
260
+ migrations: [...lock.migrations, ...added],
261
+ functions: fns.functions,
262
+ });
263
+ const config = ensureFunctionConfig(cwd);
264
+ fs.copyFileSync(path.join(PKG_ROOT, 'templates', 'BOOKING_ENGINE.md'), path.join(cwd, 'BOOKING_ENGINE.md'));
265
+ const configLine = () => console.log(green(` ✓ ${CONFIG_TOML}: [functions.booking-mailer] verify_jwt = false`));
266
+ if (!added.length && !fns.changed.length) {
267
+ console.log(green(`Up to date: engine ${MANIFEST.version}, schema ${MANIFEST.schemaVersion}. No new migrations.`));
268
+ if (config === 'added') configLine();
269
+ return;
270
+ }
271
+ console.log(bold(`Engine ${lock.version} → ${MANIFEST.version}.`));
272
+ for (const m of added) console.log(green(` + ${m.file}`));
273
+ for (const f of fns.changed) console.log(green(` + ${f}`));
274
+ if (config === 'added') configLine();
275
+ console.log(green(' ✓ BOOKING_ENGINE.md (engine-owned rules, replaced — keep your own rules in CLAUDE.md)'));
276
+ if (added.length) {
277
+ console.log(
278
+ '\nBefore applying: back up your data (Supabase dashboard → Database → Backups, or export your bookings).\n' +
279
+ `Then review and apply: ${SUPABASE} db push --dry-run → ${SUPABASE} db push`,
280
+ );
281
+ }
282
+ if (fns.changed.length) console.log(`Then deploy the updated mailer: ${DEPLOY}`);
283
+ console.log('Read the upgrade notes: node_modules/@profitstudio/booking-engine/CHANGELOG.md');
284
+ }
285
+
286
+ function decodeJwtRole(token) {
287
+ const parts = token.split('.');
288
+ if (parts.length !== 3) return null;
289
+ try {
290
+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')).role ?? null;
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+
296
+ function looksSecret(value) {
297
+ if (/sb_secret_[A-Za-z0-9_-]{8,}/.test(value)) return true;
298
+ // An email provider key (Resend: re_…) belongs only in Edge Function secrets.
299
+ if (/\bre_[A-Za-z0-9]{6,}_[A-Za-z0-9]{12,}\b/.test(value)) return true;
300
+ for (const jwt of value.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g) ?? []) {
301
+ if (decodeJwtRole(jwt) === 'service_role') return true;
302
+ }
303
+ return false;
304
+ }
305
+
306
+ function walk(dir, exts, out = []) {
307
+ if (!fs.existsSync(dir)) return out;
308
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
309
+ if (entry.name === 'node_modules' || entry.name.startsWith('.git')) continue;
310
+ const full = path.join(dir, entry.name);
311
+ if (entry.isDirectory()) walk(full, exts, out);
312
+ else if (!exts || exts.includes(path.extname(entry.name))) out.push(full);
313
+ }
314
+ return out;
315
+ }
316
+
317
+ /** KEY=value pairs of an env file, read as Vite reads them (quotes removed, inline comments dropped). */
318
+ function readEnvFile(file) {
319
+ const out = {};
320
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
321
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
322
+ if (!m) continue;
323
+ const quoted = /^(['"`])([\s\S]*?)\1/.exec(m[2].trim());
324
+ out[m[1]] = quoted ? quoted[2] : m[2].replace(/\s+#.*$/, '').trim();
325
+ }
326
+ return out;
327
+ }
328
+
329
+ async function cmdDoctor(cwd, args) {
330
+ // The same connection check that stops a website build (dist/config.js); only doctor needs it.
331
+ const { BACKEND_ENV, BACKEND_ENV_ALIASES, checkBackendEnv } = await import('../dist/config.js').catch(() =>
332
+ fail(`This copy of ${MANIFEST.package} is damaged (dist/config.js). Reinstall the package; nothing was changed.`),
333
+ );
334
+ const errors = [];
335
+ const warnings = [];
336
+ const okLines = [];
337
+ const lock = readLock(cwd);
338
+
339
+ // 1. Versions and engine files
340
+ if (!lock) {
341
+ errors.push(`No ${LOCK_FILE}. Run "npx booking-engine init".`);
342
+ } else {
343
+ const cmp = compare(MANIFEST.version, lock.version);
344
+ if (cmp > 0) warnings.push(`Installed engine ${MANIFEST.version} is newer than the lock (${lock.version}). Run "npx booking-engine sync".`);
345
+ if (cmp < 0) errors.push(`Installed engine ${MANIFEST.version} is OLDER than the lock (${lock.version}). Reinstall ${lock.version}.`);
346
+ errors.push(...verifyInstalled(cwd, lock));
347
+ errors.push(...verifyFunctions(cwd, lock));
348
+ const have = new Set(lock.migrations.map((m) => m.id));
349
+ const pending = MANIFEST.migrations.filter((m) => !have.has(m.id));
350
+ if (pending.length && cmp === 0) errors.push(`Engine migrations missing from this project: ${pending.map((m) => m.id).join(', ')}.`);
351
+ for (const fn of MANIFEST.functions ?? []) {
352
+ const locked = lock.functions?.[fn.name]?.files ?? {};
353
+ const missing = fn.files.filter((f) => !fs.existsSync(path.join(cwd, FUNCTIONS_DIR, fn.name, f.path)));
354
+ if (missing.length) errors.push(`${path.join(FUNCTIONS_DIR, fn.name)} is incomplete. Run "npx booking-engine sync".`);
355
+ else if (fn.files.some((f) => locked[f.path] !== f.sha256) && cmp === 0) {
356
+ warnings.push(`The ${fn.name} function is older than the installed engine. Run "npx booking-engine sync", then: ${DEPLOY}`);
357
+ }
358
+ }
359
+ if (!errors.length) {
360
+ okLines.push(`Engine ${lock.version}, schema ${lock.schemaVersion}; ${lock.migrations.length} engine migration(s) and the mailer function intact.`);
361
+ }
362
+ const toml = path.join(cwd, CONFIG_TOML);
363
+ if (fs.existsSync(toml)) {
364
+ const block = /^\[functions\.booking-mailer\]([^[]*)/m.exec(fs.readFileSync(toml, 'utf8'))?.[1] ?? null;
365
+ if (block === null) warnings.push(`${CONFIG_TOML} has no [functions.booking-mailer] section: deploy with --no-verify-jwt (or run "npx booking-engine sync").`);
366
+ else if (/verify_jwt\s*=\s*true/.test(block)) errors.push(`${CONFIG_TOML}: booking-mailer must have verify_jwt = false (the database calls it with the mailer token, not a user token).`);
367
+ }
368
+ }
369
+
370
+ // 2. Environment files: only public values may be exposed to the browser
371
+ const envFiles = fs.readdirSync(cwd).filter((f) => /^\.env(\..+)?$/.test(f) && f !== '.env.example');
372
+ const exposedSecret = new Set();
373
+ for (const f of envFiles) {
374
+ for (const [key, value] of Object.entries(readEnvFile(path.join(cwd, f)))) {
375
+ if (key.startsWith('VITE_') && (looksSecret(value) || /SECRET|SERVICE_ROLE|RESEND/.test(key))) {
376
+ errors.push(`${f}: ${key} exposes a SECRET key to the browser. Remove it and rotate the key (Supabase or Resend).`);
377
+ exposedSecret.add(key);
378
+ } else if (/RESEND/.test(key) && value) {
379
+ warnings.push(`${f}: ${key} — email provider keys belong in Supabase Edge Function secrets, not in the website's env files.`);
380
+ }
381
+ }
382
+ }
383
+ // The two connection values as `npm run dev` and a production build see them (the
384
+ // same check stops the build): half a pair, a misnamed variable, a dashboard address…
385
+ const connection = {};
386
+ for (const mode of ['development', 'production']) {
387
+ const env = {};
388
+ for (const f of ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`]) {
389
+ if (fs.existsSync(path.join(cwd, f))) Object.assign(env, readEnvFile(path.join(cwd, f)));
390
+ }
391
+ for (const name of [BACKEND_ENV.url, BACKEND_ENV.key, ...Object.keys(BACKEND_ENV_ALIASES)]) {
392
+ if (process.env[name] !== undefined) env[name] = process.env[name]; // like Vite: the shell wins
393
+ }
394
+ connection[mode] = checkBackendEnv(env);
395
+ }
396
+ const reported = new Set();
397
+ for (const mode of ['development', 'production']) {
398
+ for (const problem of connection[mode].problems) {
399
+ if (reported.has(problem)) continue;
400
+ reported.add(problem);
401
+ if (problem.startsWith(`${BACKEND_ENV.key} holds a SECRET`) && exposedSecret.has(BACKEND_ENV.key)) continue;
402
+ errors.push(mode === 'production' && !connection.development.problems.includes(problem) ? `Production build: ${problem}` : problem);
403
+ }
404
+ }
405
+ if (connection.development.status === 'configured') okLines.push('Supabase connection configured (Project URL and publishable key).');
406
+ else if (connection.development.status === 'none') okLines.push('No Supabase connection yet: the site runs in preview mode in development.');
407
+
408
+ // 3. Source code: the engine owns all data access
409
+ const sources = walk(path.join(cwd, 'src'), ['.ts', '.tsx', '.js', '.jsx', '.mjs']);
410
+ for (const file of sources) {
411
+ const text = fs.readFileSync(file, 'utf8');
412
+ const rel = path.relative(cwd, file);
413
+ if (looksSecret(text)) errors.push(`${rel}: contains a secret key.`);
414
+ if (/from\s+['"]@supabase\/supabase-js['"]/.test(text)) {
415
+ warnings.push(`${rel}: imports @supabase/supabase-js directly. Use the engine client so security rules stay in one place.`);
416
+ }
417
+ if (/\.schema\(\s*['"]booking['"]\s*\)|\.rpc\(\s*['"]booking_/.test(text)) {
418
+ warnings.push(`${rel}: calls the booking database directly. Use createBookingEngine() methods instead.`);
419
+ }
420
+ if (/\bcreateBooking\b/.test(text)) {
421
+ errors.push(`${rel}: uses createBooking(), closed since 2.0.0-alpha.4 (it always returns VERIFICATION_REQUIRED, so no booking can be made). Use requestBooking() + verifyBooking() (INTEGRATION.md, "Upgrading from 2.0.0-alpha.3").`);
422
+ }
423
+ }
424
+ if (!fs.existsSync(path.join(cwd, 'admin', 'index.html'))) {
425
+ warnings.push('No admin/index.html: mount <BookingAdmin> on its own page (see INTEGRATION.md, "Admin dashboard").');
426
+ }
427
+
428
+ // 4. Build output must not contain secrets
429
+ const distArg = args.indexOf('--dist');
430
+ const distValue = distArg >= 0 && args[distArg + 1] && !args[distArg + 1].startsWith('--') ? args[distArg + 1] : 'dist';
431
+ const dist = path.resolve(cwd, distValue);
432
+ if (fs.existsSync(dist)) {
433
+ const files = walk(dist, null).filter((f) => /\.(js|mjs|html|css|json|map|txt)$/.test(f));
434
+ const leaks = files.filter((f) => looksSecret(fs.readFileSync(f, 'utf8')));
435
+ if (leaks.length) errors.push(`Build output contains a secret key: ${leaks.map((f) => path.relative(cwd, f)).join(', ')}`);
436
+ else okLines.push(`Build output: no secret keys found (${files.length} files scanned).`);
437
+ } else if (distArg >= 0) {
438
+ // Asked to scan a build that is not there: never report "passed" for files nobody looked at.
439
+ errors.push(`No build output at ${distValue}: run the build first (npm run build), or give the folder: --dist <dir>.`);
440
+ }
441
+
442
+ for (const l of okLines) console.log(green(`✓ ${l}`));
443
+ for (const w of warnings) console.log(yellow(`! ${w}`));
444
+ for (const e of errors) console.log(red(`✗ ${e}`));
445
+ if (errors.length) process.exit(1);
446
+ console.log(bold(warnings.length ? 'Doctor finished with warnings.' : 'All checks passed.'));
447
+ }
448
+
449
+ /** The project URL from the arguments or the website's env files (public value). */
450
+ function projectUrl(cwd, args) {
451
+ const i = args.indexOf('--url');
452
+ if (i >= 0 && args[i + 1]) return args[i + 1].replace(/\/+$/, '');
453
+ for (const f of ['.env.local', '.env', '.env.production']) {
454
+ const file = path.join(cwd, f);
455
+ if (!fs.existsSync(file)) continue;
456
+ const m = /^\s*VITE_SUPABASE_URL\s*=\s*['"]?([^'"\s]+)/m.exec(fs.readFileSync(file, 'utf8'));
457
+ if (m?.[1]) return m[1].replace(/\/+$/, '');
458
+ }
459
+ return 'https://YOUR-PROJECT-REF.supabase.co';
460
+ }
461
+
462
+ /**
463
+ * The one-time SQL (Supabase → SQL Editor) that lets the database start the
464
+ * mailer: pg_net + pg_cron, the every-minute job, and the function address.
465
+ * Its last statement returns the mailer-only token to copy into the Edge
466
+ * Function secret BOOKING_MAILER_TOKEN. No Supabase key is involved.
467
+ */
468
+ async function cmdMailerSql(cwd, args) {
469
+ // The same statements `connect` runs for you (one source).
470
+ const { mailerStatements } = await import('./connect.mjs');
471
+ const s = mailerStatements(projectUrl(cwd, args)).map((sql) => `${sql};`);
472
+ console.log(`-- Booking Engine ${MANIFEST.version}: let the database send booking emails.
473
+ -- Easiest: npx booking-engine connect does all of this and stores the token for you.
474
+ -- By hand: run once in Supabase → SQL Editor, after "${DEPLOY}"
475
+ -- and after adding the RESEND_API_KEY and BOOKING_EMAIL_FROM function secrets.
476
+ -- Safe to run again: it updates what exists and keeps the same token.
477
+
478
+ -- 1. Extensions: pg_net sends emails right away, pg_cron retries and sends expiry notices.
479
+ ${s.slice(0, 4).join('\n')}
480
+
481
+ -- 2. Every minute: release lapsed holds, retry failed emails, send expiry notices.
482
+ -- (It only calls the mailer when an email is due.) Keeps 7 days of job history.
483
+ ${s.slice(4, 6).join('\n')}
484
+
485
+ -- 3. Where the mailer is. The result row shows the MAILER TOKEN: copy it into
486
+ -- Edge Functions → Secrets as BOOKING_MAILER_TOKEN. The token can only start
487
+ -- the mailer (it is not a Supabase key). New token: add , p_rotate => true
488
+ ${s[6]}`);
489
+ }
490
+
491
+ function cmdMigrations(cwd) {
492
+ const lock = readLock(cwd);
493
+ const have = new Map((lock?.migrations ?? []).map((m) => [m.id, m]));
494
+ for (const m of MANIFEST.migrations) {
495
+ const installed = have.get(m.id);
496
+ console.log(`${installed ? green('installed') : yellow('pending ')} ${m.id} (schema ${m.schemaVersion})${installed ? ` ${installed.file}` : ''}`);
497
+ }
498
+ }
499
+
500
+ function compare(a, b) {
501
+ const parse = (v) => {
502
+ const [core, pre = ''] = v.split('-');
503
+ return { nums: core.split('.').map(Number), pre };
504
+ };
505
+ const x = parse(a);
506
+ const y = parse(b);
507
+ for (let i = 0; i < 3; i++) if (x.nums[i] !== y.nums[i]) return x.nums[i] < y.nums[i] ? -1 : 1;
508
+ if (x.pre === y.pre) return 0;
509
+ if (!x.pre) return 1;
510
+ if (!y.pre) return -1;
511
+ return x.pre.localeCompare(y.pre, 'en', { numeric: true });
512
+ }
513
+
514
+ function fail(message) {
515
+ console.error(red(message));
516
+ process.exit(1);
517
+ }
518
+
519
+ const [command, ...args] = process.argv.slice(2);
520
+ const cwd = process.cwd();
521
+ switch (command) {
522
+ case 'init':
523
+ cmdInit(cwd, args);
524
+ break;
525
+ case 'sync':
526
+ cmdSync(cwd);
527
+ break;
528
+ case 'doctor':
529
+ await cmdDoctor(cwd, args);
530
+ break;
531
+ case 'migrations':
532
+ cmdMigrations(cwd);
533
+ break;
534
+ case 'mailer-sql':
535
+ await cmdMailerSql(cwd, args);
536
+ break;
537
+ case 'connect': {
538
+ const { checkBackendEnv } = await import('../dist/config.js').catch(() =>
539
+ fail(`This copy of ${MANIFEST.package} is damaged (dist/config.js). Reinstall the package; nothing was changed.`),
540
+ );
541
+ const { connect } = await import('./connect.mjs');
542
+ process.exitCode = await connect(cwd, args, { readLock, readEnvFile, checkBackendEnv, ensureFunctionConfig, colors: { green, yellow, red, bold } });
543
+ break;
544
+ }
545
+ case 'photos': {
546
+ const { preparePhotos } = await import('./photos.mjs');
547
+ try {
548
+ for (const line of await preparePhotos(cwd, args)) console.log(line);
549
+ } catch (error) {
550
+ fail(error.userFacing ? error.message : `Preparing photos failed: ${error.message}`);
551
+ }
552
+ break;
553
+ }
554
+ case 'version':
555
+ case '--version':
556
+ console.log(`${MANIFEST.package} ${MANIFEST.version} (schema ${MANIFEST.schemaVersion}, requires ${MANIFEST.requiredSchemaVersion})`);
557
+ break;
558
+ default:
559
+ console.log(`booking-engine ${MANIFEST.version}
560
+
561
+ init [--preset <id>] add engine migrations, the booking-mailer function, ${LOCK_FILE},
562
+ .env.example and BOOKING_ENGINE.md
563
+ sync after upgrading the package: add its new migrations, update the mailer
564
+ doctor [--dist <dir>] check versions, engine files, keys and build output
565
+ connect [--admin <email>] [--site-url <https://…>] [--yes] [--check]
566
+ connect this site to its Supabase project and turn on booking emails:
567
+ link, migrations, owner, mailer, its token; says exactly what is yours to do
568
+ photos [manifest] crop and export the site's photos (AVIF + WebP widths) from photos/photos.json
569
+ mailer-sql [--url <u>] print the one-time SQL that lets the database send booking emails (connect runs it)
570
+ migrations list engine migrations and their status
571
+ version print versions
572
+
573
+ Presets: ${MANIFEST.presets.join(', ')}`);
574
+ if (command && command !== 'help' && command !== '--help') process.exit(1);
575
+ }