@semics-tech/emdash-events 1.0.0-rc.3 → 1.0.0-rc.31

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 (41) hide show
  1. package/README.md +1 -1
  2. package/dist/index.mjs +6 -2
  3. package/dist/manifest.json +6 -5
  4. package/dist/plugin.mjs +7 -6
  5. package/dist/ts/astro/lib/call.d.ts +2 -0
  6. package/dist/ts/astro/lib/call.js +2 -0
  7. package/dist/ts/astro/lib/page.d.ts +44 -0
  8. package/dist/ts/astro/lib/page.js +123 -0
  9. package/dist/ts/integration/index.d.ts +15 -1
  10. package/dist/ts/integration/index.js +21 -1
  11. package/emdash-plugin.jsonc +8 -3
  12. package/package.json +6 -1
  13. package/src/astro/AttendeeList.astro +36 -15
  14. package/src/astro/BookingPage.astro +72 -10
  15. package/src/astro/BookingStatus.astro +209 -54
  16. package/src/astro/BookingWidget.astro +284 -59
  17. package/src/astro/CancelBooking.astro +80 -0
  18. package/src/astro/PageBrand.astro +18 -0
  19. package/src/astro/PageOrganiser.astro +22 -0
  20. package/src/astro/SetupPage.astro +88 -0
  21. package/src/astro/TicketPass.astro +131 -33
  22. package/src/astro/checkout-endpoint.ts +21 -3
  23. package/src/astro/lib/attendees.ts +76 -10
  24. package/src/astro/lib/book-link.ts +46 -0
  25. package/src/astro/lib/call.ts +4 -0
  26. package/src/astro/lib/checkout-form.ts +49 -1
  27. package/src/astro/lib/encryption.ts +67 -0
  28. package/src/astro/lib/list.ts +22 -0
  29. package/src/astro/lib/mapping.ts +106 -0
  30. package/src/astro/lib/page.ts +143 -0
  31. package/src/astro/lib/pass.ts +9 -0
  32. package/src/astro/lib/payment.ts +6 -10
  33. package/src/astro/lib/setup.ts +129 -0
  34. package/src/astro/lib/widget.ts +172 -7
  35. package/src/astro/virtual.d.ts +25 -1
  36. package/src/client/booking.ts +42 -6
  37. package/src/client/forget-form.ts +16 -0
  38. package/src/client/picker.ts +20 -9
  39. package/src/client/print.ts +12 -0
  40. package/src/i18n/ar.ts +55 -1
  41. package/src/i18n/en.ts +57 -1
@@ -41,6 +41,8 @@ export interface PublicRouteError {
41
41
  message: string;
42
42
  /** Input validation issues, when the route reported them (`BAD_REQUEST`). */
43
43
  issues?: PublicRouteIssue[];
44
+ /** Any other top-level fields of the route's refusal, e.g. Vouchers' `lookups` (T166). */
45
+ details?: Record<string, unknown>;
44
46
  }
45
47
 
46
48
  export type PublicRouteResult<T> =
@@ -162,10 +164,12 @@ function refusal(data: unknown): PublicRouteError | undefined {
162
164
  if (!data || typeof data !== "object") return undefined;
163
165
  const body = data as { ok?: unknown; error?: { code?: unknown; message?: unknown }; issues?: unknown };
164
166
  if (body.ok !== false || typeof body.error?.code !== "string") return undefined;
167
+ const { ok: _ok, error: _error, issues: _issues, ...details } = body as Record<string, unknown>;
165
168
  return {
166
169
  code: body.error.code,
167
170
  message: typeof body.error.message === "string" ? body.error.message : "Request failed",
168
171
  ...(Array.isArray(body.issues) ? { issues: body.issues as PublicRouteIssue[] } : {}),
172
+ ...(Object.keys(details).length > 0 ? { details } : {}),
169
173
  };
170
174
  }
171
175
 
@@ -11,13 +11,35 @@ import {
11
11
  widgetErrorLocation,
12
12
  } from "./widget";
13
13
 
14
+ /** What the suite's voucher hook answers (T166): a signed `voucher-hold/1` token, or the refusal's code. */
15
+ export type VoucherHoldResult = { ok: true; hold: string } | { ok: false; code: string };
16
+
17
+ /**
18
+ * Holds a gift voucher for a booking just reserved (T166, voucher/1 §8.1): the suite's `holdVoucher`, given
19
+ * through `eventsIntegration({ vouchers })`. Events never talks to Vouchers itself.
20
+ */
21
+ export type VoucherHook = (
22
+ ctx: PublicRouteContext,
23
+ input: { code: string; bookingRef: string; accessToken: string },
24
+ ) => Promise<VoucherHoldResult>;
25
+
14
26
  export interface CheckoutFormOptions {
15
27
  /** The core's plugin id. Defaults to the slug; registry installs pass their `r_…` id. */
16
28
  pluginId?: string;
17
29
  /** Injected for tests: makes the idempotency key when the form carries none. */
18
30
  newKey?: () => string;
31
+ /** The gift voucher hold (T166); without it a typed voucher code is refused (`VOUCHER_UNAVAILABLE`). */
32
+ voucher?: VoucherHook;
33
+ /** The suite's dry run of that hold before reserving (T168); without it the hold alone decides. */
34
+ check?: VoucherCheckHook;
19
35
  }
