@semics-tech/emdash-events 0.0.0-bootstrap.0 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -2
  3. package/dist/index.d.mts +5 -0
  4. package/dist/index.mjs +392 -0
  5. package/dist/manifest.json +401 -0
  6. package/dist/plugin.d.mts +11 -0
  7. package/dist/plugin.mjs +7 -0
  8. package/dist/ts/astro/lib/call.d.ts +54 -0
  9. package/dist/ts/astro/lib/call.js +121 -0
  10. package/dist/ts/integration/index.d.ts +48 -0
  11. package/dist/ts/integration/index.js +76 -0
  12. package/dist/ts/ui/index.d.ts +6 -0
  13. package/dist/ts/ui/index.js +46 -0
  14. package/emdash-plugin.jsonc +206 -0
  15. package/package.json +79 -10
  16. package/src/astro/AddToCalendar.astro +47 -0
  17. package/src/astro/BookingBlock.astro +30 -0
  18. package/src/astro/BookingPage.astro +193 -0
  19. package/src/astro/BookingStatus.astro +106 -0
  20. package/src/astro/BookingWidget.astro +581 -0
  21. package/src/astro/CheckIn.astro +186 -0
  22. package/src/astro/DoorSignPage.astro +62 -0
  23. package/src/astro/EventCard.astro +81 -0
  24. package/src/astro/EventList.astro +83 -0
  25. package/src/astro/OptOutPage.astro +58 -0
  26. package/src/astro/PaymentReturn.astro +96 -0
  27. package/src/astro/TicketPass.astro +95 -0
  28. package/src/astro/checkout-endpoint.ts +11 -0
  29. package/src/astro/index.js +18 -0
  30. package/src/astro/lib/call.ts +185 -0
  31. package/src/astro/lib/checkout-form.ts +271 -0
  32. package/src/astro/lib/list.ts +99 -0
  33. package/src/astro/lib/opt-out.ts +49 -0
  34. package/src/astro/lib/pass.ts +35 -0
  35. package/src/astro/lib/payment.ts +73 -0
  36. package/src/astro/lib/promo.ts +162 -0
  37. package/src/astro/lib/questions.ts +107 -0
  38. package/src/astro/lib/receipt.ts +132 -0
  39. package/src/astro/lib/waitlist.ts +72 -0
  40. package/src/astro/lib/widget.ts +278 -0
  41. package/src/astro/promo-endpoint.ts +11 -0
  42. package/src/astro/virtual.d.ts +16 -0
  43. package/src/astro/waitlist-endpoint.ts +12 -0
  44. package/src/client/booking.ts +188 -0
  45. package/src/client/checkin.ts +260 -0
  46. package/src/client/payment.ts +76 -0
  47. package/src/client/receipt.ts +75 -0
  48. package/src/i18n/ar.ts +213 -0
  49. package/src/i18n/en.ts +219 -0
  50. package/src/i18n/index.ts +121 -0
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Server-side helpers for the booking widget, status page, pass and calendar link (T055). Pure, so
3
+ * the components stay thin. `src/client/booking.ts` mirrors `validateCheckoutFields` (a test keeps
4
+ * them in step) because the client script ships without imports.
5
+ */
6
+ import { type MessageKey, t } from "../../i18n/index";
7
+
8
+ /** What `GET public/event` answers for one event (T046 implements the route to this shape). */
9
+ export interface PublicEvent {
10
+ eventId: string;
11
+ title?: string;
12
+ status: "draft" | "on_sale" | "paused" | "closed" | "cancelled";
13
+ currency: string;
14
+ /** IANA zone the event's dates are shown in (the entry's `timezone` field). */
15
+ timezone?: string;
16
+ /** The event's own start, end and venue (the mapped entry fields), when the core has them. */
17
+ startsAt?: string;
18
+ endsAt?: string | null;
19
+ venue?: string | null;
20
+ ticketTypes: Array<{
21
+ id: string;
22
+ name: string;
23
+ priceMinor: number;
24
+ /** Seats left; `null` when not shown. */
25
+ available?: number | null;
26
+ minPerOrder?: number | null;
27
+ maxPerOrder?: number | null;
28
+ }>;
29
+ occurrences?: Array<{ id: string; startsAt: string; endsAt?: string | null; available?: number | null }>;
30
+ /** Public Turnstile site key, when the site owner configured one. */
31
+ turnstileSiteKey?: string;
32
+ /** True when the event requires a signed waiver (T066): the booking form then asks for attendees. */
33
+ waiver?: boolean;
34
+ /** True when the core takes promo codes (Events Pro, T078): the widget then shows a code field. */
35
+ promoCodes?: boolean;
36
+ /** True when a sold-out event takes a waitlist (T081): the widget then shows a "Join the waitlist" form. */
37
+ waitlist?: boolean;
38
+ /** Custom attendee questions (Events Pro, T080): the buyer answers them once per booking. */
39
+ questions?: PublicQuestion[];
40
+ }
41
+
42
+ /** One custom question as `public/event` lists it (EV-FR-15). */
43
+ export interface PublicQuestion {
44
+ id: string;
45
+ label: string;
46
+ type: "text" | "select" | "checkbox";
47
+ required: boolean;
48
+ /** The choices of a `select` question. */
49
+ options?: string[];
50
+ }
51
+
52
+ /** What `POST public/booking` answers (T049), plus the optional fields later tasks add. */
53
+ export interface BookingView {
54
+ bookingRef: string;
55
+ status: string;
56
+ eventId?: string;
57
+ lines: Array<{ ticketTypeId: string; qty: number }>;
58
+ totals: { totalMinor: number; currency: string };
59
+ holdExpiresAt?: string;
60
+ /** `qr`: Events Pro's QR matrix of `code` (T082), drawn by `<TicketPass>`; Free sends none. */
61
+ attendees: Array<{ name: string; ticketTypeId?: string; status: string; code?: string; qr?: unknown }>;
62
+ canCancel: boolean;
63
+ cancelBy?: string;
64
+ /** A short-lived signed query for `public/booking/ics`, issued by the core (T050). */
65
+ calendar?: { query?: string };
66
+ /**
67
+ * While a waiver booking waits for signatures (T066): the refs still unsigned, and with Pro a signed
68
+ * receipt-lookup request for each, which the suite's reconciliation sends to e-sign.
69
+ */
70
+ waiver?: { refs: string[]; lookups?: Record<string, string> };
71
+ }
72
+
73
+ /** A custom question's field is `q:<question id>` (T080). */
74
+ export type QuestionField = `q:${string}`;
75
+ export type WidgetField = "occurrence" | "promo" | "tickets" | "name" | "email" | QuestionField;
76
+
77
+ /** Question ids safe in HTML ids, field names and the widget's error URL. */
78
+ export const QUESTION_ID = /^[A-Za-z0-9_-]{1,64}$/;
79
+
80
+ /** In form order: the first one is where focus goes. */
81
+ export const WIDGET_FIELDS = ["occurrence", "promo", "tickets", "name", "email"] as const;
82
+
83
+ export const WIDGET_PARAMS = { error: "booking_error", fields: "booking_fields", event: "booking_event" } as const;
84
+
85
+ /** The key reserve accepts (`src/domain/checkout.ts`). */
86
+ export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9_-]{32,128}$/;
87
+
88
+ const ERROR_CODES = [
89
+ "BAD_REQUEST",
90
+ "SOLD_OUT",
91
+ "SALES_CLOSED",
92
+ "RATE_LIMITED",
93
+ "TURNSTILE_FAILED",
94
+ "HOLD_EXPIRED",
95
+ "NOT_FOUND",
96
+ "PROMO_INVALID",
97
+ "PROMO_EXHAUSTED",
98
+ "PROMO_ORDER_TOO_LARGE",
99
+ "PROMO_UNAVAILABLE",
100
+ "INTERNAL",
101
+ ] as const;
102
+
103
+ /** A field's message in the locale's language (T102). */
104
+ export const fieldMessage = (field: (typeof WIDGET_FIELDS)[number], locale?: string) =>
105
+ t(locale, `widget.field.${field}`);
106
+
107
+ /** English field messages, by field (the 1.0 API; components use `fieldMessage`). */
108
+ export const FIELD_MESSAGES = Object.fromEntries(WIDGET_FIELDS.map((f) => [f, fieldMessage(f, "en")])) as Record<
109
+ (typeof WIDGET_FIELDS)[number],
110
+ string
111
+ >;
112
+
113
+ /** English refusal messages by code: the codes the widget knows (anything else reads as `INTERNAL`). */
114
+ export const ERROR_MESSAGES: Record<string, string> = Object.fromEntries(
115
+ ERROR_CODES.map((code) => [code, t("en", `widget.error.${code}`)]),
116
+ );
117
+
118
+ /** A refusal's message in the locale's language; an unknown code gets `INTERNAL`'s. */
119
+ export const errorMessage = (code: string, locale?: string) =>
120
+ t(locale, `widget.error.${(ERROR_CODES as readonly string[]).includes(code) ? code : "INTERNAL"}` as MessageKey);
121
+
122
+ /** A refusal of an order or check with a code: Pro's licence codes (it lapsed) mean the code can't be used (T120). */
123
+ export const promoRefusal = (code: string) => (code.startsWith("LICENCE_") ? "PROMO_UNAVAILABLE" : code);
124
+
125
+ /** 32 random bytes as 43 unpadded base64url characters: a fresh key for each checkout attempt. */
126
+ export function newIdempotencyKey(): string {
127
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
128
+ return btoa(String.fromCharCode(...bytes))
129
+ .replaceAll("+", "-")
130
+ .replaceAll("/", "_")
131
+ .replaceAll("=", "");
132
+ }
133
+
134
+ /** The widget's element id, safe in HTML ids, CSS selectors and URL fragments. */
135
+ export function anchorId(eventId: string): string {
136
+ return `semics-booking-${eventId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
137
+ }
138
+
139
+ /**
140
+ * A same-site path to send the buyer back to, or `undefined`. Refuses absolute and
141
+ * protocol-relative URLs (no open redirect) and the checkout endpoint itself, and drops earlier
142
+ * widget error parameters and the fragment.
143
+ */
144
+ export function safeReturnTo(raw: string, origin: string): string | undefined {
145
+ if (!raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return undefined;
146
+ let url: URL;
147
+ try {
148
+ url = new URL(raw, origin);
149
+ } catch {
150
+ return undefined;
151
+ }
152
+ // `/.//x` and `/%2e//x` resolve to `//x`: as a Location that is another host (T119 F11).
153
+ if (url.origin !== origin || url.pathname.startsWith("//") || url.pathname.startsWith("/_events/")) return undefined;
154
+ for (const name of Object.values(WIDGET_PARAMS)) url.searchParams.delete(name);
155
+ return `${url.pathname}${url.search}`;
156
+ }
157
+
158
+ /** Where a refused checkout goes: back to the widget with a code and the fields to fix. No values. */
159
+ export function widgetErrorLocation(
160
+ returnTo: string,
161
+ eventId: string,
162
+ code: string,
163
+ fields: readonly WidgetField[],
164
+ ): string {
165
+ const url = new URL(returnTo, "http://x");
166
+ url.searchParams.set(WIDGET_PARAMS.error, code);
167
+ if (fields.length > 0) url.searchParams.set(WIDGET_PARAMS.fields, fields.join(","));
168
+ url.searchParams.set(WIDGET_PARAMS.event, eventId);
169
+ return `${url.pathname}${url.search}#${anchorId(eventId)}`;
170
+ }
171
+
172
+ /** The error a widget shows after a no-JS round trip; only for the widget of `eventId`. */
173
+ export function readWidgetState(url: URL, eventId: string): { code?: string; fields: WidgetField[] } {
174
+ const raw = url.searchParams.get(WIDGET_PARAMS.error);
175
+ if (!raw || url.searchParams.get(WIDGET_PARAMS.event) !== eventId) return { fields: [] };
176
+ const code = Object.hasOwn(ERROR_MESSAGES, raw) ? raw : "INTERNAL";
177
+ const asked = new Set((url.searchParams.get(WIDGET_PARAMS.fields) ?? "").split(","));
178
+ const questions = [...asked].filter((f): f is QuestionField => f.startsWith("q:") && QUESTION_ID.test(f.slice(2)));
179
+ return { code, fields: [...WIDGET_FIELDS.filter((f) => asked.has(f)), ...questions] };
180
+ }
181
+
182
+ export interface CheckoutFieldValues {
183
+ name: string;
184
+ email: string;
185
+ /** Ticket lines with a quantity above zero. */
186
+ lines: number;
187
+ needsOccurrence: boolean;
188
+ occurrenceId: string;
189
+ }
190
+
191
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
192
+
193
+ /** The fields to fix before checkout is worth a call; reserve's own validation is the authority. */
194
+ export function validateCheckoutFields(v: CheckoutFieldValues): WidgetField[] {
195
+ const name = v.name.trim();
196
+ const email = v.email.trim();
197
+ const bad: WidgetField[] = [];
198
+ if (v.needsOccurrence && !v.occurrenceId) bad.push("occurrence");
199
+ if (v.lines < 1) bad.push("tickets");
200
+ if (name.length < 1 || name.length > 200) bad.push("name");
201
+ if (email.length > 254 || !EMAIL.test(email)) bad.push("email");
202
+ return bad;
203
+ }
204
+
205
+ const ISSUE_FIELDS: Array<[RegExp, WidgetField]> = [
206
+ [/^occurrenceId/, "occurrence"],
207
+ [/^lines/, "tickets"],
208
+ [/^buyer\.name/, "name"],
209
+ [/^buyer\.email/, "email"],
210
+ ];
211
+
212
+ /** Reserve's validation issues (`{ path, code }`) as widget fields, each once. */
213
+ export function fieldsFromIssues(issues: ReadonlyArray<{ path?: unknown; code?: unknown }> | undefined): WidgetField[] {
214
+ const found = new Set<WidgetField>();
215
+ for (const issue of issues ?? []) {
216
+ const path = typeof issue.path === "string" ? issue.path : "";
217
+ const hit = ISSUE_FIELDS.find(([pattern]) => pattern.test(path));
218
+ const question = /^answers\.([^.]+)/.exec(path)?.[1];
219
+ if (hit) found.add(hit[1]);
220
+ else if (question && QUESTION_ID.test(question)) found.add(`q:${question}`);
221
+ }
222
+ return [...found];
223
+ }
224
+
225
+ const TOKEN_LIKE = /^(t|.*token.*|.*receipt.*|.*secret.*|.*otp.*)$/i;
226
+
227
+ const routeBase = (pluginId: string) => `/_emdash/api/plugins/${encodeURIComponent(pluginId)}`;
228
+
229
+ /**
230
+ * The booking's calendar file link, from the signed query the core issued (`signLink`). The UI
231
+ * holds no secret and never signs: it only refuses a query that is unsigned, expired or carries a
232
+ * token, so an access token can never end up in a calendar URL.
233
+ */
234
+ export function bookingCalendarHref(input: {
235
+ pluginId: string;
236
+ query: string | undefined;
237
+ now: number;
238
+ }): string | undefined {
239
+ if (!input.query) return undefined;
240
+ const query = new URLSearchParams(input.query);
241
+ const exp = query.get("exp") ?? "";
242
+ if (!query.get("sig") || !/^\d{1,15}$/.test(exp) || Number(exp) * 1000 <= input.now) return undefined;
243
+ for (const name of query.keys()) if (TOKEN_LIKE.test(name)) return undefined;
244
+ return `${routeBase(input.pluginId)}/public/booking/ics?${query}`;
245
+ }
246
+
247
+ /** The public event calendar file (no booking data, so no signature). */
248
+ export function eventCalendarHref(pluginId: string, eventId: string): string {
249
+ return `${routeBase(pluginId)}/public/event/ics?${new URLSearchParams({ eventId })}`;
250
+ }
251
+
252
+ export function formatMoney(minor: number, currency: string, locale = "en-GB"): string {
253
+ if (minor === 0) return t(locale, "money.free");
254
+ try {
255
+ return new Intl.NumberFormat(locale, { style: "currency", currency }).format(minor / 100);
256
+ } catch {
257
+ return `${(minor / 100).toFixed(2)} ${currency}`;
258
+ }
259
+ }
260
+
261
+ const STATUSES = [
262
+ "draft",
263
+ "held",
264
+ "awaiting_signature",
265
+ "awaiting_payment",
266
+ "confirmed",
267
+ "expired",
268
+ "cancelled",
269
+ "refunded",
270
+ "refunded_unavailable",
271
+ ] as const;
272
+
273
+ /** A booking status for people, in the locale's language; an unknown status is shown as it is. */
274
+ export const statusLabel = (status: string, locale?: string) =>
275
+ (STATUSES as readonly string[]).includes(status) ? t(locale, `status.${status}` as MessageKey) : status;
276
+
277
+ /** English status labels (the 1.0 API; components use `statusLabel`). */
278
+ export const STATUS_LABELS: Record<string, string> = Object.fromEntries(STATUSES.map((s) => [s, statusLabel(s, "en")]));
@@ -0,0 +1,11 @@
1
+ // Injected at `/_events/promo` by the integration: the booking widget's "Apply" button (a plain form
2
+ // post, no JavaScript needed). Cross-site posts get a 403 before anything runs (`isCrossSiteRequest`).
3
+ import { pluginId } from "virtual:semics-events/config";
4
+
5
+ import { handlePromoRequest, type PromoEndpointContext } from "./lib/promo";
6
+
7
+ export const prerender = false;
8
+
9
+ export function POST(ctx: PromoEndpointContext): Promise<Response> {
10
+ return handlePromoRequest(ctx, { pluginId });
11
+ }
@@ -0,0 +1,16 @@
1
+ // Provided by the integration's Vite plugin (`eventsIntegration({ pluginId })`).
2
+ declare module "virtual:semics-events/config" {
3
+ export const pluginId: string;
4
+ /** The e-sign core's plugin id, or `null` when e-sign is not configured (`eventsIntegration({ esignPluginId })`). */
5
+ export const esignPluginId: string | null;
6
+ /**
7
+ * The suite's reconciliation of a booking that waits for signatures (T066), or `null` without the suite
8
+ * (`eventsIntegration({ reconcile })`). Forwards the receipts e-sign already has; resolves with how many.
9
+ */
10
+ export const reconcile:
11
+ | ((
12
+ ctx: import("./lib/call").PublicRouteContext,
13
+ input: { booking: import("./lib/widget").BookingView; pluginId: string; esignPluginId: string },
14
+ ) => Promise<{ forwarded: number }>)
15
+ | null;
16
+ }
@@ -0,0 +1,12 @@
1
+ // Injected at `/_events/waitlist` by the integration: the booking widget's "Join the waitlist" form (a
2
+ // plain form post, no JavaScript needed). Cross-site posts get a 403 before anything runs.
3
+ import { pluginId } from "virtual:semics-events/config";
4
+
5
+ import type { CheckoutEndpointContext } from "./lib/checkout-form";
6
+ import { handleWaitlistRequest } from "./lib/waitlist";
7
+
8
+ export const prerender = false;
9
+
10
+ export function POST(ctx: CheckoutEndpointContext): Promise<Response> {
11
+ return handleWaitlistRequest(ctx, { pluginId });
12
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Progressive enhancement for `<BookingWidget>` (EU-FR-04, EU-NFR-01..03). The form works without
3
+ * this script (a plain POST to `/_events/checkout`); with it the buyer gets:
4
+ *
5
+ * - a fresh idempotency key when the page loads (so a cached page never shares one), kept for every
6
+ * resubmit from that page so a retry finds the same booking;
7
+ * - errors next to their fields before anything is sent, with focus on the first one;
8
+ * - a live order total;
9
+ * - a guard against double submits, and the submit button enabled when Turnstile needs scripts.
10
+ *
11
+ * Self-contained (no imports) and budgeted at 15 KB gzipped (`tests/ui/client-bundle.build.test.ts`).
12
+ * Text only ever goes in through `textContent`. `validateBooking` mirrors the server's
13
+ * `validateCheckoutFields` (`src/astro/lib/widget.ts`); a test keeps them identical.
14
+ */
15
+
16
+ export type BookingField = "occurrence" | "promo" | "tickets" | "name" | "email" | `q:${string}`;
17
+
18
+ export interface BookingValues {
19
+ name: string;
20
+ email: string;
21
+ lines: number;
22
+ needsOccurrence: boolean;
23
+ occurrenceId: string;
24
+ }
25
+
26
+ // `promo` is only ever set by the server (a refused code); listing it clears that error on a resubmit.
27
+ const FIELDS: readonly BookingField[] = ["occurrence", "promo", "tickets", "name", "email"];
28
+
29
+ /** A custom question's control (Events Pro, T080): its field and whether it has an answer. */
30
+ export interface QuestionState {
31
+ field: BookingField;
32
+ required: boolean;
33
+ filled: boolean;
34
+ }
35
+
36
+ /** The required questions without an answer, in form order. Pro's reserve checks them again. */
37
+ export function missingAnswers(questions: readonly QuestionState[]): BookingField[] {
38
+ return questions.filter((q) => q.required && !q.filled).map((q) => q.field);
39
+ }
40
+
41
+ function questionStates(form: HTMLFormElement): QuestionState[] {
42
+ return Array.from(form.querySelectorAll<HTMLInputElement | HTMLSelectElement>("[data-question]"), (el) => ({
43
+ field: (el.dataset.field ?? "") as BookingField,
44
+ required: el.required,
45
+ filled: el instanceof HTMLInputElement && el.type === "checkbox" ? el.checked : el.value.trim() !== "",
46
+ }));
47
+ }
48
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
49
+
50
+ /** 32 random bytes as 43 unpadded base64url characters. */
51
+ export function freshKey(): string {
52
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
53
+ let binary = "";
54
+ for (const byte of bytes) binary += String.fromCharCode(byte);
55
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
56
+ }
57
+
58
+ export function validateBooking(v: BookingValues): BookingField[] {
59
+ const name = v.name.trim();
60
+ const email = v.email.trim();
61
+ const bad: BookingField[] = [];
62
+ if (v.needsOccurrence && !v.occurrenceId) bad.push("occurrence");
63
+ if (v.lines < 1) bad.push("tickets");
64
+ if (name.length < 1 || name.length > 200) bad.push("name");
65
+ if (email.length > 254 || !EMAIL.test(email)) bad.push("email");
66
+ return bad;
67
+ }
68
+
69
+ export function orderTotalMinor(lines: ReadonlyArray<{ qty: number; priceMinor: number }>): number {
70
+ let total = 0;
71
+ for (const line of lines) if (line.qty > 0) total += line.qty * line.priceMinor;
72
+ return total;
73
+ }
74
+
75
+ /** `free` is the page's word for a zero total (the widget renders it as `data-free`, T102). */
76
+ export function formatMinor(minor: number, currency: string, locale: string, free: string): string {
77
+ if (minor === 0) return free;
78
+ try {
79
+ return new Intl.NumberFormat(locale, { style: "currency", currency }).format(minor / 100);
80
+ } catch {
81
+ return `${(minor / 100).toFixed(2)} ${currency}`;
82
+ }
83
+ }
84
+
85
+ const qtyOf = (input: HTMLInputElement) => {
86
+ const n = Number.parseInt(input.value, 10);
87
+ return Number.isFinite(n) ? n : 0;
88
+ };
89
+
90
+ function fieldValue(form: HTMLFormElement, name: string): string {
91
+ const el = form.elements.namedItem(name);
92
+ return el instanceof HTMLInputElement || el instanceof HTMLSelectElement ? el.value : "";
93
+ }
94
+
95
+ function showErrors(form: HTMLFormElement, bad: readonly BookingField[]): void {
96
+ for (const field of [...FIELDS, ...questionStates(form).map((q) => q.field)]) {
97
+ const control = form.querySelector<HTMLElement>(`[data-field="${field}"]`);
98
+ const message = form.querySelector<HTMLElement>(`[data-error-for="${field}"]`);
99
+ if (!control || !message) continue;
100
+ const invalid = bad.includes(field);
101
+ message.textContent = invalid ? (message.dataset.message ?? "") : "";
102
+ if (invalid) control.setAttribute("aria-invalid", "true");
103
+ else control.removeAttribute("aria-invalid");
104
+ }
105
+ const first = bad[0] && form.querySelector<HTMLElement>(`[data-field="${bad[0]}"]`);
106
+ if (!first) return;
107
+ const target = first.matches("fieldset") ? first.querySelector<HTMLElement>("input:not([disabled])") : first;
108
+ target?.focus();
109
+ }
110
+
111
+ function formAlert(form: HTMLFormElement, text: string): void {
112
+ const alert = form.querySelector<HTMLElement>("[data-form-alert]");
113
+ if (!alert) return;
114
+ alert.textContent = text;
115
+ alert.hidden = text === "";
116
+ }
117
+
118
+ /** Wire one booking form. Safe to call twice. */
119
+ export function enhance(form: HTMLFormElement): void {
120
+ if (form.dataset.enhanced) return;
121
+ form.dataset.enhanced = "1";
122
+ form.noValidate = true;
123
+
124
+ const key = form.elements.namedItem("idempotencyKey");
125
+ if (key instanceof HTMLInputElement) key.value = freshKey();
126
+
127
+ // The promo code's Apply button sits inside the widget but belongs to its own form.
128
+ const button = form.querySelector<HTMLButtonElement>('button[type="submit"]:not([data-promo-apply])');
129
+ if (button) button.disabled = false;
130
+
131
+ const qtyInputs = Array.from(form.querySelectorAll<HTMLInputElement>('input[name^="qty:"]'));
132
+ const total = form.querySelector<HTMLElement>("[data-total]");
133
+ const totalValue = total?.querySelector<HTMLElement>("[data-total-value]");
134
+ const updateTotal = () => {
135
+ if (!total || !totalValue) return;
136
+ const minor = orderTotalMinor(
137
+ qtyInputs.map((i) => ({ qty: qtyOf(i), priceMinor: Number(i.dataset.priceMinor) || 0 })),
138
+ );
139
+ totalValue.textContent = formatMinor(
140
+ minor,
141
+ form.dataset.currency ?? "GBP",
142
+ form.dataset.locale ?? "en-GB",
143
+ form.dataset.free ?? "0",
144
+ );
145
+ total.hidden = false;
146
+ };
147
+ for (const input of qtyInputs) input.addEventListener("input", updateTotal);
148
+ updateTotal();
149
+
150
+ form.addEventListener("submit", (event) => {
151
+ if (form.dataset.submitting) {
152
+ event.preventDefault();
153
+ return;
154
+ }
155
+ const bad = [
156
+ ...validateBooking({
157
+ name: fieldValue(form, "name"),
158
+ email: fieldValue(form, "email"),
159
+ lines: qtyInputs.filter((i) => qtyOf(i) > 0).length,
160
+ needsOccurrence: fieldValue(form, "needsOccurrence") === "1",
161
+ occurrenceId: fieldValue(form, "occurrenceId"),
162
+ }),
163
+ ...missingAnswers(questionStates(form)),
164
+ ];
165
+ const needsCheck = form.dataset.turnstile === "on" && fieldValue(form, "cf-turnstile-response") === "";
166
+ if (bad.length > 0 || needsCheck) {
167
+ event.preventDefault();
168
+ formAlert(form, needsCheck && bad.length === 0 ? (form.dataset.turnstileMessage ?? "") : "");
169
+ showErrors(form, bad);
170
+ return;
171
+ }
172
+ formAlert(form, "");
173
+ showErrors(form, []);
174
+ form.dataset.submitting = "1";
175
+ button?.setAttribute("aria-busy", "true");
176
+ });
177
+
178
+ // Back/forward cache: the same page (and key) may submit again; let it.
179
+ window.addEventListener("pageshow", (event) => {
180
+ if (!event.persisted) return;
181
+ delete form.dataset.submitting;
182
+ button?.removeAttribute("aria-busy");
183
+ });
184
+ }
185
+
186
+ if (typeof document !== "undefined") {
187
+ for (const form of document.querySelectorAll<HTMLFormElement>("form[data-semics-booking]")) enhance(form);
188
+ }