@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,408 @@
1
+ // booking-engine connect — connect this website to its own Supabase project and
2
+ // turn on booking emails, using the Supabase CLI (npx supabase@2).
3
+ //
4
+ // npx booking-engine connect [--admin you@example.com] [--site-url https://…] [--yes] [--check]
5
+ //
6
+ // Every step looks before it acts and is safe to run again. It works only on the
7
+ // project named in .env.local (VITE_SUPABASE_URL) and refuses when this folder
8
+ // is linked to another one. It never prints, logs or stores a secret: the mailer
9
+ // token goes from the database straight into an Edge Function secret through a
10
+ // private temporary file. Steps only the owner can do (accounts, passwords, the
11
+ // Resend key) stop the run with the exact action and exit code 2.
12
+ //
13
+ // --check look only: report every step, change nothing
14
+ // --yes apply database migrations without asking (after reading the list)
15
+ // --admin make this Supabase Auth user the dashboard's owner
16
+ // --site-url the live website's address: owner alerts get an “Open your
17
+ // dashboard” button (stored as the BOOKING_ADMIN_URL secret)
18
+ import crypto from 'node:crypto';
19
+ import fs from 'node:fs';
20
+ import os from 'node:os';
21
+ import path from 'node:path';
22
+ import readline from 'node:readline/promises';
23
+ import { spawnSync } from 'node:child_process';
24
+
25
+ const REF_RE = /^([a-z0-9]{20})\.supabase\.co$/;
26
+ const EMAIL_RE = /^[^@\s'"<>()]+@[^@\s'"<>()]+\.[^@\s'"<>()]{2,}$/;
27
+ const EMAIL_SECRETS = ['RESEND_API_KEY', 'BOOKING_EMAIL_FROM'];
28
+ const SUPABASE = 'npx supabase@2';
29
+
30
+ /** "https://example.com" (or …/admin/) → "https://example.com/admin/"; null when not an https address. */
31
+ export function adminUrl(siteUrl) {
32
+ let u;
33
+ try {
34
+ u = new URL(String(siteUrl).trim());
35
+ } catch {
36
+ return null;
37
+ }
38
+ if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash) return null;
39
+ const base = u.pathname.replace(/\/admin\/?$/, '/').replace(/\/?$/, '/');
40
+ return `${u.origin}${base}admin/`;
41
+ }
42
+
43
+ /** Keeps the Supabase CLI's link state (project ref, pooler address) out of Git. */
44
+ export function ignoreSupabaseTemp(cwd) {
45
+ const file = path.join(cwd, '.gitignore');
46
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
47
+ if (/^\/?supabase\/\.temp\/?\s*$/m.test(existing)) return false;
48
+ const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
49
+ fs.writeFileSync(file, `${existing}${prefix}# Supabase CLI: this computer's link to the project\nsupabase/.temp/\n`);
50
+ return true;
51
+ }
52
+
53
+ /** Hides anything that could be a secret before text from the CLI is shown. */
54
+ export function redact(text) {
55
+ return String(text)
56
+ .replace(/\b[0-9a-f]{64}\b/g, '[hidden]')
57
+ .replace(/sb_secret_[A-Za-z0-9_-]+/g, 'sb_secret_[hidden]')
58
+ .replace(/\bre_[A-Za-z0-9_]{8,}/g, 're_[hidden]')
59
+ .replace(/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, '[hidden token]');
60
+ }
61
+
62
+ /** The rows of a `supabase db query` answer (JSON), or the error it reported. */
63
+ export function parseQueryOutput(text) {
64
+ const start = text.indexOf('{');
65
+ const end = text.lastIndexOf('}');
66
+ if (start < 0 || end < start) return { ok: false, error: redact(text.trim().split('\n').slice(-3).join(' ') || 'no answer') };
67
+ try {
68
+ const json = JSON.parse(text.slice(start, end + 1));
69
+ if (json._tag === 'Error') return { ok: false, error: redact(json.error?.message ?? 'query failed') };
70
+ return { ok: true, rows: Array.isArray(json.rows) ? json.rows : [] };
71
+ } catch {
72
+ return { ok: false, error: redact(text.trim().split('\n').slice(-3).join(' ')) };
73
+ }
74
+ }
75
+
76
+ const sqlText = (s) => `'${String(s).replace(/'/g, "''")}'`;
77
+
78
+ /** The one-time SQL that lets the database start the mailer — one statement each (the CLI runs one at a time). */
79
+ export function mailerStatements(projectUrl) {
80
+ return [
81
+ 'create extension if not exists pg_net with schema extensions',
82
+ 'create extension if not exists pg_cron with schema pg_catalog',
83
+ 'grant usage on schema cron to postgres',
84
+ 'grant all privileges on all tables in schema cron to postgres',
85
+ "select cron.schedule('booking-engine-mailer', '* * * * *', 'select booking.mailer_tick()')",
86
+ `select cron.schedule('booking-engine-mailer-history', '17 3 * * *', $job$
87
+ delete from cron.job_run_details
88
+ where jobid = (select jobid from cron.job where jobname = 'booking-engine-mailer')
89
+ and end_time < now() - interval '7 days'
90
+ $job$)`,
91
+ `select * from booking.configure_mailer(${sqlText(`${projectUrl}/functions/v1/booking-mailer`)})`,
92
+ ];
93
+ }
94
+
95
+ export async function connect(cwd, args, { readLock, readEnvFile, checkBackendEnv, ensureFunctionConfig, colors }) {
96
+ const { green, yellow, red, bold } = colors;
97
+ const flag = (name) => args.includes(name);
98
+ const value = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : null);
99
+ const check = flag('--check');
100
+ const admin = value('--admin');
101
+ const siteUrl = value('--site-url');
102
+ const dashboardUrl = siteUrl ? adminUrl(siteUrl) : null;
103
+ const steps = [];
104
+ const manual = [];
105
+ // Always worth doing; not a reason to run connect again.
106
+ const advice = ['Supabase → Authentication → Sign In / Providers: turn off “Allow new users to sign up” (only you need a login).'];
107
+ const say = (state, text) => {
108
+ const mark = state === 'ok' ? green('✓') : state === 'todo' ? yellow('→') : state === 'info' ? '·' : red('✗');
109
+ console.log(`${mark} ${text}`);
110
+ steps.push({ state, text });
111
+ };
112
+ const finish = (code) => {
113
+ console.log('');
114
+ if (manual.length) {
115
+ console.log(bold('Your part (then run this again):'));
116
+ manual.forEach((m, i) => console.log(` ${i + 1}. ${m}`));
117
+ console.log('');
118
+ }
119
+ console.log(bold('Recommended:'));
120
+ advice.forEach((a) => console.log(` • ${a}`));
121
+ console.log('');
122
+ console.log(bold('Then, in your dashboard (/admin/) → Finish setting up:'));
123
+ console.log(' • Choose where new-request alerts go — without it, nobody is told about new requests');
124
+ console.log(' • Send a test email to that address, then turn on online booking');
125
+ return code;
126
+ };
127
+
128
+ // The Supabase CLI: npx supabase@2, or a stand-in for tests.
129
+ const cli = (cliArgs, { interactive = false } = {}) => {
130
+ const stub = process.env.BOOKING_ENGINE_SUPABASE_CLI;
131
+ const [cmd, base] = stub ? [process.execPath, [stub]] : [process.platform === 'win32' ? 'npx.cmd' : 'npx', ['--yes', 'supabase@2']];
132
+ const r = spawnSync(cmd, [...base, ...cliArgs], {
133
+ cwd,
134
+ encoding: 'utf8',
135
+ stdio: interactive ? 'inherit' : ['ignore', 'pipe', 'pipe'],
136
+ env: { ...process.env, SUPABASE_TELEMETRY_DISABLED: '1' },
137
+ shell: !stub && process.platform === 'win32',
138
+ maxBuffer: 32 << 20,
139
+ });
140
+ return { code: r.status ?? 1, out: `${r.stdout ?? ''}${r.stderr ?? ''}` };
141
+ };
142
+ // SQL goes through a private temporary file: nothing to quote, nothing in the process list.
143
+ const query = (sql) => {
144
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'booking-engine-'));
145
+ const file = path.join(dir, 'query.sql');
146
+ try {
147
+ fs.writeFileSync(file, `${sql};\n`, { mode: 0o600 });
148
+ const r = cli(['db', 'query', '--linked', '--file', file]);
149
+ const parsed = parseQueryOutput(r.out);
150
+ return r.code === 0 || parsed.ok ? parsed : { ok: false, error: parsed.error };
151
+ } finally {
152
+ fs.rmSync(dir, { recursive: true, force: true });
153
+ }
154
+ };
155
+ const loginHint = (out) => /access token|not logged in|supabase login|Unauthorized|401/i.test(out);
156
+
157
+ console.log(bold(`Booking Engine — connect${check ? ' (checking only, nothing is changed)' : ''}`));
158
+
159
+ // 1. The engine's files in this project.
160
+ const lock = readLock(cwd);
161
+ if (!lock) {
162
+ say('fail', 'The Booking Engine is not set up in this folder.');
163
+ manual.push('Run npx booking-engine init in the project folder.');
164
+ return finish(1);
165
+ }
166
+ say('ok', `Engine ${lock.version}: ${lock.migrations.length} migrations and the mailer in supabase/`);
167
+ if (siteUrl && !dashboardUrl) {
168
+ say('fail', `--site-url ${JSON.stringify(siteUrl)} is not an https address. Nothing was changed.`);
169
+ manual.push('Use the live website\'s address, e.g. --site-url https://yourdomain.com');
170
+ return finish(1);
171
+ }
172
+
173
+ // 2. The website's connection (.env.local): which project this is.
174
+ const env = {};
175
+ for (const f of ['.env', '.env.local']) if (fs.existsSync(path.join(cwd, f))) Object.assign(env, readEnvFile(path.join(cwd, f)));
176
+ const backend = checkBackendEnv(env);
177
+ if (backend.status === 'none') {
178
+ say('todo', 'The website does not know its Supabase project yet.');
179
+ manual.push(
180
+ 'In Supabase → Project Settings → API Keys, copy the Project URL and the publishable key into .env.local:\n' +
181
+ ' VITE_SUPABASE_URL=https://<project-ref>.supabase.co\n' +
182
+ ' VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_…\n' +
183
+ ' (Both are public and safe to paste into Claude Code. Never the secret key.)',
184
+ );
185
+ return finish(2);
186
+ }
187
+ if (backend.status === 'invalid') {
188
+ say('fail', 'The Supabase values in .env.local are not usable:');
189
+ for (const p of backend.problems) console.log(` - ${p}`);
190
+ return finish(1);
191
+ }
192
+ const url = env.VITE_SUPABASE_URL.trim().replace(/\/+$/, '');
193
+ const ref = value('--project-ref') ?? REF_RE.exec(new URL(url).hostname)?.[1] ?? null;
194
+ if (!ref) {
195
+ say('fail', `${url} is not a <ref>.supabase.co address: give the project with --project-ref <ref>.`);
196
+ return finish(1);
197
+ }
198
+ const fromUrl = REF_RE.exec(new URL(url).hostname)?.[1];
199
+ if (fromUrl && fromUrl !== ref) {
200
+ say('fail', `--project-ref ${ref} does not match VITE_SUPABASE_URL (${fromUrl}). Nothing was changed.`);
201
+ return finish(1);
202
+ }
203
+ say('ok', `Website connection: project ${ref} (Project URL and publishable key in .env.local)`);
204
+
205
+ // 3. Link this folder to that project — never to another one.
206
+ const refFile = path.join(cwd, 'supabase', '.temp', 'project-ref');
207
+ const linked = fs.existsSync(refFile) ? fs.readFileSync(refFile, 'utf8').trim() : null;
208
+ if (linked && linked !== ref) {
209
+ say('fail', `This folder is linked to Supabase project ${linked}, but .env.local points to ${ref}. Nothing was changed.`);
210
+ manual.push(`Fix .env.local, or relink on purpose: ${SUPABASE} link --project-ref ${ref}`);
211
+ return finish(1);
212
+ }
213
+ // Only now, with the project known and the link consistent, may files be created.
214
+ if (!fs.existsSync(path.join(cwd, 'supabase', 'config.toml'))) {
215
+ if (check) {
216
+ say('todo', 'supabase/config.toml is missing (connect creates it).');
217
+ } else {
218
+ const r = cli(['init'], { interactive: true });
219
+ if (r.code !== 0 || !fs.existsSync(path.join(cwd, 'supabase', 'config.toml'))) {
220
+ say('fail', `${SUPABASE} init did not create supabase/config.toml.`);
221
+ return finish(1);
222
+ }
223
+ }
224
+ }
225
+ if (!check) {
226
+ ensureFunctionConfig(cwd);
227
+ if (ignoreSupabaseTemp(cwd)) say('ok', '.gitignore: supabase/.temp/ (this computer\'s link) stays out of Git');
228
+ }
229
+ if (!linked) {
230
+ const projects = cli(['projects', 'list', '-o', 'json']);
231
+ if (projects.code !== 0) {
232
+ say('todo', 'The Supabase CLI is not signed in on this computer.');
233
+ manual.push(`Run ${SUPABASE} login (it opens your browser), then run this again.`);
234
+ return finish(2);
235
+ }
236
+ if (!projects.out.includes(ref)) {
237
+ say('fail', `Project ${ref} is not in the Supabase account this computer is signed in to.`);
238
+ manual.push(`Check VITE_SUPABASE_URL, or sign in to the right account: ${SUPABASE} login`);
239
+ return finish(1);
240
+ }
241
+ if (check) {
242
+ say('todo', `This folder is not linked to ${ref} yet (connect links it).`);
243
+ } else {
244
+ console.log(` Linking to ${ref} — if asked, type the database password you chose for the project.`);
245
+ const r = cli(['link', '--project-ref', ref], { interactive: true });
246
+ const now = fs.existsSync(refFile) ? fs.readFileSync(refFile, 'utf8').trim() : null;
247
+ if (r.code !== 0 || now !== ref) {
248
+ say('fail', `Could not link to ${ref}.`);
249
+ manual.push(`Run ${SUPABASE} link --project-ref ${ref} yourself (it asks for the database password), then run this again.`);
250
+ return finish(1);
251
+ }
252
+ say('ok', `Linked this folder to ${ref}`);
253
+ }
254
+ } else {
255
+ say('ok', `Linked to ${ref}`);
256
+ }
257
+ if (check && !linked) {
258
+ say('info', 'The remaining steps need the link: run without --check.');
259
+ return finish(2);
260
+ }
261
+
262
+ // 4. Database: the engine's migrations, after showing what will change.
263
+ const dry = cli(['db', 'push', '--dry-run']);
264
+ if (dry.code !== 0) {
265
+ say('fail', `Could not read the database's migration history: ${redact(dry.out.trim().split('\n').slice(-2).join(' '))}`);
266
+ if (loginHint(dry.out)) manual.push(`Run ${SUPABASE} login, then run this again.`);
267
+ return finish(1);
268
+ }
269
+ const pending = [...new Set(dry.out.match(/\d{14}_[a-z0-9_]+\.sql/g) ?? [])];
270
+ if (!pending.length) {
271
+ say('ok', 'Database: up to date');
272
+ } else if (check) {
273
+ say('todo', `Database: ${pending.length} migration(s) to apply: ${pending.join(', ')}`);
274
+ } else {
275
+ console.log(` ${pending.length} migration(s) will be applied to ${ref}:`);
276
+ pending.forEach((p) => console.log(` ${p}`));
277
+ let go = flag('--yes');
278
+ if (!go && process.stdin.isTTY) {
279
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
280
+ go = /^y(es)?$/i.test((await rl.question(' Apply them now? [y/N] ')).trim());
281
+ rl.close();
282
+ }
283
+ if (!go) {
284
+ say('todo', 'Database: migrations not applied yet.');
285
+ manual.push('Read the list above, then run npx booking-engine connect --yes to apply it.');
286
+ return finish(2);
287
+ }
288
+ const push = cli(['db', 'push', '--yes']);
289
+ if (push.code !== 0) {
290
+ say('fail', `Applying the migrations failed: ${redact(push.out.trim().split('\n').slice(-3).join(' '))}`);
291
+ return finish(1);
292
+ }
293
+ say('ok', `Database: applied ${pending.length} migration(s)`);
294
+ }
295
+ if (check && pending.length) {
296
+ say('info', 'The remaining steps need the migrations: run without --check.');
297
+ return finish(2);
298
+ }
299
+
300
+ // 5. The owner's account (Supabase Auth user + the engine's admin list).
301
+ if (admin) {
302
+ if (!EMAIL_RE.test(admin)) {
303
+ say('fail', `--admin ${JSON.stringify(admin)} is not an email address.`);
304
+ return finish(1);
305
+ }
306
+ if (check) {
307
+ say('info', `Would make ${admin} the dashboard owner (run without --check).`);
308
+ } else {
309
+ const r = query(`select booking.add_admin(${sqlText(admin)}) as result`);
310
+ if (!r.ok) {
311
+ if (/No Supabase Auth user/i.test(r.error)) {
312
+ say('todo', `There is no Supabase login for ${admin} yet.`);
313
+ manual.push(`Supabase → Authentication → Users → Add user: ${admin}, a strong password, “Auto Confirm User” on.`);
314
+ // Not a reason to stop: the email setup below does not need the owner yet.
315
+ } else {
316
+ say('fail', `Could not make ${admin} the owner: ${r.error}`);
317
+ return finish(1);
318
+ }
319
+ } else {
320
+ say('ok', `Dashboard owner: ${admin}`);
321
+ }
322
+ }
323
+ } else {
324
+ const r = query('select count(*)::int as admins from booking.admins');
325
+ if (r.ok && r.rows[0]?.admins > 0) {
326
+ say('ok', `Dashboard owner: ${r.rows[0].admins} account(s)`);
327
+ } else {
328
+ say('todo', 'Nobody can sign in to the dashboard yet.');
329
+ manual.push(
330
+ 'Supabase → Authentication → Users → Add user (your email, a strong password, “Auto Confirm User” on),\n' +
331
+ ' then run npx booking-engine connect --admin you@example.com',
332
+ );
333
+ }
334
+ }
335
+
336
+ // 6. Email secrets — the Resend key is the owner's to enter, never ours to see.
337
+ const secrets = cli(['secrets', 'list']);
338
+ const has = (name) => new RegExp(`\\b${name}\\b`).test(secrets.out);
339
+ const missingEmail = secrets.code === 0 ? EMAIL_SECRETS.filter((s) => !has(s)) : EMAIL_SECRETS;
340
+ if (secrets.code !== 0) {
341
+ say('fail', `Could not list the Edge Function secrets: ${redact(secrets.out.trim().split('\n').slice(-1)[0] ?? '')}`);
342
+ } else if (missingEmail.length) {
343
+ say('todo', `Email: ${missingEmail.join(' and ')} not set yet.`);
344
+ manual.push(
345
+ `Supabase → Edge Functions → Secrets → add ${missingEmail.join(' and ')}:\n` +
346
+ ' RESEND_API_KEY your Resend API key (Sending access, your verified domain) — paste it only there\n' +
347
+ ' BOOKING_EMAIL_FROM e.g. Your Business <bookings@mail.yourdomain.com> (an address on that domain)',
348
+ );
349
+ } else {
350
+ say('ok', 'Email: RESEND_API_KEY and BOOKING_EMAIL_FROM are set');
351
+ }
352
+ if (secrets.code === 0 && !dashboardUrl && !has('BOOKING_ADMIN_URL')) {
353
+ advice.push('Once the website is live: npx booking-engine connect --site-url https://yourdomain.com — owner alerts then get an “Open your dashboard” button.');
354
+ }
355
+
356
+ // 7. The mailer function (bundled by Supabase: no Docker on this computer).
357
+ if (check) {
358
+ const fns = cli(['functions', 'list']);
359
+ say(/booking-mailer/.test(fns.out) ? 'ok' : 'todo', /booking-mailer/.test(fns.out) ? 'Mailer: booking-mailer is deployed' : 'Mailer: not deployed yet (connect deploys it).');
360
+ } else {
361
+ const deploy = cli(['functions', 'deploy', 'booking-mailer', '--no-verify-jwt', '--use-api']);
362
+ if (deploy.code !== 0) {
363
+ say('fail', `Deploying booking-mailer failed: ${redact(deploy.out.trim().split('\n').slice(-3).join(' '))}`);
364
+ return finish(1);
365
+ }
366
+ say('ok', 'Mailer: booking-mailer deployed');
367
+ }
368
+
369
+ // 8. Wire the database to the mailer; the token goes straight into a secret.
370
+ if (!check) {
371
+ let token = null;
372
+ for (const sql of mailerStatements(url)) {
373
+ const r = query(sql);
374
+ if (!r.ok) {
375
+ say('fail', `Setting up automatic sending failed: ${r.error}`);
376
+ return finish(1);
377
+ }
378
+ if (r.rows[0]?.booking_mailer_token) token = r.rows[0].booking_mailer_token;
379
+ }
380
+ if (!/^[0-9a-f]{64}$/.test(token ?? '')) {
381
+ say('fail', 'The database did not return a mailer token.');
382
+ return finish(1);
383
+ }
384
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'booking-engine-'));
385
+ const file = path.join(dir, `secrets-${crypto.randomUUID()}.env`);
386
+ try {
387
+ fs.writeFileSync(file, `BOOKING_MAILER_TOKEN=${token}\n${dashboardUrl ? `BOOKING_ADMIN_URL=${dashboardUrl}\n` : ''}`, { mode: 0o600 });
388
+ const set = cli(['secrets', 'set', '--env-file', file]);
389
+ if (set.code !== 0) {
390
+ say('fail', `Storing the mailer token as a secret failed: ${redact(set.out.trim().split('\n').slice(-2).join(' '))}`);
391
+ return finish(1);
392
+ }
393
+ } finally {
394
+ fs.rmSync(dir, { recursive: true, force: true });
395
+ token = null;
396
+ }
397
+ say('ok', 'Automatic sending: the database starts the mailer (token stored as BOOKING_MAILER_TOKEN, never shown)');
398
+ if (dashboardUrl) say('ok', `Owner alerts link to ${dashboardUrl} (BOOKING_ADMIN_URL)`);
399
+ }
400
+ const wiring = query('select booking.mailer_wiring() as wiring');
401
+ const w = wiring.ok ? wiring.rows[0]?.wiring ?? {} : {};
402
+ const wired = w.configured && w.pgNet && w.schedule;
403
+ say(wired ? 'ok' : 'todo', wired ? 'Mailer wiring: address, pg_net and the every-minute job in place' : `Mailer wiring incomplete (${['configured', 'pgNet', 'schedule'].filter((k) => !w[k]).join(', ') || 'unknown'})${check ? ' — connect sets it up' : ''}`);
404
+
405
+ const waiting = steps.some((s) => s.state === 'todo') || steps.some((s) => s.state === 'fail');
406
+ if (!waiting) console.log(green('\nConnected.'));
407
+ return finish(steps.some((s) => s.state === 'fail') ? 1 : waiting ? 2 : 0);
408
+ }
package/bin/photos.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // booking-engine photos [manifest] — the website's own photos, prepared once:
2
+ // cropped to each frame's aspect ratio, camera data removed, written as AVIF and
3
+ // WebP at the widths the design asks for. Uses the project's own `sharp`
4
+ // (npm install --save-dev sharp); the engine does not ship an image library.
5
+ //
6
+ // photos/photos.json:
7
+ // { "out": "public/photos",
8
+ // "photos": [{ "src": "photos/source/hero.jpg", "name": "hero", "aspect": "4:5",
9
+ // "widths": [640, 1024, 1440], "position": "attention" }] }
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { createRequire } from 'node:module';
13
+
14
+ const POSITIONS = ['center', 'top', 'bottom', 'left', 'right', 'attention', 'entropy'];
15
+ const NAME_RE = /^[a-z0-9][a-z0-9-]{0,60}$/;
16
+
17
+ function problem(message) {
18
+ const error = new Error(message);
19
+ error.userFacing = true;
20
+ return error;
21
+ }
22
+
23
+ function readManifest(cwd, file) {
24
+ const full = path.resolve(cwd, file);
25
+ if (!fs.existsSync(full)) {
26
+ throw problem(`No ${path.relative(cwd, full)}. Describe each photo there (see docs/BUILD-A-SITE.md §5), then run this again.`);
27
+ }
28
+ let manifest;
29
+ try {
30
+ manifest = JSON.parse(fs.readFileSync(full, 'utf8'));
31
+ } catch (error) {
32
+ throw problem(`${path.relative(cwd, full)} is not valid JSON: ${error.message}`);
33
+ }
34
+ const photos = Array.isArray(manifest.photos) ? manifest.photos : [];
35
+ if (!photos.length) throw problem(`${path.relative(cwd, full)} lists no photos ("photos": [ … ]).`);
36
+ const names = new Set();
37
+ for (const [i, p] of photos.entries()) {
38
+ const where = `photos[${i}]`;
39
+ if (typeof p.src !== 'string' || !fs.existsSync(path.resolve(cwd, p.src))) throw problem(`${where}.src: file not found (${p.src}).`);
40
+ if (typeof p.name !== 'string' || !NAME_RE.test(p.name)) throw problem(`${where}.name: lowercase letters, digits and dashes only (got ${JSON.stringify(p.name)}).`);
41
+ if (names.has(p.name)) throw problem(`${where}.name: "${p.name}" is used twice.`);
42
+ names.add(p.name);
43
+ if (p.aspect !== undefined && !/^\d+(\.\d+)?:\d+(\.\d+)?$/.test(String(p.aspect))) throw problem(`${where}.aspect: like "4:5" or "3:2".`);
44
+ if (!Array.isArray(p.widths) || !p.widths.length || !p.widths.every((w) => Number.isInteger(w) && w >= 160 && w <= 4000)) {
45
+ throw problem(`${where}.widths: whole pixel widths between 160 and 4000, e.g. [640, 1024, 1440].`);
46
+ }
47
+ if (p.position !== undefined && !POSITIONS.includes(p.position)) throw problem(`${where}.position: one of ${POSITIONS.join(', ')}.`);
48
+ }
49
+ return { out: manifest.out ?? 'public/photos', photos };
50
+ }
51
+
52
+ /** Runs the command; returns the lines to print. Throws errors with `userFacing` for plain messages. */
53
+ export async function preparePhotos(cwd, args) {
54
+ const manifestFile = args.find((a) => !a.startsWith('--')) ?? path.join('photos', 'photos.json');
55
+ const { out, photos } = readManifest(cwd, manifestFile);
56
+ let sharp;
57
+ try {
58
+ sharp = createRequire(path.join(cwd, 'package.json'))('sharp');
59
+ } catch {
60
+ throw problem('The photos command uses the project\'s own image library: run npm install --save-dev sharp and try again.');
61
+ }
62
+ const outDir = path.resolve(cwd, out);
63
+ fs.mkdirSync(outDir, { recursive: true });
64
+ const lines = [];
65
+ for (const p of photos) {
66
+ const source = sharp(path.resolve(cwd, p.src)).rotate(); // honour the camera's orientation, then drop all metadata
67
+ const meta = await source.metadata();
68
+ const [aw, ah] = p.aspect ? String(p.aspect).split(':').map(Number) : [meta.width, meta.height];
69
+ const sizes = [];
70
+ for (const width of [...p.widths].sort((a, b) => a - b)) {
71
+ const height = Math.round((width * ah) / aw);
72
+ const base = source.clone().resize(width, height, { fit: 'cover', position: p.position ?? 'centre', withoutEnlargement: false });
73
+ await base.clone().avif({ quality: 50 }).toFile(path.join(outDir, `${p.name}-${width}.avif`));
74
+ await base.clone().webp({ quality: 74 }).toFile(path.join(outDir, `${p.name}-${width}.webp`));
75
+ sizes.push(`${width}×${height}`);
76
+ }
77
+ const upscaled = Math.max(...p.widths) > (meta.width ?? Infinity);
78
+ lines.push(`${p.name}: ${sizes.join(', ')} (avif, webp)${upscaled ? ` ! the source is only ${meta.width} px wide: the largest sizes are upscaled` : ''}`);
79
+ }
80
+ lines.push(`Written to ${path.relative(cwd, outDir) || '.'}/ — use <name>-<width>.avif|webp with width/height from the sizes above.`);
81
+ return lines;
82
+ }
@@ -0,0 +1,29 @@
1
+ import type { BookingEngine } from '../client.js';
2
+ import type { SiteContentSchema } from '../content/schema.js';
3
+ import type { Preset } from '../types.js';
4
+ import { type EmailDelivery } from './context.js';
5
+ export interface BookingAdminProps {
6
+ /** The same engine instance the website uses. */
7
+ engine: BookingEngine;
8
+ /** Starter sets offered when there are no services. Defaults to the presets in this engine version. */
9
+ presets?: Preset[];
10
+ /** Link back to the public website (also where previews open). */
11
+ siteUrl?: string;
12
+ /**
13
+ * The content this website lets its owner edit (defineSiteContent). Without
14
+ * it the Website section explains how to add some.
15
+ */
16
+ content?: SiteContentSchema;
17
+ /**
18
+ * How booking emails reach customers. 'live' (the default): the engine's mailer
19
+ * sends them. 'none': an installation that never emails anyone — a public demo
20
+ * or a showcase. The dashboard then never says that a customer gets an email.
21
+ */
22
+ emailDelivery?: EmailDelivery;
23
+ }
24
+ export type Appearance = 'system' | 'light' | 'dark';
25
+ /**
26
+ * The packaged admin dashboard. Mount it on its own page (e.g. /admin/).
27
+ * It handles sign-in, admin checks and every management screen.
28
+ */
29
+ export declare function BookingAdmin({ engine, presets, siteUrl, content, emailDelivery }: BookingAdminProps): import("react").JSX.Element;