20
36
 
37
+ /** Checks a typed gift voucher code before anything is reserved (T168): the suite's `checkVoucher`. */
38
+ export type VoucherCheckHook = (
39
+ ctx: PublicRouteContext,
40
+ input: { code: string; eventId: string; ticketTypeIds: string[] },
41
+ ) => Promise<{ ok: true } | { ok: false; code: string }>;
42
+
21
43
  export interface CheckoutRedirect {
22
44
  location: string;
23
45
  /** The booking's access token, for an HttpOnly cookie scoped to `/booking`. Never in a URL. */
@@ -176,8 +198,22 @@ export async function handleCheckoutForm(
176
198
  needsOccurrence: form.get("needsOccurrence") === "1",
177
199
  occurrenceId,
178
200
  });
201
+ // A booking request (T174a): a date and a window instead of an occurrence; both are needed.
202
+ const request = { date: text(form, "requestDate"), window: text(form, "requestWindow") };
203
+ const asks = form.get("needsRequest") === "1";
204
+ if (asks && !(request.date && request.window)) invalid.push("occurrence");
179
205
  if (invalid.length > 0) return refuse("BAD_REQUEST", invalid);
180
206
 
207
+ // A gift voucher (T166) is held between reserve and continue; without the suite's hook it cannot be.
208
+ const voucherCode = text(form, "voucherCode");
209
+ if (voucherCode && !options.voucher) return refuse("VOUCHER_UNAVAILABLE", ["voucher"]);
210
+ // T168: a code the suite's check refuses never reserves, so no booking is held, cancelled and emailed.
211
+ if (voucherCode && options.check) {
212
+ const ticketTypeIds = lines.map((l) => l.ticketTypeId);
213
+ const checked = await options.check(ctx, { code: voucherCode, eventId, ticketTypeIds });
214
+ if (!checked.ok) return refuse(checked.code, ["voucher"]);
215
+ }
216
+
181
217
  const turnstileToken = text(form, "cf-turnstile-response");
182
218
  // Only a typed code is sent: Free's reserve refuses unknown keys, and only Pro offers the field.
183
219
  const promoCode = text(form, "promoCode");
@@ -190,6 +226,7 @@ export async function handleCheckoutForm(
190
226
  body: {
191
227
  eventId,
192
228
  ...(occurrenceId ? { occurrenceId } : {}),
229
+ ...(asks ? { request } : {}),
193
230
  lines,
194
231
  buyer,
195
232
  idempotencyKey: text(form, "idempotencyKey") || (options.newKey ?? newIdempotencyKey)(),
@@ -210,11 +247,22 @@ export async function handleCheckoutForm(
210
247
  // A resubmit of a booking that is already confirmed gets no new token: this browser has its cookie.
211
248
  if (!accessToken) return { location: done };
212
249
  const cookie = { name: bookingCookieName(bookingRef), value: accessToken };
250
+ let voucherHold: string | undefined;
251
+ if (voucherCode && options.voucher) {
252
+ const held = await options.voucher(ctx, { code: voucherCode, bookingRef, accessToken });
253
+ if (!held.ok) {
254
+ // Nothing paid yet: release the places so the corrected order can have them.
255
+ const body = { bookingRef, accessToken };
256
+ await callPublicRoute(ctx, { method: "POST", path: "public/booking/cancel", pluginId, body });
257
+ return refuse(held.code, ["voucher"]);
258
+ }
259
+ voucherHold = held.hold;
260
+ }
213
261
  const next = await callPublicRoute<{ next?: { type?: string; url?: string } }>(ctx, {
214
262
  method: "POST",
215
263
  path: "public/checkout/continue",
216
264
  pluginId,
217
- body: { bookingRef, accessToken },
265
+ body: { bookingRef, accessToken, ...(voucherHold ? { voucherHold } : {}) },
218
266
  });
219
267
  if (!next.ok) return fail(next.error.code, bookingRef, cookie);
220
268
 
@@ -0,0 +1,67 @@
1
+ // i18n-ignore-file: administrators only, in English like the admin it moved from (the setup check, T178).
2
+ /**
3
+ * Encryption-key notice state for the setup check page, `/_events/setup` (spike S8, T178).
4
+ *
5
+ * Secret settings are encrypted with `EMDASH_ENCRYPTION_KEY`. A sandboxed plugin cannot read the
6
+ * environment, so the caller reports what it can observe: whether the host said a key is
7
+ * configured (when it knows), and for each secret setting whether it is unset, readable, or
8
+ * stored but unreadable (wrong, rotated or lost key). Pure: no I/O.
9
+ */
10
+
11
+ export type SecretReadOutcome = "unset" | "readable" | "unreadable";
12
+
13
+ export interface EncryptionKeyInput {
14
+ /** `false` when the host reports no key; leave undefined when that is not known. */
15
+ keyConfigured?: boolean;
16
+ secrets: Readonly<Record<string, SecretReadOutcome>>;
17
+ }
18
+
19
+ export interface EncryptionKeyBanner {
20
+ severity: "error";
21
+ title: string;
22
+ message: string;
23
+ }
24
+
25
+ export interface EncryptionKeyStatus {
26
+ state: "ok" | "missing" | "unreadable";
27
+ /** Whether a secret setting can be saved right now. */
28
+ secretsWritable: boolean;
29
+ banner: EncryptionKeyBanner | null;
30
+ /** Secret settings the banner is about, sorted. */
31
+ affected: string[];
32
+ }
33
+
34
+ const KEY = "EMDASH_ENCRYPTION_KEY";
35
+
36
+ export function encryptionKeyStatus(input: EncryptionKeyInput): EncryptionKeyStatus {
37
+ const names = Object.keys(input.secrets).sort();
38
+
39
+ if (input.keyConfigured === false) {
40
+ return {
41
+ state: "missing",
42
+ secretsWritable: false,
43
+ affected: names,
44
+ banner: {
45
+ severity: "error",
46
+ title: "Encryption key missing",
47
+ message: `Set ${KEY} on the site and restart it to save secret settings.`,
48
+ },
49
+ };
50
+ }
51
+
52
+ const unreadable = names.filter((name) => input.secrets[name] === "unreadable");
53
+ if (unreadable.length) {
54
+ return {
55
+ state: "unreadable",
56
+ secretsWritable: true,
57
+ affected: unreadable,
58
+ banner: {
59
+ severity: "error",
60
+ title: "Saved secrets cannot be read",
61
+ message: `${unreadable.join(", ")} cannot be decrypted. ${KEY} is missing, changed or does not include the key the value was saved with. Restore the key, or enter the value again.`,
62
+ },
63
+ };
64
+ }
65
+
66
+ return { state: "ok", secretsWritable: true, banner: null, affected: [] };
67
+ }
@@ -62,6 +62,28 @@ const WHEN: Intl.DateTimeFormatOptions = {
62
62
  timeZoneName: "short",
63
63
  };
64
64
 
65
+ /** The booking widget's and the waiver page's date format: full date, short time. */
66
+ const AT: Intl.DateTimeFormatOptions = { dateStyle: "full", timeStyle: "short" };
67
+
68
+ /**
69
+ * A time on a customer page (a deadline, a hold, the booked session): local time in the event's own zone, as the
70
+ * session's time line reads ("Monday 9 November 2026 at 15:09", T157), without the zone's name. A missing or
71
+ * unknown zone shows UTC and says so; a value that is not a date is shown as it is.
72
+ */
73
+ export function zonedAt(iso: string, timezone: string | null | undefined, locale: string): string {
74
+ const ms = Date.parse(iso);
75
+ if (!Number.isFinite(ms)) return iso;
76
+ const known = Boolean(timezone && isValidTimeZone(timezone));
77
+ const zone = known ? (timezone as string) : "UTC";
78
+ let time: string;
79
+ try {
80
+ time = formatInZone(ms, zone, locale, AT);
81
+ } catch {
82
+ time = formatInZone(ms, zone, "en-GB", AT); // A locale `Intl` refuses, such as `en_GB`.
83
+ }
84
+ return known ? time : `${time} (${zone})`;
85
+ }
86
+
65
87
  const BADGES = { cancelled: "list.badge.cancelled", closed: "list.badge.closed", paused: "list.badge.paused" } as const;
66
88
 
67
89
  /** The start in the event's own zone; a missing or unknown zone shows UTC rather than failing. */
@@ -0,0 +1,106 @@
1
+ // i18n-ignore-file: administrators only, in English like the admin it moved from (the setup check, T178).
2
+ /**
3
+ * Events collection mapping validation (EV-FR-01).
4
+ *
5
+ * The settings map the site's events collection and the fields that hold start, end, timezone and
6
+ * venue. The setup check page (`/_events/setup`, T178) reads the collections through the host and passes
7
+ * their field names in; this module only decides whether the mapping holds and what the notice says. Pure.
8
+ */
9
+
10
+ export interface EventsMapping {
11
+ eventsCollection: string;
12
+ fieldStartsAt: string;
13
+ fieldEndsAt: string;
14
+ fieldTimezone: string;
15
+ fieldVenue: string;
16
+ }
17
+
18
+ export type CollectionSchemas = Readonly<Record<string, { fields: readonly string[] }>>;
19
+
20
+ export type MappingSetting = keyof EventsMapping;
21
+ export type MappingProblemReason = "unset" | "missing-collection" | "missing-field";
22
+
23
+ export interface MappingProblem {
24
+ setting: MappingSetting;
25
+ /** The value that failed: the collection slug or the field name. */
26
+ field: string;
27
+ reason: MappingProblemReason;
28
+ }
29
+
30
+ export interface MappingBanner {
31
+ severity: "error";
32
+ title: string;
33
+ message: string;
34
+ }
35
+
36
+ export interface MappingResult {
37
+ ok: boolean;
38
+ problems: MappingProblem[];
39
+ banner: MappingBanner | null;
40
+ }
41
+
42
+ export const LABELS: Record<MappingSetting, string> = {
43
+ eventsCollection: "Events collection",
44
+ fieldStartsAt: "Start field",
45
+ fieldEndsAt: "End field",
46
+ fieldTimezone: "Timezone field",
47
+ fieldVenue: "Venue field",
48
+ };
49
+
50
+ const REQUIRED: readonly MappingSetting[] = ["fieldStartsAt", "fieldTimezone"];
51
+ const FIELD_SETTINGS: readonly MappingSetting[] = ["fieldStartsAt", "fieldEndsAt", "fieldTimezone", "fieldVenue"];
52
+ const TITLE = "Events field mapping needs attention";
53
+
54
+ function join(parts: string[]): string {
55
+ return parts.length <= 1 ? (parts[0] ?? "") : `${parts.slice(0, -1).join(", ")} or ${parts[parts.length - 1]}`;
56
+ }
57
+
58
+ function fail(problems: MappingProblem[], message: string): MappingResult {
59
+ return { ok: false, problems, banner: { severity: "error", title: TITLE, message } };
60
+ }
61
+
62
+ export function validateMapping(mapping: EventsMapping, schemas: CollectionSchemas): MappingResult {
63
+ const slug = mapping.eventsCollection.trim();
64
+ if (slug === "") {
65
+ return fail(
66
+ [{ setting: "eventsCollection", field: "", reason: "unset" }],
67
+ `${LABELS.eventsCollection} is not set. Choose the collection that holds your events in the Events settings.`,
68
+ );
69
+ }
70
+
71
+ const schema = schemas[slug];
72
+ if (!schema) {
73
+ const available = Object.keys(schemas).sort().join(", ");
74
+ return fail(
75
+ [{ setting: "eventsCollection", field: slug, reason: "missing-collection" }],
76
+ `The collection "${slug}" does not exist. Choose an existing collection in the Events settings.${available ? ` Available: ${available}.` : ""}`,
77
+ );
78
+ }
79
+
80
+ const unset: MappingProblem[] = [];
81
+ const missing: MappingProblem[] = [];
82
+ for (const setting of FIELD_SETTINGS) {
83
+ const field = mapping[setting].trim();
84
+ if (field === "") {
85
+ if (REQUIRED.includes(setting)) unset.push({ setting, field: "", reason: "unset" });
86
+ } else if (!schema.fields.includes(field)) {
87
+ missing.push({ setting, field, reason: "missing-field" });
88
+ }
89
+ }
90
+
91
+ if (unset.length) {
92
+ const names = unset.map((p) => LABELS[p.setting]);
93
+ return fail(
94
+ [...unset, ...missing],
95
+ `${names.join(" and ")} ${names.length > 1 ? "are" : "is"} not set. Choose the field in the Events settings.`,
96
+ );
97
+ }
98
+ if (missing.length) {
99
+ const named = missing.map((p) => `"${p.field}" (${LABELS[p.setting]})`);
100
+ return fail(
101
+ missing,
102
+ `The "${slug}" collection has no field ${join(named)}. Add the field to the collection, or choose another field in the Events settings.`,
103
+ );
104
+ }
105
+ return { ok: true, problems: [], banner: null };
106
+ }
@@ -0,0 +1,143 @@
1
+ // i18n-ignore-file: a stylesheet and its option names, no text for people.
2
+ /**
3
+ * The look of the plugins' own full pages (`/booking`, the suite's `/_events/waiver`), which run outside the
4
+ * site's layout: a default stylesheet built only on the `--events-*` properties, and what a site sets through
5
+ * `eventsIntegration({ page })` / `eventsSuite({ page })`. It is one exact string so the signing page can allow
6
+ * it by hash (its CSP allows nothing else inline, `ceremonyCsp`). Web APIs only (R35).
7
+ *
8
+ * The site's own layout is deliberately not wrapped around these pages: an emailed link's one-time code is in the
9
+ * URL here, and a signing page's CSP would block the layout's scripts and styles anyway.
10
+ */
11
+
12
+ /** A theme value by property: `accent` sets `--events-accent` (the signing form follows, see `PAGE_CSS`). */
13
+ export const THEME_PROPERTIES = [
14
+ "fg",
15
+ "muted",
16
+ "bg",
17
+ "border",
18
+ "accent",
19
+ "accent-fg",
20
+ "error",
21
+ "success",
22
+ "radius",
23
+ "font",
24
+ "page-bg",
25
+ "heading-font",
26
+ "heading-fg",
27
+ ] as const;
28
+ export type ThemeProperty = (typeof THEME_PROPERTIES)[number];
29
+ export interface PageBrand {
30
+ /** The site's name: the link's text, or the logo's alternative text. Also the organiser at the page's foot. */
31
+ name: string;
32
+ /** Where it links, a path on this site (default `/`). */
33
+ href?: string;
34
+ /** A logo, a path on this site. */
35
+ logo?: string;
36
+ /** The organiser's postal address, one line, at the page's foot and on a printed booking (T157). */
37
+ address?: string;
38
+ }
39
+
40
+ /** One line of text for people: 1 to 300 characters, no control characters (line breaks included). */
41
+ function oneLine(value: unknown): boolean {
42
+ if (typeof value !== "string" || !value.trim() || value.length > 300) return false;
43
+ for (let i = 0; i < value.length; i++) {
44
+ const unit = value.charCodeAt(i);
45
+ if (unit <= 0x1f || unit === 0x7f) return false;
46
+ }
47
+ return true;
48
+ }
49
+
50
+ export interface PageOptions {
51
+ /** Values for the pages' custom properties, for example `{ accent: "#1f3a2e", "page-bg": "#f6f1ea" }`. */
52
+ theme?: Partial<Record<ThemeProperty, string>>;
53
+ /** A stylesheet on this site, loaded after the defaults: for `@font-face`, or any further rules. */
54
+ stylesheet?: string;
55
+ /** The site's name or logo at the top of each page. */
56
+ brand?: PageBrand;
57
+ /** The event's page, where "Book again" goes: a path with `{slug}` (default `/events/{slug}`). */
58
+ eventPath?: string;
59
+ }
60
+
61
+ /** One line of CSS, nothing that could end the declaration, the rule or the `<style>` element. */
62
+ const THEME_VALUE = /^[^;{}<>\\@]{1,200}$/;
63
+ /** A path on this site; `;` and `,` would end a source in the signing page's CSP header. */
64
+ const SITE_PATH = /^\/(?!\/)[^\s"'<>\\;,]*$/;
65
+
66
+ /** Checks a site's page options when the site's config loads; a bad value stops the build with its name. */
67
+ export function checkPageOptions(page: PageOptions = {}): PageOptions {
68
+ const refuse = (what: string) => {
69
+ throw new Error(`page.${what} is not valid`); // i18n-ignore
70
+ };
71
+ for (const [name, value] of Object.entries(page.theme ?? {})) {
72
+ const known = (THEME_PROPERTIES as readonly string[]).includes(name);
73
+ if (!known || typeof value !== "string" || !THEME_VALUE.test(value) || /url\(/i.test(value))
74
+ refuse(`theme.${name}`);
75
+ }
76
+ const { brand, stylesheet, eventPath } = page;
77
+ if (stylesheet !== undefined && !SITE_PATH.test(stylesheet)) refuse("stylesheet");
78
+ if (eventPath !== undefined && !(SITE_PATH.test(eventPath) && eventPath.includes("{slug}"))) refuse("eventPath");
79
+ if (brand) {
80
+ if (typeof brand.name !== "string" || !brand.name.trim()) refuse("brand.name");
81
+ if (brand.href !== undefined && !SITE_PATH.test(brand.href)) refuse("brand.href");
82
+ if (brand.logo !== undefined && !SITE_PATH.test(brand.logo)) refuse("brand.logo");
83
+ if (brand.address !== undefined && !oneLine(brand.address)) refuse("brand.address");
84
+ }
85
+ return page;
86
+ }
87
+
88
+ /** The event's page for "Book again"; undefined when the booking does not know its slug. */
89
+ export function eventPageHref(slug: string | null | undefined, eventPath?: string): string | undefined {
90
+ return slug ? (eventPath ?? "/events/{slug}").replace("{slug}", encodeURIComponent(slug)) : undefined;
91
+ }
92
+
93
+ /**
94
+ * Works with no site theme at all. Zero specificity on elements, so the components' own rules win; except the card
95
+ * rule for `main`'s sections, which outranks a component's own box (`.semics-payment`, `.semics-attendee-list`) so
96
+ * every card has the same edges, width and look (T158).
97
+ */
98
+ export const PAGE_CSS = `*,*::before,*::after{box-sizing:border-box}
99
+ html{color-scheme:light;-webkit-text-size-adjust:100%}
100
+ body.semics-page{margin:0;min-block-size:100vh;background:var(--events-page-bg, #f5f4f0);color:var(--events-fg, #1a1a1a);font-family:var(--events-font, system-ui, sans-serif);font-size:1.0625rem;line-height:1.55;overflow-wrap:anywhere;
101
+ --esign-fg:var(--events-fg, #1a1a1a);--esign-muted:var(--events-muted, #4a4a4a);--esign-bg:var(--events-bg, #ffffff);--esign-border:var(--events-border, #6b6b6b);--esign-accent:var(--events-accent, #0b57d0);--esign-accent-fg:var(--events-accent-fg, #ffffff);--esign-error:var(--events-error, #b3261e);--esign-radius:var(--events-radius, 6px);--esign-font:var(--events-font, system-ui, sans-serif)}
102
+ .semics-page-brand{max-inline-size:40rem;margin-inline:auto;padding:1.25rem 1rem 0;font-family:var(--events-heading-font, inherit);font-weight:600}
103
+ .semics-page-brand a{color:var(--events-heading-fg, inherit);text-decoration:none}
104
+ .semics-page-brand img{display:block;block-size:2.5rem;inline-size:auto;max-inline-size:100%}
105
+ .semics-page-main{max-inline-size:40rem;margin-inline:auto;padding:1.5rem 1rem 2rem}
106
+ :where(.semics-page) :is(h1,h2,h3){margin:0 0 .75rem;font-family:var(--events-heading-font, inherit);color:var(--events-heading-fg, inherit);line-height:1.2}
107
+ :where(.semics-page) h1{margin-block-end:1.25rem;font-size:clamp(1.75rem,1.5rem + 1.5vw,2.25rem)}
108
+ :where(.semics-page) h2{font-size:1.25rem}
109
+ :where(.semics-page) h3{font-size:1.0625rem}
110
+ :where(.semics-page) p{margin:0 0 .75rem}
111
+ :where(.semics-page) a{color:var(--events-accent, #0b57d0);text-underline-offset:.2em}
112
+ :where(.semics-page) :focus-visible{outline:3px solid var(--events-accent, #0b57d0);outline-offset:2px}
113
+ .semics-page-main > :is(section,form:not([hidden]),.semics-ceremony){margin-block:0 1.25rem;padding:clamp(1.25rem,.9rem + 1.8vw,1.75rem);background:var(--events-bg, #ffffff);border:1px solid color-mix(in srgb,var(--events-border, #6b6b6b) 30%,transparent);border-radius:calc(var(--events-radius, 6px) + 6px);box-shadow:0 1px 2px rgb(0 0 0 / .04),0 6px 24px rgb(0 0 0 / .05);max-inline-size:none}
114
+ :where(.semics-page-main > section,.semics-page-main > form,.semics-page-main > .semics-ceremony) > :last-child{margin-block-end:0}
115
+ :where(.semics-page) [role="alert"]{padding:.75rem 1rem;border:1px solid var(--events-error, #b3261e);border-radius:var(--events-radius, 6px);background:var(--events-bg, #ffffff);color:var(--events-error, #b3261e)}
116
+ :where(.semics-page) :is(input:not([type="checkbox"],[type="radio"],[type="hidden"]),select,textarea){font:inherit;inline-size:100%;min-block-size:2.75rem;padding:.5rem .75rem;border:1px solid var(--events-border, #6b6b6b);border-radius:var(--events-radius, 6px);background:var(--events-bg, #ffffff);color:var(--events-fg, #1a1a1a)}
117
+ :where(.semics-page) label{display:block}
118
+ :where(.semics-page) fieldset{min-inline-size:0;margin:0 0 1rem;padding:0;border:0}
119
+ :where(.semics-page) legend{padding:0;margin-block-end:.5rem;font-weight:600}
120
+ :where(.semics-page) button{font:inherit;font-weight:600;min-block-size:2.75rem;padding:.625rem 1.25rem;border:1px solid var(--events-accent, #0b57d0);border-radius:var(--events-radius, 6px);background:var(--events-accent, #0b57d0);color:var(--events-accent-fg, #ffffff);cursor:pointer}
121
+ :where(.semics-page) a.semics-page-button{display:inline-block;font-weight:600;padding:.625rem 1.25rem;border:1px solid var(--events-accent, #0b57d0);border-radius:var(--events-radius, 6px);background:var(--events-accent, #0b57d0);color:var(--events-accent-fg, #ffffff);text-decoration:none}
122
+ .semics-page-actions{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem 1.25rem;margin-block:0 1.25rem}
123
+ .semics-page-actions .semics-print{background:transparent;color:var(--events-accent, #0b57d0)}
124
+ .semics-page-organiser{max-inline-size:40rem;margin-inline:auto;padding:0 1rem 3rem;color:var(--events-muted, #4a4a4a);font-size:.9375rem}
125
+ .semics-page-organiser p{margin:0}
126
+ .semics-page-organiser address{font-style:normal}
127
+ @media print{
128
+ @page{margin:15mm}
129
+ body.semics-page{min-block-size:0;background:#ffffff;color:#000000;font-size:11pt}
130
+ .semics-page-brand,.semics-page-actions,.semics-page-main form,.semics-page-main button,.semics-page-main details,.semics-add-to-calendar,[data-semics-payment-live]{display:none !important}
131
+ .semics-page-main{max-inline-size:none;padding:0}
132
+ .semics-page-main > :is(section,form:not([hidden]),.semics-ceremony){box-shadow:none;border-color:#999999;break-inside:avoid}
133
+ .semics-ticket-pass{break-inside:avoid}
134
+ .semics-page-organiser{max-inline-size:none;padding:1rem 0 0;color:#000000}
135
+ }
136
+ `;
137
+
138
+ /** The stylesheet for a page: the defaults, then the site's theme. Exact: the signing page hashes this text. */
139
+ export function pageCss(page: PageOptions = {}): string {
140
+ const set = Object.entries(page.theme ?? {}) as Array<[ThemeProperty, string]>;
141
+ if (set.length === 0) return PAGE_CSS;
142
+ return `${PAGE_CSS}:root{${set.map(([name, value]) => `--events-${name}:${value}`).join(";")}}\n`;
143
+ }
@@ -33,3 +33,12 @@ export function qrPath(qr: unknown): QrPath | null {
33
33
  }
34
34
  return { size, d };
35
35
  }
36
+
37
+ /**
38
+ * A check-in code in groups of four for reading (T158): the pass draws each group as its own span, spaced by CSS, so
39
+ * the text (and a copy of it) stays the exact value door check-in takes. A short code (12 or fewer) stays whole.
40
+ */
41
+ export function codeGroups(code: string): string[] {
42
+ if (code.length <= 12) return code ? [code] : [];
43
+ return code.match(/.{1,4}/gsu) ?? [];
44
+ }
@@ -5,6 +5,7 @@
5
5
  * way" are told apart by asking the core, never by a query parameter.
6
6
  */
7
7
  import { type MessageKey, t } from "../../i18n/index";
8
+ import { zonedAt } from "./list";
8
9
  import type { BookingView } from "./widget";
9
10
 
10
11
  export type PaymentState = "confirmed" | "pending" | "expired" | "cancelled" | "refunded" | "refunded_unavailable";
@@ -19,15 +20,6 @@ export interface PaymentView {
19
20
  resume: boolean;
20
21
  }
21
22
 
22
- const utc = (iso: string, locale: string) => {
23
- try {
24
- const at = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
25
- return t(locale, "time.utc", { time: at.format(new Date(iso)) });
26
- } catch {
27
- return iso;
28
- }
29
- };
30
-
31
23
  /** The provider's payment page is followed only when it is an `https:` URL (never `javascript:` or `//host`). */
32
24
  export function isPayUrl(value: unknown): value is string {
33
25
  if (typeof value !== "string" || !value.startsWith("https://")) return false;
@@ -49,13 +41,17 @@ const final = (state: PaymentState, locale: string): PaymentView => ({
49
41
  /** The payment section for a booking, or `null` when there is nothing to say about money. */
50
42
  export function paymentView(booking: BookingView, locale = "en-GB"): PaymentView | null {
51
43
  const paid = booking.totals.totalMinor > 0;
44
+ // Ran out waiting for the organiser: not about a payment (`endedNotes` says what happened).
45
+ if (booking.status === "expired" && booking.undecided) return null;
52
46
  switch (booking.status) {
53
47
  case "awaiting_payment":
54
48
  return {
55
49
  state: "pending",
56
50
  heading: t(locale, "payment.pending.heading"),
57
51
  body: booking.holdExpiresAt
58
- ? t(locale, "payment.pending.bodyUntil", { time: utc(booking.holdExpiresAt, locale) })
52
+ ? t(locale, "payment.pending.bodyUntil", {
53
+ time: zonedAt(booking.holdExpiresAt, booking.event?.timezone, locale),
54
+ })
59
55
  : t(locale, "payment.pending.body"),
60
56
  poll: true,
61
57
  resume: true,
@@ -0,0 +1,129 @@
1
+ // i18n-ignore-file: administrators only, in English like the admin it moved from (the setup check, T178).
2
+ /**
3
+ * The Events setup check, behind `/_events/setup` (EV-FR-01, S8, T047; moved off the admin page in T178).
4
+ *
5
+ * It ran in the sandboxed admin page; it now runs on the site so the Free backend does not carry it.
6
+ * Facts this rests on (EmDash 1.2):
7
+ * - The host's plugin-settings read (`GET /_emdash/api/admin/plugins/<id>/settings`, run in process with
8
+ * the visitor's `locals`) checks `plugins:manage`, so it is the administrator check. It answers
9
+ * `{ schema, values, secretsSet }`: secret settings are masked to `secretsSet[key]` (stored and not
10
+ * empty), never their values.
11
+ * - The host's schema read (`GET /_emdash/api/schema`) checks `schema:read` and lists every collection
12
+ * with its fields.
13
+ * - Telling a readable secret from one saved under a lost or changed `EMDASH_ENCRYPTION_KEY` needs a
14
+ * decrypt: `readSecret` (`getPluginSetting` in the page) throws when the host cannot open the value.
15
+ * It is called only after the administrator check and only for secrets the host says are set; the
16
+ * value is dropped here, only "readable" or "unreadable" is kept.
17
+ *
18
+ * Glue only: the rules are `validateMapping` and `encryptionKeyStatus`, the same as the admin page used.
19
+ */
20
+
21
+ import { encryptionKeyStatus, type SecretReadOutcome } from "./encryption";
22
+ import { type EventsMapping, LABELS, validateMapping } from "./mapping";
23
+
24
+ /** The page (injected by `eventsIntegration`). */
25
+ export const SETUP_PATH = "/_events/setup";
26
+
27
+ export interface SetupContext {
28
+ /** Astro's locals: a visitor with no `user` is refused before anything is read. */
29
+ locals: unknown;
30
+ /** The host's plugin-settings read for the Events core, with the visitor's locals. */
31
+ readSettings(): Promise<Response>;
32
+ /** The host's schema read (`/_emdash/api/schema`), with the visitor's locals. */
33
+ readSchema(): Promise<Response>;
34
+ /** One stored setting of the Events core, decrypted on the server; throws when it cannot be. */
35
+ readSecret(key: string): Promise<unknown>;
36
+ }
37
+
38
+ export interface SetupNotice {
39
+ severity: "error" | "warning";
40
+ title: string;
41
+ message: string;
42
+ }
43
+
44
+ export type SetupView =
45
+ | { state: "forbidden" }
46
+ | { state: "error" }
47
+ | { state: "ok"; notices: SetupNotice[]; fields: Array<{ label: string; value: string }> };
48
+
49
+ const MAPPING_DEFAULTS: EventsMapping = {
50
+ eventsCollection: "events",
51
+ fieldStartsAt: "starts_at",
52
+ fieldEndsAt: "ends_at",
53
+ fieldTimezone: "timezone",
54
+ fieldVenue: "venue",
55
+ };
56
+
57
+ const NO_TURNSTILE: SetupNotice = {
58
+ severity: "warning",
59
+ title: "Turnstile is not set up",
60
+ message: "Checkout runs without a bot check; add the Turnstile keys.",
61
+ };
62
+
63
+ type Read = { kind: "ok"; data: Record<string, unknown> } | { kind: "forbidden" } | { kind: "error" };
64
+
65
+ async function read(get: () => Promise<Response>): Promise<Read> {
66
+ const res = await get().catch(() => null);
67
+ if (!res) return { kind: "error" };
68
+ if (res.status === 401 || res.status === 403) return { kind: "forbidden" };
69
+ const body = (await res.json().catch(() => null)) as { success?: unknown; data?: unknown } | null;
70
+ const data = body?.data;
71
+ if (!res.ok || body?.success !== true || !data || typeof data !== "object") return { kind: "error" };
72
+ return { kind: "ok", data: data as Record<string, unknown> };
73
+ }
74
+
75
+ const record = (v: unknown): Record<string, unknown> =>
76
+ v && typeof v === "object" ? (v as Record<string, unknown>) : {};
77
+
78
+ /** Readable when the host opens it to text; anything else it stores but cannot give back is unreadable. */
79
+ async function outcome(ctx: SetupContext, key: string, set: unknown): Promise<SecretReadOutcome> {
80
+ if (set !== true) return "unset";
81
+ const value = await ctx.readSecret(key).catch(() => null);
82
+ return typeof value === "string" && value !== "" ? "readable" : "unreadable";
83
+ }
84
+
85
+ /** The page's state. Nothing is read beyond the settings unless the visitor may manage plugins. */
86
+ export async function setupCheck(ctx: SetupContext): Promise<SetupView> {
87
+ // Signed out: refused here, as `/_events/pair` does (without a session the host's handlers can answer 500).
88
+ if (!(ctx.locals as { user?: unknown } | null | undefined)?.user) return { state: "forbidden" };
89
+ const settings = await read(ctx.readSettings);
90
+ if (settings.kind !== "ok") return { state: settings.kind };
91
+ const schema = await read(ctx.readSchema);
92
+ if (schema.kind !== "ok") return { state: schema.kind };
93
+
94
+ const values = record(settings.data.values);
95
+ const mapping = { ...MAPPING_DEFAULTS };
96
+ for (const key of Object.keys(mapping) as Array<keyof EventsMapping>) {
97
+ const v = values[key];
98
+ if (typeof v === "string") mapping[key] = v;
99
+ }
100
+ const collections = Array.isArray(schema.data.collections) ? schema.data.collections : [];
101
+ const schemas = Object.fromEntries(
102
+ collections.map((c) => {
103
+ const { slug, fields } = record(c);
104
+ const names = Array.isArray(fields) ? fields.map((f) => String(record(f).slug ?? "")) : [];
105
+ return [String(slug ?? ""), { fields: names }];
106
+ }),
107
+ );
108
+ const mapped = validateMapping(mapping, schemas);
109
+
110
+ // Every secret setting the host declares for the core (Pro's too), in the host's own order.
111
+ const set = Object.entries(record(settings.data.secretsSet));
112
+ const secrets: Record<string, SecretReadOutcome> = {};
113
+ for (const [key, isSet] of set) secrets[key] = await outcome(ctx, key, isSet);
114
+ const encryption = encryptionKeyStatus({ secrets });
115
+
116
+ const notices: SetupNotice[] = [];
117
+ if (mapped.banner) notices.push(mapped.banner);
118
+ if (encryption.banner) notices.push(encryption.banner);
119
+ if ((secrets.turnstileSecretKey ?? "unset") === "unset") notices.push(NO_TURNSTILE);
120
+
121
+ return {
122
+ state: "ok",
123
+ notices,
124
+ fields: (Object.keys(LABELS) as Array<keyof EventsMapping>).map((k) => ({
125
+ label: LABELS[k],
126
+ value: mapping[k] || "(not set)",
127
+ })),
128
+ };
129
+ }