@scopetickets/checkout 0.6.3 → 0.7.1

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.
@@ -1,3556 +0,0 @@
1
- // src/island/island-press.ts
2
- import {
3
- createContext,
4
- useContext,
5
- useEffect,
6
- useMemo,
7
- useRef,
8
- useState
9
- } from "react";
10
-
11
- // ../checkout-core/src/motion/island-motion.ts
12
- var SURFACE_MORPH_MS = 250;
13
- var SURFACE_DAMPING = 0.82;
14
- var SURFACE_SPRING = {
15
- response: responseForSettle(SURFACE_MORPH_MS / 1e3, SURFACE_DAMPING),
16
- damping: SURFACE_DAMPING,
17
- clampOvershoot: false
18
- };
19
- var CARRY_SPRING = {
20
- response: responseForSettle(SURFACE_MORPH_MS / 1e3, 0.95),
21
- damping: 0.95,
22
- clampOvershoot: true
23
- };
24
- var POP_RETURN_SPRING = { ...SURFACE_SPRING, clampOvershoot: true };
25
- function responseForSettle(settleSeconds, damping) {
26
- return settleSeconds * damping * 2 * Math.PI / 4;
27
- }
28
- function naturalFrequency({ response }) {
29
- return 2 * Math.PI / response;
30
- }
31
- function settleMs(spring) {
32
- const exact = 4 / (spring.damping * naturalFrequency(spring)) * 1e3;
33
- return Math.ceil(Number(exact.toFixed(9)));
34
- }
35
- function springAt(spring, t) {
36
- const wn = naturalFrequency(spring);
37
- const z = spring.damping;
38
- const wd = wn * Math.sqrt(1 - z * z);
39
- const value = 1 - Math.exp(-z * wn * t) * (Math.cos(wd * t) + z / Math.sqrt(1 - z * z) * Math.sin(wd * t));
40
- return spring.clampOvershoot ? Math.min(value, 1) : value;
41
- }
42
- var OUTGOING_FADE_MS = 125;
43
- var SURFACE_MORPH_DELAY_MS = OUTGOING_FADE_MS;
44
- var INCOMING_FADE_DELAY_MS = SURFACE_MORPH_DELAY_MS + SURFACE_MORPH_MS;
45
- var INCOMING_FADE_MS = 175;
46
- var DAY_SWAP_STRETCH = 1.6;
47
- var DAY_SWAP_OUT_MS = Math.round(OUTGOING_FADE_MS * DAY_SWAP_STRETCH);
48
- var DAY_SWAP_IN_MS = Math.round(INCOMING_FADE_MS * DAY_SWAP_STRETCH);
49
- var ARC_LEAD_BEZIER = [0.61, 1, 0.88, 1];
50
- var ARC_TRAIL_BEZIER = [0.12, 0, 0.39, 0];
51
- var CARRY_MOVE_DELAY_MS = SURFACE_MORPH_DELAY_MS;
52
- var CARRY_MOVE_MS = settleMs(CARRY_SPRING);
53
- var POP_SCALE = 0.95;
54
- var SHIELD_POP_SCALE = 1 - (1 - POP_SCALE) / 2;
55
- var POP_CONTRACT_MS = OUTGOING_FADE_MS;
56
- var POP_RETURN_MS = settleMs(POP_RETURN_SPRING);
57
- var POP_MS = POP_CONTRACT_MS + POP_RETURN_MS;
58
- var POP_TURN_PERCENT = Number((POP_CONTRACT_MS / POP_MS * 100).toFixed(3));
59
- var PRESS_IN_MS = POP_CONTRACT_MS;
60
- var PRESS_LETGO_MS = 50;
61
- var PRESS_RETURN_MS = SURFACE_MORPH_DELAY_MS + SURFACE_MORPH_MS;
62
- var ISLAND_TRANSITION_MS = Math.max(
63
- INCOMING_FADE_DELAY_MS + INCOMING_FADE_MS,
64
- CARRY_MOVE_DELAY_MS + CARRY_MOVE_MS,
65
- POP_MS
66
- );
67
- var BAY_SWAP_IN_PERCENT = Number(
68
- (INCOMING_FADE_DELAY_MS / ISLAND_TRANSITION_MS * 100).toFixed(3)
69
- );
70
- var PROCESSING_FLOOR_MS = 3e3;
71
- var PAID_GRACE_MS = 6e3;
72
- var ACCOUNT_CREATING_FLOOR_MS = 3e3;
73
- var HOLD_TICK_MS = 500;
74
-
75
- // src/island/island-press.ts
76
- var PressContext = createContext(null);
77
- var primaryHeld = (event) => (event.buttons & 1) === 1;
78
- var AT_REST = { at: "rest" };
79
- var RISEN = { at: "rising", timer: null };
80
- function stopWaiting(sink) {
81
- if (sink.at === "rising" && sink.timer !== null) window.clearTimeout(sink.timer);
82
- }
83
- function useIslandPress(scope = "island") {
84
- const api = useContext(PressContext);
85
- const [pressedHere, setPressedHere] = useState(false);
86
- const whole = scope === "island";
87
- const sink = useRef(AT_REST);
88
- useEffect(() => () => stopWaiting(sink.current), []);
89
- const handlers = useMemo(() => {
90
- const letGo = () => {
91
- if (sink.current.at !== "down") return;
92
- const left = PRESS_IN_MS - (Date.now() - sink.current.since);
93
- if (left <= 0) {
94
- sink.current = RISEN;
95
- setPressedHere(false);
96
- return;
97
- }
98
- sink.current = {
99
- at: "rising",
100
- timer: window.setTimeout(() => {
101
- sink.current = AT_REST;
102
- setPressedHere(false);
103
- }, left)
104
- };
105
- };
106
- const undo = () => {
107
- if (sink.current.at !== "down") return;
108
- sink.current = AT_REST;
109
- setPressedHere(false);
110
- };
111
- const begin = whole ? () => api?.press("island") : () => {
112
- api?.press("element");
113
- stopWaiting(sink.current);
114
- sink.current = { at: "down", since: Date.now() };
115
- setPressedHere(true);
116
- };
117
- const end = whole ? () => api?.release() : () => {
118
- api?.release();
119
- letGo();
120
- };
121
- const cancel = whole ? () => api?.abandon() : () => {
122
- api?.abandon();
123
- undo();
124
- };
125
- return {
126
- onPointerDown: (event) => {
127
- if (primaryHeld(event)) begin();
128
- },
129
- onPointerUp: end,
130
- onPointerLeave: cancel,
131
- onPointerEnter: (event) => {
132
- if (primaryHeld(event)) begin();
133
- },
134
- onPointerCancel: cancel
135
- };
136
- }, [api, whole]);
137
- return whole || !pressedHere ? handlers : { ...handlers, "data-pressed": "" };
138
- }
139
-
140
- // ../checkout-core/src/domain/user-types.ts
141
- var SOLO_KEY = "default";
142
- function agreed(values) {
143
- const first = values[0];
144
- if (first === void 0) return null;
145
- return values.every((value) => value === first) ? first : null;
146
- }
147
- function groupUserTypes(rows) {
148
- const byName = /* @__PURE__ */ new Map();
149
- for (const row of rows) {
150
- if (row.Name === "") continue;
151
- const group = byName.get(row.Name);
152
- if (group === void 0) byName.set(row.Name, [row]);
153
- else group.push(row);
154
- }
155
- return [...byName.entries()].map(([name, group]) => ({
156
- key: name,
157
- name,
158
- note: agreed(group.map((row) => row.Note ?? null))
159
- }));
160
- }
161
- function partyTypes(host, fetched, asking) {
162
- if (host.length > 0) return { status: "KNOWN", types: host };
163
- if (fetched !== void 0) return { status: "KNOWN", types: fetched };
164
- return asking ? { status: "ASKING" } : { status: "KNOWN", types: [] };
165
- }
166
- function assignmentFor(product, key) {
167
- if (product.UserTypes === void 0) return key;
168
- const offered = product.UserTypes ?? [];
169
- const byName = offered.find((type) => type.Name === key);
170
- if (byName !== void 0) return byName.AssignmentKey;
171
- return offered.some((type) => type.AssignmentKey === key) ? key : void 0;
172
- }
173
- function userTypeNames(rows) {
174
- return Object.fromEntries(rows.map((row) => [row.AssignmentKey, row.Name]));
175
- }
176
-
177
- // ../checkout-core/src/domain/island-timeslots.ts
178
- function slotFullness(remaining, total) {
179
- if (!Number.isFinite(remaining) || remaining < 0) return null;
180
- if (remaining <= 1) return remaining;
181
- if (!Number.isFinite(total) || total <= 0) return null;
182
- return Math.min(1, remaining / total);
183
- }
184
- var MAX_TIME_INPUT = 40;
185
- var WALL_CLOCK = /^(?:\d{4}-\d{2}-\d{2}[T ])?(\d{2}):(\d{2})(?::\d{2})?/;
186
- function parseWallClockTime(value) {
187
- if (typeof value !== "string" || value.length > MAX_TIME_INPUT) return null;
188
- const match = WALL_CLOCK.exec(value.trim());
189
- if (!match) return null;
190
- if (Number(match[1]) > 23 || Number(match[2]) > 59) return null;
191
- return `${match[1]}:${match[2]}`;
192
- }
193
- function timeOfDayInZone(now, timeZone) {
194
- const read = (zone) => {
195
- const parts = new Intl.DateTimeFormat("en-GB", {
196
- timeZone: zone,
197
- hour: "2-digit",
198
- minute: "2-digit",
199
- hourCycle: "h23"
200
- }).formatToParts(now);
201
- const hour = parts.find((part) => part.type === "hour")?.value ?? "00";
202
- const minute = parts.find((part) => part.type === "minute")?.value ?? "00";
203
- return `${String(Number(hour) % 24).padStart(2, "0")}:${minute}`;
204
- };
205
- try {
206
- return read(timeZone ?? "UTC");
207
- } catch {
208
- return read("UTC");
209
- }
210
- }
211
- function dayInZone(now, timeZone) {
212
- const read = (zone) => new Intl.DateTimeFormat("en-CA", {
213
- timeZone: zone,
214
- year: "numeric",
215
- month: "2-digit",
216
- day: "2-digit"
217
- }).format(now);
218
- try {
219
- return read(timeZone ?? "UTC");
220
- } catch {
221
- return read("UTC");
222
- }
223
- }
224
- var PART_OF_DAY_LABELS = {
225
- OVERNIGHT: "OVERNIGHT",
226
- PRE_DAWN: "PRE-DAWN",
227
- EARLY_MORNING: "EARLY MORNING",
228
- LATE_MORNING: "LATE MORNING",
229
- EARLY_AFTERNOON: "EARLY AFTERNOON",
230
- LATE_AFTERNOON: "LATE AFTERNOON",
231
- EARLY_EVENING: "EARLY EVENING",
232
- LATE_EVENING: "LATE EVENING"
233
- };
234
- function partOfDayLabel(part) {
235
- return PART_OF_DAY_LABELS[part];
236
- }
237
- function partOfDay(time) {
238
- const hour = Number(time.slice(0, 2));
239
- if (hour < 3) return "OVERNIGHT";
240
- if (hour < 6) return "PRE_DAWN";
241
- if (hour < 9) return "EARLY_MORNING";
242
- if (hour < 12) return "LATE_MORNING";
243
- if (hour < 15) return "EARLY_AFTERNOON";
244
- if (hour < 18) return "LATE_AFTERNOON";
245
- if (hour < 21) return "EARLY_EVENING";
246
- return "LATE_EVENING";
247
- }
248
- var MINUTES_IN_DAY = 24 * 60;
249
- function minutesOfDay(time) {
250
- return Number(time.slice(0, 2)) * 60 + Number(time.slice(3, 5));
251
- }
252
- function formatSlotRange(startTime, endTime) {
253
- return endTime === null ? startTime : `${startTime} - ${endTime}`;
254
- }
255
- function formatSlotDuration(startTime, endTime) {
256
- if (endTime === null) return null;
257
- const minutes = (minutesOfDay(endTime) - minutesOfDay(startTime) + MINUTES_IN_DAY) % MINUTES_IN_DAY;
258
- if (!Number.isFinite(minutes) || minutes <= 0) return null;
259
- const hours = Math.floor(minutes / 60);
260
- const rest = minutes % 60;
261
- if (hours === 0) return `${rest}m`;
262
- return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
263
- }
264
- function withSelectedDay(selection, day) {
265
- return selection.day === day ? selection : { day, startTime: null };
266
- }
267
- function withSelectedTime(selection, startTime) {
268
- return { day: selection.day, startTime };
269
- }
270
- function hasStarted(slot, options) {
271
- if (options.selection.day < options.today) return true;
272
- if (options.selection.day > options.today) return false;
273
- return slot.startTime <= options.nowTime;
274
- }
275
- function timeslotState(slot, options) {
276
- if (hasStarted(slot, options)) return "PAST_BUT_RELEVANT";
277
- if (slot.remaining !== null && slot.remaining <= 0) return "UNAVAILABLE";
278
- return slot.startTime === options.selection.startTime ? "SELECTED" : "AVAILABLE";
279
- }
280
- function sameTimeslots(a, b) {
281
- if (a === b) return true;
282
- if (a.length !== b.length) return false;
283
- return a.every((slot, index) => {
284
- const other = b[index];
285
- return slot.startTime === other.startTime && slot.endTime === other.endTime && slot.remaining === other.remaining && slot.product === other.product;
286
- });
287
- }
288
- function buildTimeslotGroups(slots, options) {
289
- const groups = [];
290
- const chronological = [...slots].sort((a, b) => a.startTime.localeCompare(b.startTime));
291
- const cellFor = (slot) => ({
292
- slot,
293
- part: partOfDay(slot.startTime),
294
- state: timeslotState(slot, options),
295
- duration: formatSlotDuration(slot.startTime, slot.endTime)
296
- });
297
- const grouping = options.grouping ?? "PART_OF_DAY";
298
- if (grouping === "NONE") {
299
- return chronological.length === 0 ? [] : [{ key: "ALL", part: null, label: null, cells: chronological.map(cellFor) }];
300
- }
301
- const byKey = /* @__PURE__ */ new Map();
302
- const groupOf = (slot) => {
303
- if (grouping === "PRODUCT") {
304
- const product = slot.product?.trim() ?? "";
305
- return product === "" ? { key: "PRODUCT:", part: null, label: null } : { key: `PRODUCT:${product}`, part: null, label: product };
306
- }
307
- const part = partOfDay(slot.startTime);
308
- return { key: part, part, label: partOfDayLabel(part) };
309
- };
310
- for (const slot of chronological) {
311
- const head = groupOf(slot);
312
- let group = byKey.get(head.key);
313
- if (!group) {
314
- group = { ...head, cells: [] };
315
- byKey.set(head.key, group);
316
- groups.push(group);
317
- }
318
- group.cells.push(cellFor(slot));
319
- }
320
- return groups;
321
- }
322
- function timeslotRequest(day, startTime, schedule) {
323
- if (day === void 0 || startTime === void 0 || startTime === "") return void 0;
324
- const slot = schedule?.slotsByDay?.[day]?.find((candidate) => candidate.startTime === startTime);
325
- if (slot === void 0) return void 0;
326
- const ends = slot.endTime ?? slot.startTime;
327
- return { LocalStartTime: `${slot.startTime}:00`, LocalEndTime: `${ends}:00` };
328
- }
329
-
330
- // ../checkout-core/src/domain/island-calendar.ts
331
- var HIGH_FROM = 2 / 3;
332
- var MEDIUM_FROM = 1 / 3;
333
- function toAvailabilityLevel(remaining) {
334
- if (!Number.isFinite(remaining) || remaining <= 0) return null;
335
- if (remaining > HIGH_FROM) return "HIGH";
336
- if (remaining > MEDIUM_FROM) return "MEDIUM";
337
- return "LOW";
338
- }
339
- function readAvailability(remaining) {
340
- if (remaining === null) return null;
341
- const level = toAvailabilityLevel(remaining);
342
- if (level === null) return null;
343
- const percent = Math.round(Math.min(remaining, 1) * 100);
344
- return { level, announcement: `about ${percent}% availability` };
345
- }
346
- var RAMP = [
347
- [0, 0],
348
- [MEDIUM_FROM, 33],
349
- [HIGH_FROM, 67],
350
- [1, 100]
351
- ];
352
- function availabilityMix(remaining) {
353
- const flat = (stop) => ({
354
- from: stop,
355
- to: stop,
356
- towards: 100
357
- });
358
- if (remaining === null || !Number.isFinite(remaining) || remaining <= 0) return flat(0);
359
- if (remaining >= 1) return flat(100);
360
- const top = RAMP.findIndex(([at]) => remaining <= at);
361
- const [lowAt, lowStop] = RAMP[top - 1];
362
- const [highAt, highStop] = RAMP[top];
363
- return {
364
- from: lowStop,
365
- to: highStop,
366
- towards: Math.round((remaining - lowAt) / (highAt - lowAt) * 100)
367
- };
368
- }
369
- function availabilityColor(remaining) {
370
- const stop = (suffix) => `var(--scopetickets-island-availability-${suffix})`;
371
- const { from, to, towards } = availabilityMix(remaining);
372
- if (from === to) return stop(from);
373
- return `color-mix(in srgb, ${stop(to)} ${towards}%, ${stop(from)})`;
374
- }
375
- function isDatePickerCellSelectable(state) {
376
- return state === "AVAILABLE" || state === "SELECTED";
377
- }
378
- function isSelectableCalendarCell(cell) {
379
- return cell.kind !== "EMPTY" && isDatePickerCellSelectable(cell.kind);
380
- }
381
- function parseMonth(month) {
382
- return { year: Number(month.slice(0, 4)), monthIndex: Number(month.slice(5, 7)) - 1 };
383
- }
384
- function mondayFirstWeekday(date) {
385
- return (date.getUTCDay() + 6) % 7;
386
- }
387
- function toDay(year, monthIndex, dayOfMonth) {
388
- const month = String(monthIndex + 1).padStart(2, "0");
389
- return `${year}-${month}-${String(dayOfMonth).padStart(2, "0")}`;
390
- }
391
- function eventsOn(series, day) {
392
- return series.events.filter((event) => event.day === day);
393
- }
394
- function eventKeyForDay(series, day) {
395
- return series === void 0 ? void 0 : eventsOn(series, day)[0]?.eventKey;
396
- }
397
- function dateRange(series) {
398
- let first = null;
399
- let last = null;
400
- for (const event of series.events) {
401
- if (first === null || event.day < first) first = event.day;
402
- if (last === null || event.day > last) last = event.day;
403
- }
404
- return first === null || last === null ? null : { first, last };
405
- }
406
- function soonestRelevantDay(series, today) {
407
- const days = [...new Set(series.events.map((event) => event.day))].sort();
408
- return days.find((day) => day >= today) ?? days[days.length - 1] ?? null;
409
- }
410
- function classifyDay(series, day, span, today, selectedDay) {
411
- const dayOfMonth = Number(day.slice(8, 10));
412
- const events = eventsOn(series, day);
413
- const elapsed = day < today;
414
- if (events.length > 0) {
415
- if (elapsed) return { kind: "PAST_BUT_RELEVANT", day, dayOfMonth, events };
416
- if (day === selectedDay) return { kind: "SELECTED", day, dayOfMonth, events };
417
- return { kind: "AVAILABLE", day, dayOfMonth, events };
418
- }
419
- const insideSpan = span !== null && day >= span.first && day <= span.last;
420
- return insideSpan && !elapsed ? { kind: "UNAVAILABLE", day, dayOfMonth } : { kind: "OUT_OF_SERIES", day, dayOfMonth };
421
- }
422
- function addDays(day, count) {
423
- const at = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
424
- at.setUTCDate(at.getUTCDate() + count);
425
- return at.toISOString().slice(0, 10);
426
- }
427
- function startOfWeek(day) {
428
- return addDays(day, -mondayFirstWeekday(/* @__PURE__ */ new Date(`${day}T00:00:00.000Z`)));
429
- }
430
- function monthOfWeek(weekStart) {
431
- return monthOfDay(addDays(weekStart, 3));
432
- }
433
- function weeksInSeries(series) {
434
- const span = dateRange(series);
435
- if (!span) return [];
436
- const last = startOfWeek(span.last);
437
- const weeks = [];
438
- for (let week = startOfWeek(span.first); week <= last; week = addDays(week, 7)) {
439
- weeks.push(week);
440
- }
441
- return weeks;
442
- }
443
- function weeksInCalendar(series) {
444
- const span = dateRange(series);
445
- if (!span) return [];
446
- const from = parseMonth(monthOfDay(span.first));
447
- const to = parseMonth(monthOfDay(span.last));
448
- const lastOfMonth = new Date(Date.UTC(to.year, to.monthIndex + 1, 0)).getUTCDate();
449
- const first = startOfWeek(toDay(from.year, from.monthIndex, 1));
450
- const last = startOfWeek(toDay(to.year, to.monthIndex, lastOfMonth));
451
- const weeks = [];
452
- for (let week = first; week <= last; week = addDays(week, 7)) weeks.push(week);
453
- const finalMonth = monthOfDay(span.last);
454
- const finalMonthRow = monthStartRows(weeks).find(({ month }) => month === finalMonth)?.row ?? 0;
455
- while (weeks.length < finalMonthRow + CALENDAR_VIEWPORT_ROWS) {
456
- weeks.push(addDays(weeks[weeks.length - 1], 7));
457
- }
458
- return weeks;
459
- }
460
- function buildWeekRow(series, weekStart, { today, selectedDay = null }) {
461
- const span = dateRange(series);
462
- return Array.from(
463
- { length: 7 },
464
- (_unused, offset) => classifyDay(series, addDays(weekStart, offset), span, today, selectedDay)
465
- );
466
- }
467
- function buildMonthGrid(series, month, { today, selectedDay = null }) {
468
- const { year, monthIndex } = parseMonth(month);
469
- const first = new Date(Date.UTC(year, monthIndex, 1));
470
- const dayCount = new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
471
- const span = dateRange(series);
472
- const cells = [];
473
- for (let i = 0; i < mondayFirstWeekday(first); i += 1) cells.push({ kind: "EMPTY" });
474
- for (let dayOfMonth = 1; dayOfMonth <= dayCount; dayOfMonth += 1) {
475
- cells.push(classifyDay(series, toDay(year, monthIndex, dayOfMonth), span, today, selectedDay));
476
- }
477
- while (cells.length % 7 !== 0) cells.push({ kind: "EMPTY" });
478
- const weeks = [];
479
- for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
480
- return weeks;
481
- }
482
- function weekContainingDay(weeks, day) {
483
- return weeks.find((week) => week.some((cell) => cell.kind !== "EMPTY" && cell.day === day)) ?? null;
484
- }
485
- function locateDayInMonthStack(series, day, { today }) {
486
- const months = monthsInSeries(series);
487
- const monthIndex = months.indexOf(monthOfDay(day));
488
- if (monthIndex < 0) return null;
489
- const weeks = buildMonthGrid(series, months[monthIndex] ?? day.slice(0, 7), { today });
490
- const weekIndex = weeks.findIndex(
491
- (week) => week.some((cell) => cell.kind !== "EMPTY" && cell.day === day)
492
- );
493
- if (weekIndex < 0) return null;
494
- return { monthIndex, weekIndex };
495
- }
496
- function monthOfDay(day) {
497
- return day.slice(0, 7);
498
- }
499
- function monthsInSeries(series) {
500
- const months = [];
501
- for (const event of series.events) {
502
- const month = monthOfDay(event.day);
503
- if (!months.includes(month)) months.push(month);
504
- }
505
- return months.sort();
506
- }
507
- function openingMonth(series, today) {
508
- const day = soonestRelevantDay(series, today);
509
- if (day) return monthOfDay(day);
510
- return monthsInSeries(series)[0] ?? null;
511
- }
512
- function stepMonth(series, month, step) {
513
- const months = monthsInSeries(series);
514
- const index = months.indexOf(month);
515
- if (index === -1) return null;
516
- return months[index + step] ?? null;
517
- }
518
- var CALENDAR_LOCALE = "en-IE";
519
- function formatMonthYear(month) {
520
- return month.slice(0, 4);
521
- }
522
- function formatMonthName(month) {
523
- const { year, monthIndex } = parseMonth(month);
524
- return new Date(Date.UTC(year, monthIndex, 1, 12)).toLocaleDateString(CALENDAR_LOCALE, {
525
- month: "long",
526
- timeZone: "UTC"
527
- });
528
- }
529
- function formatMonthNameShort(month) {
530
- const long = formatMonthName(month);
531
- const { year, monthIndex } = parseMonth(month);
532
- const short = new Date(Date.UTC(year, monthIndex, 1, 12)).toLocaleDateString(CALENDAR_LOCALE, {
533
- month: "short",
534
- timeZone: "UTC"
535
- });
536
- return short.length < long.length ? `${short}.` : long;
537
- }
538
- function formatDayDate(day) {
539
- return (/* @__PURE__ */ new Date(`${day}T12:00:00.000Z`)).toLocaleDateString(CALENDAR_LOCALE, {
540
- day: "numeric",
541
- month: "long",
542
- year: "numeric",
543
- timeZone: "UTC"
544
- });
545
- }
546
- function formatWeekdayAndDate(day) {
547
- return (/* @__PURE__ */ new Date(`${day}T12:00:00.000Z`)).toLocaleDateString(CALENDAR_LOCALE, {
548
- weekday: "long",
549
- day: "numeric",
550
- month: "long",
551
- timeZone: "UTC"
552
- });
553
- }
554
- function formatDayChip(day) {
555
- const at = /* @__PURE__ */ new Date(`${day}T12:00:00.000Z`);
556
- return {
557
- date: at.toLocaleDateString(CALENDAR_LOCALE, { day: "numeric", timeZone: "UTC" }),
558
- month: shortMonthLabel(
559
- at.toLocaleDateString(CALENDAR_LOCALE, { month: "short", timeZone: "UTC" })
560
- )
561
- };
562
- }
563
- function shortMonthLabel(abbreviation) {
564
- return abbreviation.replace(/\.$/, "").slice(0, 3).toUpperCase();
565
- }
566
- function formatDayWeekday(day) {
567
- return (/* @__PURE__ */ new Date(`${day}T12:00:00.000Z`)).toLocaleDateString(CALENDAR_LOCALE, {
568
- weekday: "long",
569
- timeZone: "UTC"
570
- });
571
- }
572
- var DATE_PICKER_ACCESSORY = "NONE";
573
- var CALENDAR_VIEWPORT_ROWS = 6;
574
- function monthStartRows(weeks) {
575
- if (weeks.length === 0) return [];
576
- const starts = [{ month: monthOfDay(weeks[0]), row: 0 }];
577
- weeks.forEach((weekStart, row) => {
578
- for (let offset = 0; offset < 7; offset += 1) {
579
- const day = addDays(weekStart, offset);
580
- if (!day.endsWith("-01")) continue;
581
- const month = monthOfDay(day);
582
- if (!starts.some((start) => start.month === month)) starts.push({ month, row });
583
- }
584
- });
585
- return starts;
586
- }
587
- function monthAtRow(starts, topRow) {
588
- let current = starts[0]?.month ?? null;
589
- for (const start of starts) {
590
- if (start.row <= topRow) current = start.month;
591
- }
592
- return current;
593
- }
594
- function lastTopRow({ rowCount, viewportRows }) {
595
- return Math.max(0, rowCount - viewportRows);
596
- }
597
- function rowAfterDrag(drag) {
598
- const { row, offset, rowHeight } = drag;
599
- if (rowHeight <= 0) return clampRow(row, drag);
600
- return clampRow(Math.round(row - offset / rowHeight), drag);
601
- }
602
- var CALENDAR_ROW_OVERSHOOT = 1;
603
- function resist(overshoot, rowHeight) {
604
- const limit = rowHeight * CALENDAR_ROW_OVERSHOOT;
605
- return limit * overshoot / (limit + overshoot);
606
- }
607
- function rowDragOffset(drag) {
608
- const { row, offset, rowHeight } = drag;
609
- if (rowHeight <= 0) return 0;
610
- const wanted = row * rowHeight - offset;
611
- const furthest = lastTopRow(drag) * rowHeight;
612
- const held = wanted < 0 ? -resist(-wanted, rowHeight) : wanted > furthest ? furthest + resist(wanted - furthest, rowHeight) : wanted;
613
- return row * rowHeight - held;
614
- }
615
- function clampRow(row, drag) {
616
- return Math.max(0, Math.min(lastTopRow(drag), row));
617
- }
618
- function rowContainingDay(weeks, day) {
619
- if (day === null || weeks.length === 0) return 0;
620
- const rows = Math.floor(daysBetween(weeks[0], day) / 7);
621
- const lastTop = Math.max(0, weeks.length - CALENDAR_VIEWPORT_ROWS);
622
- return Math.max(0, Math.min(lastTop, rows));
623
- }
624
- function monthOpeningRow(weeks, starts, day) {
625
- if (day === null || weeks.length === 0) return 0;
626
- const start = starts.find((candidate) => candidate.month === monthOfDay(day));
627
- if (start === void 0) return rowContainingDay(weeks, day);
628
- return Math.min(Math.max(0, weeks.length - CALENDAR_VIEWPORT_ROWS), start.row);
629
- }
630
- function daysBetween(from, to) {
631
- const ms = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`);
632
- return Math.round(ms / 864e5);
633
- }
634
- function toggleSelectedDay(selected, day) {
635
- return selected === day ? null : day;
636
- }
637
-
638
- // ../checkout-core/src/domain/money.ts
639
- var MONEY_LOCALE = "en-IE";
640
- function formatterFor(currency) {
641
- return new Intl.NumberFormat(MONEY_LOCALE, { style: "currency", currency });
642
- }
643
- function minorUnitDigits(formatter) {
644
- return formatter.resolvedOptions().maximumFractionDigits ?? 2;
645
- }
646
- function majorUnits(minorUnits, currency) {
647
- const digits = minorUnitDigits(formatterFor(currency));
648
- return Number((minorUnits / 10 ** digits).toFixed(digits));
649
- }
650
- function formatMoney(minorUnits, currency) {
651
- const formatter = formatterFor(currency);
652
- return formatter.format(minorUnits / 10 ** minorUnitDigits(formatter));
653
- }
654
- function moneyParts(minorUnits, currency) {
655
- const formatter = formatterFor(currency);
656
- const digits = minorUnitDigits(formatter);
657
- const plain = new Intl.NumberFormat(MONEY_LOCALE, {
658
- minimumFractionDigits: digits,
659
- maximumFractionDigits: digits
660
- });
661
- const value = minorUnits / 10 ** digits;
662
- const magnitude = Math.abs(value);
663
- const symbol = formatter.format(magnitude).replace(plain.format(magnitude), "").replace(/\s/gu, "");
664
- return { symbol, amount: plain.format(value) };
665
- }
666
- function widestAmount(amounts) {
667
- return amounts.reduce((widest, amount) => Math.max(widest, amount.length), 0);
668
- }
669
- function quoteLines(quote) {
670
- if (quote.kind === "NONE") return null;
671
- const headline = formatMoney(quote.minorUnits, quote.currency);
672
- if (quote.kind === "FROM") return { qualifier: "From", headline };
673
- if (quote.kind === "SAVING") {
674
- return { qualifier: `Save ${formatMoney(quote.savedMinorUnits, quote.currency)}`, headline };
675
- }
676
- return { qualifier: null, headline };
677
- }
678
-
679
- // src/island/PartyStepper.tsx
680
- import { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
681
- import { MinusMarkIcon, PlusMarkIcon } from "@scopetickets/icons";
682
-
683
- // ../checkout-core/src/view/component-copy.ts
684
- var FIELD_COPY = {
685
- firstName: "First Name",
686
- lastName: "Last Name",
687
- email: "Email",
688
- countryCode: "Country Code",
689
- phoneNumber: "Phone Number",
690
- confirmPassword: "Confirm Password",
691
- verificationCode: "Verification code"
692
- };
693
- var PARTY_COPY = {
694
- remove: (name) => `Remove one ${name}`,
695
- add: (name) => `Add one ${name}`,
696
- count: (count, name) => `${count} ${name}. Change the number`,
697
- field: (name) => `Number of ${name}`,
698
- /**
699
- * AND WHAT AN UNDIFFERENTIATED PARTY IS CALLED — a run selling a single UserType has no
700
- * name worth showing per row, so the one line it draws names the whole party.
701
- *
702
- * A PROP DEFAULT ON THE WEB IS INVISIBLE TO THE OTHER RENDERER, which is why this is
703
- * here: `PartyStepper`'s own `soloName = 'Guests'` could not be read from native, so
704
- * native re-typed it.
705
- */
706
- soloName: "Guests"
707
- };
708
- var ACTION_COPY = {
709
- cancel: "Cancel",
710
- confirm: "Confirm",
711
- returnToOrder: "Return to Order",
712
- payNow: "Pay Now",
713
- tryAgain: "Try Again"
714
- };
715
- var DISMISS_COPY = {
716
- back: "Back",
717
- close: "Close",
718
- /*
719
- * ASKING ABOUT LEAVING IS STILL LEAVING, as far as the button's NAME is concerned: what
720
- * a buyer presses it for is the same thing, and "Close, but we will check first" is a
721
- * sentence nobody needs read to them.
722
- */
723
- abandon: "Close"
724
- };
725
- var ISLAND_COPY = {
726
- order: "Your order",
727
- runWeeks: "Weeks of the run",
728
- inventories: "Show sessions"
729
- };
730
- var TIMESLOT_COPY = {
731
- /**
732
- * WHAT A SLOT WITH NOTHING LEFT SAYS, IN WORDS. The ring is a reading of how full a
733
- * slot is, and at zero it draws nothing — an arc of no length is an absence, not a
734
- * statement, and a buyer scanning a column for a time cannot be asked to notice an
735
- * opacity.
736
- */
737
- soldOut: "Sold Out",
738
- /**
739
- * AND WHAT QUALIFIES THE PRICE — IN THE ROW'S NAME ONLY, not on its face. A column of
740
- * forty rows each repeating the word says it forty times and the figure once. A screen
741
- * reader gets one row at a time and no column, so a bare "€17.90" beside a time is a
742
- * price with no qualifier at all.
743
- */
744
- from: "From"
745
- };
746
-
747
- // src/island/PartyStepper.tsx
748
- import { jsx, jsxs } from "react/jsx-runtime";
749
- function UserTypeRow({
750
- option,
751
- count,
752
- atLimit,
753
- onAdd,
754
- onRemove,
755
- onSet,
756
- max,
757
- onRefuse
758
- }) {
759
- return /* @__PURE__ */ jsxs("div", { className: "scopetickets-island-party-row", children: [
760
- /* @__PURE__ */ jsxs("span", { className: "scopetickets-island-party-row__text", children: [
761
- /* @__PURE__ */ jsx("span", { className: "scopetickets-island-party-row__name", children: option.name }),
762
- option.note !== null && /* @__PURE__ */ jsx("span", { className: "scopetickets-island-party-row__note", children: option.note })
763
- ] }),
764
- /* @__PURE__ */ jsx(
765
- UserTypeStepper,
766
- {
767
- name: option.name,
768
- count,
769
- atLimit,
770
- onAdd,
771
- onRemove,
772
- onSet,
773
- max,
774
- onRefuse
775
- }
776
- )
777
- ] });
778
- }
779
- function UserTypeStepper({
780
- name,
781
- count,
782
- atLimit,
783
- onAdd,
784
- onRemove,
785
- onSet,
786
- max,
787
- onRefuse
788
- }) {
789
- const chosen = count > 0;
790
- return /* @__PURE__ */ jsxs("span", { className: "scopetickets-island-stepper", "data-expanded": chosen ? "" : void 0, children: [
791
- /* @__PURE__ */ jsx(
792
- "span",
793
- {
794
- className: "scopetickets-island-stepper__opening",
795
- "aria-hidden": chosen ? void 0 : "true",
796
- children: /* @__PURE__ */ jsxs("span", { className: "scopetickets-island-stepper__opening-inner", children: [
797
- /* @__PURE__ */ jsx(
798
- StepperButton,
799
- {
800
- label: PARTY_COPY.remove(name),
801
- onPress: onRemove,
802
- kind: "remove",
803
- state: chosen ? "LIVE" : "CLOSED"
804
- }
805
- ),
806
- /* @__PURE__ */ jsx(
807
- TypedCount,
808
- {
809
- count,
810
- name,
811
- onSet,
812
- valueClassName: "scopetickets-island-stepper__value",
813
- inputClassName: "scopetickets-island-stepper__input",
814
- closed: !chosen,
815
- max,
816
- onRefuse
817
- }
818
- )
819
- ] })
820
- }
821
- ),
822
- /* @__PURE__ */ jsx(
823
- StepperButton,
824
- {
825
- label: PARTY_COPY.add(name),
826
- onPress: onAdd,
827
- kind: "add",
828
- state: atLimit ? "REFUSING" : "LIVE"
829
- }
830
- )
831
- ] });
832
- }
833
- function StepperButton({
834
- label,
835
- onPress,
836
- kind,
837
- state = "LIVE"
838
- }) {
839
- const press = useIslandPress("element");
840
- return /* @__PURE__ */ jsx(
841
- "button",
842
- {
843
- type: "button",
844
- className: "scopetickets-island-stepper__button",
845
- "data-kind": kind,
846
- "aria-label": label,
847
- "aria-disabled": state === "REFUSING" ? true : void 0,
848
- disabled: state === "CLOSED",
849
- onClick: state === "LIVE" ? onPress : void 0,
850
- ...press,
851
- children: /* @__PURE__ */ jsx("span", { className: "scopetickets-island-stepper__mark", children: kind === "add" ? /* @__PURE__ */ jsx(PlusMarkIcon, { fill: true, color: "currentColor" }) : /* @__PURE__ */ jsx(MinusMarkIcon, { fill: true, color: "currentColor" }) })
852
- }
853
- );
854
- }
855
- function SoloPartyStepper({ max, name, count, onSet, onRemove, onRefuse }) {
856
- return /* @__PURE__ */ jsxs("div", { className: "scopetickets-island-party-solo", children: [
857
- /* @__PURE__ */ jsx(
858
- StepperButton,
859
- {
860
- label: PARTY_COPY.remove(name),
861
- onPress: onRemove,
862
- kind: "remove",
863
- state: count === 0 ? "REFUSING" : "LIVE"
864
- }
865
- ),
866
- /* @__PURE__ */ jsx(
867
- TypedCount,
868
- {
869
- count,
870
- name,
871
- onSet,
872
- valueClassName: "scopetickets-island-party-solo__value",
873
- inputClassName: "scopetickets-island-party-solo__input",
874
- max,
875
- onRefuse
876
- }
877
- ),
878
- /* @__PURE__ */ jsx(
879
- StepperButton,
880
- {
881
- label: PARTY_COPY.add(name),
882
- onPress: () => onSet(count + 1),
883
- kind: "add",
884
- state: count >= max ? "REFUSING" : "LIVE"
885
- }
886
- )
887
- ] });
888
- }
889
- function TypedCount({
890
- count,
891
- name,
892
- onSet,
893
- valueClassName,
894
- inputClassName,
895
- onRefuse,
896
- closed = false,
897
- max
898
- }) {
899
- const [typing, setTyping] = useState2(null);
900
- const field = useRef2(null);
901
- const editing = typing !== null;
902
- useEffect2(() => {
903
- if (!editing) return;
904
- field.current?.focus({ preventScroll: true });
905
- }, [editing]);
906
- const commit = () => {
907
- if (typing === null) return;
908
- const asked = Number.parseInt(typing, 10);
909
- setTyping(null);
910
- if (!Number.isFinite(asked)) return;
911
- if (max !== void 0 && asked > max) {
912
- onRefuse?.(asked);
913
- return;
914
- }
915
- onRefuse?.(null);
916
- onSet(Math.max(0, asked));
917
- };
918
- if (typing === null) {
919
- return /* @__PURE__ */ jsx(
920
- "button",
921
- {
922
- type: "button",
923
- className: valueClassName,
924
- "aria-label": PARTY_COPY.count(count, name),
925
- onClick: () => setTyping(String(count)),
926
- disabled: closed,
927
- children: count
928
- }
929
- );
930
- }
931
- return /* @__PURE__ */ jsx(
932
- "input",
933
- {
934
- className: inputClassName,
935
- type: "text",
936
- inputMode: "numeric",
937
- pattern: "[0-9]*",
938
- size: 1,
939
- ref: field,
940
- "aria-label": PARTY_COPY.field(name),
941
- value: typing,
942
- onChange: (event) => setTyping(event.target.value.replace(/\D/g, "")),
943
- onBlur: commit,
944
- onKeyDown: (event) => {
945
- if (event.key === "Enter") commit();
946
- else if (event.key === "Escape") setTyping(null);
947
- else return;
948
- event.preventDefault();
949
- event.stopPropagation();
950
- }
951
- }
952
- );
953
- }
954
- function PartyStepper({
955
- userTypes,
956
- counts,
957
- onChange,
958
- max,
959
- soloName = PARTY_COPY.soloName,
960
- onRefuse,
961
- refused = null
962
- }) {
963
- const headcount = Object.values(counts).reduce((total, n2) => total + n2, 0);
964
- const refuse = (asked) => onRefuse?.(asked);
965
- const shown = (count) => refused === null ? count : refused;
966
- if (userTypes.length === 0) {
967
- return /* @__PURE__ */ jsx("div", { className: "scopetickets-island-party", "data-excess": refused === null ? void 0 : "", children: /* @__PURE__ */ jsx(
968
- SoloPartyStepper,
969
- {
970
- max,
971
- name: soloName,
972
- count: shown(headcount),
973
- onSet: (next) => {
974
- refuse(null);
975
- onChange(SOLO_KEY, next);
976
- },
977
- onRemove: () => refused === null ? onChange(SOLO_KEY, Math.max(0, headcount - 1)) : (refuse(null), onChange(SOLO_KEY, max)),
978
- onRefuse: refuse
979
- }
980
- ) });
981
- }
982
- return /* @__PURE__ */ jsx("div", { className: "scopetickets-island-party", "data-excess": refused === null ? void 0 : "", children: userTypes.map((option) => /* @__PURE__ */ jsx(
983
- UserTypeRow,
984
- {
985
- option,
986
- count: counts[option.key] ?? 0,
987
- atLimit: headcount >= max,
988
- onAdd: () => {
989
- refuse(null);
990
- onChange(option.key, (counts[option.key] ?? 0) + 1);
991
- },
992
- onRemove: () => {
993
- refuse(null);
994
- onChange(option.key, Math.max(0, (counts[option.key] ?? 0) - 1));
995
- },
996
- onSet: (next) => {
997
- refuse(null);
998
- onChange(option.key, next);
999
- },
1000
- max,
1001
- onRefuse: refuse
1002
- },
1003
- option.key
1004
- )) });
1005
- }
1006
-
1007
- // src/island/DayPicker.tsx
1008
- import { useCallback as useCallback2, useEffect as useEffect4, useMemo as useMemo2, useState as useState4 } from "react";
1009
-
1010
- // src/island/CalendarMonthHeading.tsx
1011
- import { jsx as jsx2 } from "react/jsx-runtime";
1012
- function CalendarMonthHeading({ month }) {
1013
- return /* @__PURE__ */ jsx2("h3", { className: "scopetickets-island-calendar__heading", children: formatMonthName(month) });
1014
- }
1015
-
1016
- // src/island/CalendarDayIndicator.tsx
1017
- import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
1018
- var SEGMENTS = 3;
1019
- var FILLED_SEGMENTS = {
1020
- LOW: 1,
1021
- MEDIUM: 2,
1022
- HIGH: 3
1023
- };
1024
- function CalendarDayIndicator({ level }) {
1025
- const filled = FILLED_SEGMENTS[level];
1026
- return (
1027
- // DECORATIVE, and now correctly so.
1028
- /* @__PURE__ */ jsxs2("span", { className: "scopetickets-island-day-indicator", "aria-hidden": "true", children: [
1029
- /* @__PURE__ */ jsx3(
1030
- "span",
1031
- {
1032
- className: `scopetickets-island-day-indicator__fill scopetickets-island-day-indicator__fill--${level.toLowerCase()}`,
1033
- style: { flexGrow: filled }
1034
- }
1035
- ),
1036
- filled < SEGMENTS ? /* @__PURE__ */ jsx3("span", { style: { flexGrow: SEGMENTS - filled } }) : null
1037
- ] })
1038
- );
1039
- }
1040
-
1041
- // src/island/CalendarDay.tsx
1042
- import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1043
- function CalendarDay({
1044
- cell,
1045
- accessory,
1046
- remaining,
1047
- label,
1048
- outsideMonth = false,
1049
- onSelect
1050
- }) {
1051
- const press = useIslandPress("element");
1052
- const dimmed = outsideMonth ? { "data-outside-month": "" } : null;
1053
- if (cell.kind === "EMPTY") {
1054
- return /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day", "aria-hidden": "true" });
1055
- }
1056
- if (isSelectableCalendarCell(cell)) {
1057
- return /* @__PURE__ */ jsx4(
1058
- CalendarDayButton,
1059
- {
1060
- cell,
1061
- accessory,
1062
- remaining,
1063
- label,
1064
- onSelect,
1065
- outsideMonth,
1066
- press
1067
- }
1068
- );
1069
- }
1070
- if (cell.kind === "UNAVAILABLE") {
1071
- return /* @__PURE__ */ jsx4(
1072
- CalendarDayButton,
1073
- {
1074
- cell,
1075
- accessory,
1076
- remaining: null,
1077
- label,
1078
- outsideMonth,
1079
- press
1080
- }
1081
- );
1082
- }
1083
- return /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day", ...dimmed, ...press, children: /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day__well", "data-state": cell.kind, children: /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day__number", children: cell.dayOfMonth }) }) });
1084
- }
1085
- function CalendarDayButton({
1086
- cell,
1087
- accessory,
1088
- remaining,
1089
- label,
1090
- outsideMonth = false,
1091
- press,
1092
- onSelect
1093
- }) {
1094
- const selected = cell.kind === "SELECTED";
1095
- const availability = readAvailability(remaining);
1096
- return /* @__PURE__ */ jsx4(
1097
- "button",
1098
- {
1099
- type: "button",
1100
- className: "scopetickets-island-day",
1101
- ...outsideMonth ? { "data-outside-month": "" } : null,
1102
- "aria-pressed": onSelect ? selected : void 0,
1103
- "aria-disabled": onSelect ? void 0 : true,
1104
- "aria-label": availability === null ? label : `${label}, ${availability.announcement}`,
1105
- onClick: onSelect ? () => onSelect(cell.day) : void 0,
1106
- ...press,
1107
- children: /* @__PURE__ */ jsxs3("span", { className: "scopetickets-island-day__well", "data-state": cell.kind, children: [
1108
- /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day__number", children: cell.dayOfMonth }),
1109
- cell.kind === "UNAVAILABLE" ? /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day__strike", "aria-hidden": "true" }) : null,
1110
- accessory === "LINE" && availability !== null ? /* @__PURE__ */ jsx4("span", { className: "scopetickets-island-day__accessory", children: /* @__PURE__ */ jsx4(CalendarDayIndicator, { level: availability.level }) }) : null
1111
- ] })
1112
- }
1113
- );
1114
- }
1115
-
1116
- // src/island/CalendarRunGrid.tsx
1117
- import { jsx as jsx5 } from "react/jsx-runtime";
1118
- function CalendarRunGrid({
1119
- series,
1120
- weeks,
1121
- currentMonth,
1122
- accessory,
1123
- remaining,
1124
- today,
1125
- selectedDay,
1126
- onSelectDay
1127
- }) {
1128
- return /* @__PURE__ */ jsx5("div", { className: "scopetickets-island-calendar__grid", children: weeks.map((weekStart) => (
1129
- // A presentational row: the seven columns are a layout, and announcing "row 3
1130
- // of 9" describes the grid rather than the run.
1131
- /* @__PURE__ */ jsx5("div", { className: "scopetickets-island-calendar__week", children: buildWeekRow(series, weekStart, { today, selectedDay }).map((cell, dayIndex) => /* @__PURE__ */ jsx5(
1132
- CalendarDay,
1133
- {
1134
- cell,
1135
- accessory,
1136
- remaining: cell.kind === "EMPTY" ? null : remaining?.[cell.day] ?? null,
1137
- label: cell.kind === "EMPTY" ? "" : formatDayDate(cell.day),
1138
- outsideMonth: cell.kind !== "EMPTY" && monthOfDay(cell.day) !== currentMonth,
1139
- onSelect: onSelectDay
1140
- },
1141
- cell.kind === "EMPTY" ? `empty-${dayIndex}` : cell.day
1142
- )) }, weekStart)
1143
- )) });
1144
- }
1145
-
1146
- // src/island/CalendarScroller.tsx
1147
- import {
1148
- useCallback,
1149
- useEffect as useEffect3,
1150
- useRef as useRef3,
1151
- useState as useState3
1152
- } from "react";
1153
- import { jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
1154
- var WHEEL_IDLE_MS = 200;
1155
- var CALENDAR_DRAG_SLOP = 4;
1156
- function CalendarScroller({
1157
- children,
1158
- rowCount,
1159
- row,
1160
- onRowChange,
1161
- onRowPreview,
1162
- label
1163
- }) {
1164
- const viewportRef = useRef3(null);
1165
- const trackRef = useRef3(null);
1166
- const startY = useRef3(null);
1167
- const [offset, setOffset] = useState3(0);
1168
- const [dragging, setDragging] = useState3(false);
1169
- const rowRef = useRef3(row);
1170
- rowRef.current = row;
1171
- const [rowStep, setRowStep] = useState3(0);
1172
- const gapPx = (box) => {
1173
- const gap = Number.parseFloat(
1174
- getComputedStyle(box).getPropertyValue("--scopetickets-island-day-column-gap")
1175
- );
1176
- return Number.isFinite(gap) ? gap : 0;
1177
- };
1178
- useEffect3(() => {
1179
- const track = trackRef.current;
1180
- if (!track) return void 0;
1181
- const measure = () => {
1182
- const row2 = track.querySelector(".scopetickets-island-calendar__week");
1183
- if (!row2) return;
1184
- const height = row2.getBoundingClientRect().height;
1185
- if (height <= 0) return;
1186
- const step = height + gapPx(track);
1187
- setRowStep((was) => Math.abs(was - step) < 0.5 ? was : step);
1188
- };
1189
- measure();
1190
- if (typeof ResizeObserver === "undefined") return void 0;
1191
- const observer = new ResizeObserver(measure);
1192
- observer.observe(track);
1193
- return () => observer.disconnect();
1194
- }, [rowCount]);
1195
- const rowHeight = useCallback(() => {
1196
- if (rowStep > 0) return rowStep;
1197
- const box = viewportRef.current;
1198
- if (!box) return 0;
1199
- return (box.clientHeight + gapPx(box)) / CALENDAR_VIEWPORT_ROWS;
1200
- }, [rowStep]);
1201
- const drag = useCallback(
1202
- (dy) => ({
1203
- row: rowRef.current,
1204
- rowCount,
1205
- viewportRows: CALENDAR_VIEWPORT_ROWS,
1206
- offset: dy,
1207
- rowHeight: rowHeight()
1208
- }),
1209
- [rowCount, rowHeight]
1210
- );
1211
- const draw = useCallback(
1212
- (dy) => {
1213
- const moving = drag(dy);
1214
- setOffset(rowDragOffset(moving));
1215
- onRowPreview?.(rowAfterDrag(moving));
1216
- },
1217
- [drag, onRowPreview]
1218
- );
1219
- const settle = useCallback(
1220
- (dy) => {
1221
- setOffset(0);
1222
- const landed = rowAfterDrag(drag(dy));
1223
- if (landed !== rowRef.current) onRowChange(landed);
1224
- },
1225
- [drag, onRowChange]
1226
- );
1227
- const dragged = useRef3(false);
1228
- const onPointerDown = (event) => {
1229
- if ((event.buttons & 1) !== 1) return;
1230
- startY.current = event.clientY;
1231
- dragged.current = false;
1232
- };
1233
- const onPointerMove = (event) => {
1234
- if (startY.current === null) return;
1235
- const dy = event.clientY - startY.current;
1236
- if (!dragged.current) {
1237
- if (Math.abs(dy) < CALENDAR_DRAG_SLOP) return;
1238
- dragged.current = true;
1239
- setDragging(true);
1240
- event.currentTarget.setPointerCapture(event.pointerId);
1241
- }
1242
- draw(dy);
1243
- };
1244
- const onPointerUp = (event) => {
1245
- if (startY.current === null) return;
1246
- const dy = event.clientY - startY.current;
1247
- startY.current = null;
1248
- if (!dragged.current) return;
1249
- setDragging(false);
1250
- settle(dy);
1251
- };
1252
- const onClickCapture = (event) => {
1253
- if (!dragged.current) return;
1254
- dragged.current = false;
1255
- event.stopPropagation();
1256
- event.preventDefault();
1257
- };
1258
- const onPointerCancel = () => {
1259
- startY.current = null;
1260
- dragged.current = false;
1261
- setDragging(false);
1262
- setOffset(0);
1263
- };
1264
- const wheel = useRef3(0);
1265
- const settleTimer = useRef3(null);
1266
- useEffect3(() => {
1267
- const viewport = viewportRef.current;
1268
- if (!viewport) return void 0;
1269
- const onWheel = (event) => {
1270
- event.preventDefault();
1271
- wheel.current -= event.deltaY;
1272
- wheel.current = rowDragOffset(drag(wheel.current));
1273
- draw(wheel.current);
1274
- if (settleTimer.current !== null) window.clearTimeout(settleTimer.current);
1275
- settleTimer.current = window.setTimeout(() => {
1276
- settleTimer.current = null;
1277
- const travelled = wheel.current;
1278
- wheel.current = 0;
1279
- settle(travelled);
1280
- }, WHEEL_IDLE_MS);
1281
- };
1282
- viewport.addEventListener("wheel", onWheel, { passive: false });
1283
- return () => viewport.removeEventListener("wheel", onWheel);
1284
- }, [drag, draw, settle]);
1285
- useEffect3(
1286
- () => () => {
1287
- if (settleTimer.current !== null) window.clearTimeout(settleTimer.current);
1288
- },
1289
- []
1290
- );
1291
- return /* @__PURE__ */ jsxs4(
1292
- "div",
1293
- {
1294
- ref: viewportRef,
1295
- className: "scopetickets-island-calendar-scroller",
1296
- role: "group",
1297
- "aria-label": label,
1298
- style: {
1299
- "--scopetickets-island-viewport-rows": CALENDAR_VIEWPORT_ROWS,
1300
- ...rowStep > 0 ? { "--scopetickets-island-calendar-row-step": `${rowStep}px` } : null
1301
- },
1302
- onPointerDown,
1303
- onPointerMove,
1304
- onPointerUp,
1305
- onPointerCancel,
1306
- onClickCapture,
1307
- children: [
1308
- /* @__PURE__ */ jsx6("div", { className: "scopetickets-island-calendar-scroller__window", "aria-hidden": "true" }),
1309
- /* @__PURE__ */ jsx6(
1310
- "div",
1311
- {
1312
- ref: trackRef,
1313
- className: "scopetickets-island-calendar-scroller__track",
1314
- "data-dragging": dragging || offset !== 0 ? "" : void 0,
1315
- style: {
1316
- translate: `0 calc(${-row} * var(--scopetickets-island-calendar-row-step) + ${offset}px)`
1317
- },
1318
- children
1319
- }
1320
- )
1321
- ]
1322
- }
1323
- );
1324
- }
1325
-
1326
- // src/island/CalendarWeekdayNames.tsx
1327
- import { jsx as jsx7 } from "react/jsx-runtime";
1328
- var WEEKDAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
1329
- function CalendarWeekdayNames() {
1330
- return (
1331
- // `aria-hidden`, and it is not a shortcut.
1332
- /* @__PURE__ */ jsx7("div", { className: "scopetickets-island-calendar__weekdays", "aria-hidden": "true", children: WEEKDAY_NAMES.map((name) => /* @__PURE__ */ jsx7("span", { className: "scopetickets-island-calendar__weekday", children: name }, name)) })
1333
- );
1334
- }
1335
-
1336
- // src/island/DayPicker.tsx
1337
- import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
1338
- function DayPicker({
1339
- series,
1340
- offered = series,
1341
- today,
1342
- selectedDay,
1343
- onSelectDay,
1344
- remaining,
1345
- accessory = DATE_PICKER_ACCESSORY,
1346
- onVisibleMonthChange
1347
- }) {
1348
- const weeks = useMemo2(() => weeksInCalendar(series), [series]);
1349
- const starts = useMemo2(() => monthStartRows(weeks), [weeks]);
1350
- const [row, setRow] = useState4(
1351
- () => monthOpeningRow(weeks, starts, selectedDay ?? soonestRelevantDay(offered, today))
1352
- );
1353
- const [shownRow, setShownRow] = useState4(row);
1354
- const currentMonth = monthAtRow(starts, shownRow);
1355
- useEffect4(() => {
1356
- if (currentMonth !== null) onVisibleMonthChange?.(currentMonth);
1357
- }, [currentMonth, onVisibleMonthChange]);
1358
- const selectDay = useCallback2(
1359
- (day) => {
1360
- const month = monthOfDay(day);
1361
- const start = starts.find((candidate) => candidate.month === month);
1362
- if (start !== void 0 && month !== currentMonth) {
1363
- setRow(start.row);
1364
- setShownRow(start.row);
1365
- }
1366
- onSelectDay(day);
1367
- },
1368
- [starts, currentMonth, onSelectDay]
1369
- );
1370
- if (weeks.length === 0) return null;
1371
- return /* @__PURE__ */ jsxs5("div", { className: "scopetickets-island-calendar", "data-accessory": accessory, children: [
1372
- currentMonth !== null && /* @__PURE__ */ jsx8(CalendarMonthHeading, { month: currentMonth }),
1373
- /* @__PURE__ */ jsx8(CalendarWeekdayNames, {}),
1374
- /* @__PURE__ */ jsx8(
1375
- CalendarScroller,
1376
- {
1377
- rowCount: weeks.length,
1378
- row,
1379
- onRowChange: setRow,
1380
- onRowPreview: setShownRow,
1381
- label: ISLAND_COPY.runWeeks,
1382
- children: /* @__PURE__ */ jsx8(
1383
- CalendarRunGrid,
1384
- {
1385
- series: offered,
1386
- weeks,
1387
- currentMonth,
1388
- accessory,
1389
- remaining,
1390
- today,
1391
- selectedDay,
1392
- onSelectDay: selectDay
1393
- }
1394
- )
1395
- }
1396
- )
1397
- ] });
1398
- }
1399
-
1400
- // src/island/ContentFlag.tsx
1401
- import {
1402
- CheckInCircleFilledIcon,
1403
- ExclamationMarkInCircleFilledIcon,
1404
- XMarkInCircleFilledIcon
1405
- } from "@scopetickets/icons";
1406
-
1407
- // ../api/src/environment.ts
1408
- var ENVIRONMENT_URLS = {
1409
- sandbox: {
1410
- apiUrl: "https://testlink.scopetickets.com",
1411
- paymentHostUrl: "https://sandbox.pay.scopetickets.com",
1412
- artworkUrl: "https://cdn.scopetickets.com",
1413
- passkeyRpId: "testlink.scopetickets.com",
1414
- passkeyHostUrl: "https://passkeys.testlink.scopetickets.com"
1415
- },
1416
- production: {
1417
- apiUrl: "https://link.scopetickets.com",
1418
- paymentHostUrl: "https://pay.scopetickets.com",
1419
- artworkUrl: "https://cdn.scopetickets.com",
1420
- passkeyRpId: "link.scopetickets.com",
1421
- passkeyHostUrl: "https://passkeys.link.scopetickets.com"
1422
- },
1423
- internal: {
1424
- apiUrl: "https://testlink.scopetickets.com",
1425
- paymentHostUrl: "http://localhost:3001",
1426
- artworkUrl: "https://cdn.scopetickets.com",
1427
- /*
1428
- * `localhost` IS ITS OWN RP ID, and the one origin a browser will do WebAuthn on
1429
- * without TLS. A local host cannot borrow the staging id: `localhost` is not a
1430
- * suffix of `testlink.scopetickets.com`, so a credential made here is a local one
1431
- * and does not carry to staging.
1432
- */
1433
- passkeyRpId: "localhost",
1434
- passkeyHostUrl: "http://localhost:3002"
1435
- }
1436
- };
1437
- var MAX_HOST_URL_LENGTH = 256;
1438
- var HOST_PROTOCOLS = /* @__PURE__ */ new Set(["https:", "http:"]);
1439
- function acceptableHostUrl(value) {
1440
- if (typeof value !== "string") return null;
1441
- const text = value.trim();
1442
- if (text.length === 0 || text.length > MAX_HOST_URL_LENGTH) return null;
1443
- let url;
1444
- try {
1445
- url = new URL(text);
1446
- } catch {
1447
- return null;
1448
- }
1449
- if (!HOST_PROTOCOLS.has(url.protocol)) return null;
1450
- if (url.username !== "" || url.password !== "") return null;
1451
- if (url.search !== "" || url.hash !== "") return null;
1452
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
1453
- }
1454
- function resolveEnvironmentUrls(environment, overrides = {}) {
1455
- const defaults = ENVIRONMENT_URLS[environment];
1456
- return {
1457
- apiUrl: acceptableHostUrl(overrides.apiUrl) ?? defaults.apiUrl,
1458
- paymentHostUrl: acceptableHostUrl(overrides.paymentHostUrl) ?? defaults.paymentHostUrl,
1459
- artworkUrl: acceptableHostUrl(overrides.artworkUrl) ?? defaults.artworkUrl,
1460
- passkeyRpId: defaults.passkeyRpId,
1461
- passkeyHostUrl: acceptableHostUrl(overrides.passkeyHostUrl) ?? defaults.passkeyHostUrl
1462
- };
1463
- }
1464
-
1465
- // ../api/src/client.ts
1466
- var ApiError = class extends Error {
1467
- constructor(reason, message) {
1468
- super(message);
1469
- this.reason = reason;
1470
- this.name = "ApiError";
1471
- }
1472
- };
1473
- var ScopeClient = class {
1474
- constructor(config) {
1475
- this.sessionAuthorization = null;
1476
- this.onRefused = null;
1477
- this.config = config;
1478
- }
1479
- /**
1480
- * WHO TO TELL WHEN A SESSION IS REFUSED — the one signal a session has that it is over.
1481
- *
1482
- * `LoginResult` carries no expiry, so nothing can know a header has stopped working
1483
- * until the platform says so. This is where that arrives, and it is a callback on the
1484
- * INSTANCE rather than anything global: this library runs inside somebody else's page,
1485
- * and a handler registered anywhere a host could also reach is a handler two things
1486
- * fight over.
1487
- *
1488
- * IT FIRES ONLY WHERE A USER SESSION WAS ACTUALLY SENT. A 401 on the app key alone is
1489
- * the app being wrong about itself, not a buyer being signed out, and waking the session
1490
- * machinery for it would expire somebody who was never signed in.
1491
- */
1492
- setRefusedHandler(handler) {
1493
- this.onRefused = handler;
1494
- }
1495
- /**
1496
- * Holds the header a signed-in user's session gave us, or clears it on sign-out.
1497
- *
1498
- * Stored and sent VERBATIM, which is right: staging answers `POST /api/Auth/Login`
1499
- * with the `Bearer ` already on it. Nothing here adds a scheme, and nothing should.
1500
- */
1501
- setAuthorization(authorization) {
1502
- this.sessionAuthorization = authorization;
1503
- }
1504
- /** Whether a user session is in force, rather than the app key alone. */
1505
- hasAuthorization() {
1506
- return this.sessionAuthorization !== null;
1507
- }
1508
- /**
1509
- * WHICH IDENTITY A CALL CARRIES, and it is the CALL's, not the client's.
1510
- *
1511
- * THE APP KEY ON EVERY APP CALL, EVEN WITH A BUYER SIGNED IN. The platform's event and
1512
- * ticket reads take whatever follows `Bearer ` as the APPLICATION's key and look it up;
1513
- * a user session in its place finds no application and answers 401. It used to replace
1514
- * the app key on every call, so the moment a buyer signed in every event read failed —
1515
- * "We Could Not Load This Event" on every event, first seen on a device once the native
1516
- * island could sign somebody in before an event loaded. A session carries no app
1517
- * identity and there is no second header, so the two cannot travel together.
1518
- *
1519
- * THE SESSION ONLY WHERE THE CALL IS THE ACCOUNT'S — who the user is, their profile,
1520
- * photo, password, follows, passkey registration, and logout — and the app key there
1521
- * where nobody is signed in. No buyer-flow endpoint reads the caller at all (carts,
1522
- * transactions, attendees, payments, questionnaires, feedback), so nothing they did is
1523
- * lost by the app key.
1524
- */
1525
- getAuthHeaders(as) {
1526
- if (as === "USER" && this.sessionAuthorization !== null) {
1527
- return { Authorization: this.sessionAuthorization };
1528
- }
1529
- if (this.config.apiKey) {
1530
- return { Authorization: `Bearer ${this.config.apiKey}` };
1531
- }
1532
- return {};
1533
- }
1534
- /**
1535
- * A 401 on a call that CARRIED the session, and nothing else — see `setRefusedHandler`.
1536
- * An app call refused under the app key says nothing about the buyer; read as a session
1537
- * refusal it spent the refresh pair and signed a buyer out over an event read.
1538
- */
1539
- reportIfRefused(status, as) {
1540
- if (status === 401 && as === "USER" && this.sessionAuthorization !== null) {
1541
- this.onRefused?.();
1542
- }
1543
- }
1544
- async fetch(endpoint, options, as = "APP") {
1545
- const response = await fetch(`${this.config.apiUrl}${endpoint}`, {
1546
- ...options,
1547
- headers: {
1548
- "Content-Type": "application/json",
1549
- ...this.getAuthHeaders(as),
1550
- ...options?.headers
1551
- }
1552
- });
1553
- if (!response.ok) {
1554
- this.reportIfRefused(response.status, as);
1555
- let errorResponse;
1556
- try {
1557
- errorResponse = await response.json();
1558
- } catch (e) {
1559
- console.error("Failed to parse API error response:", e);
1560
- throw new ApiError("UnknownError", `API error: ${response.status} ${response.statusText}`);
1561
- }
1562
- throw new ApiError(errorResponse.Reason, errorResponse.Message);
1563
- }
1564
- const text = await response.text();
1565
- if (!text) {
1566
- return void 0;
1567
- }
1568
- try {
1569
- return JSON.parse(text);
1570
- } catch {
1571
- return text;
1572
- }
1573
- }
1574
- async fetchVoid(endpoint, options, as = "APP") {
1575
- const response = await fetch(`${this.config.apiUrl}${endpoint}`, {
1576
- ...options,
1577
- headers: {
1578
- "Content-Type": "application/json",
1579
- ...this.getAuthHeaders(as),
1580
- ...options?.headers
1581
- }
1582
- });
1583
- if (!response.ok) {
1584
- this.reportIfRefused(response.status, as);
1585
- let errorResponse;
1586
- try {
1587
- errorResponse = await response.json();
1588
- } catch (e) {
1589
- console.error("Failed to parse API error response:", e);
1590
- throw new ApiError("UnknownError", `API error: ${response.status} ${response.statusText}`);
1591
- }
1592
- throw new ApiError(errorResponse.Reason, errorResponse.Message);
1593
- }
1594
- }
1595
- // ===========================================================================
1596
- // v2 Events
1597
- // ===========================================================================
1598
- async getDisplayEvents(signal) {
1599
- const response = await this.fetch("/api/v2/EventSummaries", { signal });
1600
- return response.Events;
1601
- }
1602
- async getEventInfo(eventKey, read) {
1603
- return this.eventInformation("event", eventKey, read);
1604
- }
1605
- async getSeriesInfo(seriesKey, read) {
1606
- return this.eventInformation("series", seriesKey, read);
1607
- }
1608
- /**
1609
- * `EventInformation`, for a run or a single event.
1610
- *
1611
- * `inventories` NARROWS THE RUN ITSELF, and the platform does the narrowing: the events
1612
- * that sell nothing from those inventories are gone from `Events`, and the user types are
1613
- * the ones those inventories' products assign. Repeated on the wire, like
1614
- * `TicketInformation`'s — see `TicketInformationQuery.inventories`, which is the same
1615
- * parameter on the other endpoint and the reason both are ANDed rather than substituted.
1616
- */
1617
- async eventInformation(type, key, read) {
1618
- const params = new URLSearchParams({ type, key });
1619
- for (const inventory of read?.inventories ?? []) params.append("inventories", inventory);
1620
- return this.fetch(`/api/v2/EventInformation?${params}`, {
1621
- signal: read?.signal
1622
- });
1623
- }
1624
- /**
1625
- * Tickets for any number of events or whole series in one request, each row naming the
1626
- * events it sells for in `EventKeys`.
1627
- *
1628
- * THE ROUTE TO READ TICKETS FROM. `Events/{key}/Tickets` omits a timeslot at
1629
- * `Remaining: 0` rather than reporting it sold out, so a sold-out session never reaches
1630
- * the picker at all.
1631
- *
1632
- * A MISSPELT PARAMETER IS NOT REFUSED: the platform answers `200 {"Tickets":[]}`, which
1633
- * reads exactly like an event that sells nothing.
1634
- */
1635
- async getTicketInformation(query, signal) {
1636
- const params = new URLSearchParams();
1637
- for (const key of query.events ?? []) params.append("events", key);
1638
- for (const key of query.series ?? []) params.append("series", key);
1639
- for (const key of query.inventories ?? []) params.append("inventories", key);
1640
- if (query.includeTimeslots) params.set("include_timeslots", "true");
1641
- if (query.includeQuestions) params.set("include_questions", "true");
1642
- const response = await this.fetch(
1643
- `/api/v2/TicketInformation?${params}`,
1644
- { signal }
1645
- );
1646
- return response.Tickets ?? [];
1647
- }
1648
- /** @deprecated Use getTicketInformation(), which also reports sold-out timeslots */
1649
- async getEventTickets(eventKey, signal) {
1650
- const response = await this.fetch(
1651
- `/api/v2/Events/${eventKey}/Tickets?include_timeslots=true`,
1652
- { signal }
1653
- );
1654
- return response.Tickets;
1655
- }
1656
- // ===========================================================================
1657
- // v1 Events (deprecated — kept for cart/timeslot compat)
1658
- // ===========================================================================
1659
- /** @deprecated Use getDisplayEvents() or getEventInfo() instead */
1660
- async getEvents(count) {
1661
- const params = count ? `?count=${count}` : "";
1662
- return this.fetch(`/api/Events/ByOrganisationKey/${this.config.orgKey}${params}`);
1663
- }
1664
- /** @deprecated Use getEventTickets() instead */
1665
- async getTickets(eventId) {
1666
- return this.fetch(`/api/Ticket/Event/${eventId}`);
1667
- }
1668
- // ===========================================================================
1669
- // Cart
1670
- // ===========================================================================
1671
- async createCart(eventId) {
1672
- const body = typeof eventId === "string" ? { EventKey: eventId } : { EventId: eventId };
1673
- return this.fetch("/api/Cart", {
1674
- method: "POST",
1675
- body: JSON.stringify(body)
1676
- });
1677
- }
1678
- async getCart(cartKey) {
1679
- return this.fetch(`/api/Cart/${cartKey}`);
1680
- }
1681
- async addToCart(cartKey, ticketId, timeslot) {
1682
- const body = timeslot ? { Type: "ticket", ItemId: ticketId, Timeslot: timeslot } : { Type: "ticket", ItemId: ticketId };
1683
- return this.fetch(`/api/Cart/${cartKey}/Items`, {
1684
- method: "POST",
1685
- body: JSON.stringify(body)
1686
- });
1687
- }
1688
- async removeFromCart(cartKey, itemKey) {
1689
- return this.fetch(`/api/Cart/${cartKey}/Items/${itemKey}`, {
1690
- method: "DELETE"
1691
- });
1692
- }
1693
- /**
1694
- * WHETHER A CODE MAY BE USED, AND WHY NOT — the one call that answers the second half.
1695
- *
1696
- * THE `PUT` BELOW ONLY APPLIES. It refuses with an `ApiError` whose message is a
1697
- * transport failure's message, which is not a sentence about a promo code; `Reason` here
1698
- * is the platform's own words for an expired, spent or wrong-event code, and it is what
1699
- * the card shows the buyer.
1700
- *
1701
- * `event_id` IS WHAT THE WIDGET KNOWS. The endpoint also narrows by ticket, series and
1702
- * organisation; the cart carries its event and nothing else, so that is what is asked.
1703
- */
1704
- async checkPromoCode(promoCode, eventId) {
1705
- const params = new URLSearchParams({ code: promoCode, event_id: String(eventId) });
1706
- return this.fetch(`/api/PromoCode/Check?${params}`);
1707
- }
1708
- /**
1709
- * PUT A PROMO CODE ON THE CART, and take back the cart it made — `TotalAmount` already
1710
- * discounted, `DiscountAmount` saying by how much, `PromoCode` naming what did it.
1711
- *
1712
- * ONE PER CART, which is the wire's rule and not this client's: the field is a single
1713
- * string, so a second code REPLACES the first rather than stacking on it.
1714
- *
1715
- * A REFUSED CODE IS AN `ApiError` like any other refusal — expired, spent, or for a
1716
- * different event. The reason is the platform's own words; see `promoRefusal`, which is
1717
- * the only thing allowed to put them in front of a buyer.
1718
- */
1719
- async setCartPromoCode(cartKey, promoCode) {
1720
- return this.fetch(`/api/Cart/${encodeURIComponent(cartKey)}/PromoCode`, {
1721
- method: "PUT",
1722
- body: JSON.stringify({ PromoCode: promoCode })
1723
- });
1724
- }
1725
- /** Take it off again, and the cart comes back at its full price. */
1726
- async clearCartPromoCode(cartKey) {
1727
- return this.fetch(`/api/Cart/${encodeURIComponent(cartKey)}/PromoCode`, {
1728
- method: "DELETE"
1729
- });
1730
- }
1731
- /**
1732
- * `allowPartial` asks the platform to reserve what it can — see
1733
- * `BulkAddItemsRequest.AllowPartialFulfillment`. OMITTED rather than sent as `false`
1734
- * when it is not asked for: a body without it is what every caller already sends.
1735
- */
1736
- async addItemsBulk(cartKey, items, { allowPartial = false } = {}) {
1737
- const body = {
1738
- Items: items,
1739
- ...allowPartial ? { AllowPartialFulfillment: true } : {}
1740
- };
1741
- return this.fetch(`/api/v2/Carts/${cartKey}/Items`, {
1742
- method: "POST",
1743
- body: JSON.stringify(body)
1744
- });
1745
- }
1746
- // ===========================================================================
1747
- // Questionnaire
1748
- // ===========================================================================
1749
- async getQuestionnaireQuestions(eventId, signal) {
1750
- return this.fetch(`/api/Questionnaires/Events/${eventId}/Questions`, {
1751
- signal
1752
- });
1753
- }
1754
- // ── Passcodes ──────────────────────────────────────────────────────────
1755
- //
1756
- // @Zsolt — AUTH SURFACE. Transport only: these three make the calls and return what
1757
- // comes back. Which of them runs when, and what a failure means, is the account
1758
- // flow's business — see `domain/passcode.ts` in @scopetickets/checkout.
1759
- /** Sends a verification code to an address. */
1760
- async sendEmailPasscode(body) {
1761
- return this.fetch("/api/Passcodes/Email", {
1762
- method: "POST",
1763
- body: JSON.stringify(body)
1764
- });
1765
- }
1766
- /** Submits the code the buyer typed. */
1767
- async verifyPasscode(body) {
1768
- await this.fetch("/api/Passcodes/Verification", {
1769
- method: "POST",
1770
- body: JSON.stringify(body)
1771
- });
1772
- }
1773
- /**
1774
- * Reads whether a passcode has been verified.
1775
- *
1776
- * The authoritative answer, and separate from `verifyPasscode` on purpose: a code
1777
- * submitted in another tab, or on the phone the mail arrived on, is verified without
1778
- * this browser ever having posted it.
1779
- */
1780
- async getPasscodeStatus(passcodeKey) {
1781
- return this.fetch(
1782
- `/api/Passcodes/${encodeURIComponent(passcodeKey)}/Status`
1783
- );
1784
- }
1785
- async submitQuestionnaireResponses(cartKey, body) {
1786
- return this.fetch(`/api/Cart/${cartKey}/Questionnaires/Responses`, {
1787
- method: "POST",
1788
- body: JSON.stringify(body)
1789
- });
1790
- }
1791
- async setBuyer(cartKey, buyer) {
1792
- return this.fetch(`/api/Cart/${cartKey}/Buyer`, {
1793
- method: "POST",
1794
- body: JSON.stringify(buyer)
1795
- });
1796
- }
1797
- async getBuyer(cartKey) {
1798
- return this.fetch(`/api/Cart/${cartKey}/Buyer`);
1799
- }
1800
- async deleteCart(cartKey) {
1801
- return this.fetchVoid(`/api/Cart/${cartKey}`, {
1802
- method: "DELETE"
1803
- });
1804
- }
1805
- // ===========================================================================
1806
- // Payment
1807
- // ===========================================================================
1808
- async createPaymentIntent(cartKey, options) {
1809
- const retryQuery = options?.retry ? "?retry=true" : "";
1810
- return this.fetch(`/api/Cart/${cartKey}/Payment${retryQuery}`, {
1811
- method: "POST"
1812
- });
1813
- }
1814
- async getPaymentStatus(cartKey) {
1815
- return this.fetch(`/api/Cart/${cartKey}/Payment/Status`);
1816
- }
1817
- // ===========================================================================
1818
- // Transactions
1819
- // ===========================================================================
1820
- async convertCartToTransaction(cartKey) {
1821
- return this.fetch("/api/Transactions/FromCart", {
1822
- method: "POST",
1823
- body: JSON.stringify({ CartKey: cartKey })
1824
- });
1825
- }
1826
- async getTransactionItems(transactionKey) {
1827
- return this.fetch(`/api/Transactions/${transactionKey}/Items`);
1828
- }
1829
- async getTransactionByCartKey(cartKey) {
1830
- return this.fetch(`/api/Transactions/ByKey/${cartKey}`);
1831
- }
1832
- // ===========================================================================
1833
- // Attendees
1834
- // ===========================================================================
1835
- /**
1836
- * AMENDS ATTENDEES A TRANSACTION ALREADY OWNS, and refuses everything else with
1837
- * `AttendeesNotMatchingTransaction`. It cannot create one — the v2 `setItemAttendee`
1838
- * below is what a first naming goes through.
1839
- *
1840
- * THE TRANSACTION-WIDE CALL, and `packages/sdk`'s ticket-confirmation flow still wants
1841
- * it: it amends an attendee that already exists (buyer-as-holder on a portal-style
1842
- * purchase) and declines politely where none does. New code should prefer the
1843
- * key-addressed call, which needs no id read first and cannot erase anybody by omission.
1844
- */
1845
- async saveAttendees(transactionKey, attendees) {
1846
- return this.fetch(`/api/Transactions/${transactionKey}/Attendees`, {
1847
- method: "PUT",
1848
- body: JSON.stringify(attendees)
1849
- });
1850
- }
1851
- /**
1852
- * WHO A TICKET IS FOR — creating the attendee where there is none and rebinding the
1853
- * ticket where there is, addressed by keys on both counts.
1854
- *
1855
- * The route takes the TRANSACTION's key and the ITEM's — the same value the bulk add
1856
- * returned as `item_key` and the booking reads as `AttendeeTicketKey` — so there is no
1857
- * attendee id to have read first and nothing integer-shaped on the wire. The platform
1858
- * scopes the item to the transaction and refuses a pair that does not match with
1859
- * `ItemNotFound`.
1860
- *
1861
- * Answers `204`-shaped success with no body: the call either went or it did not, and the
1862
- * name it saved is read back on the next booking read rather than off the response.
1863
- */
1864
- async setItemAttendee(transactionKey, itemKey, body) {
1865
- await this.fetchVoid(`/api/v2/Transactions/${transactionKey}/Items/${itemKey}/Attendee`, {
1866
- method: "PUT",
1867
- body: JSON.stringify(body)
1868
- });
1869
- }
1870
- // ===========================================================================
1871
- // Accounts
1872
- // ===========================================================================
1873
- //
1874
- // Transport only: these make the calls and return what comes back. WHICH of them runs
1875
- // when, and what a failure means, is the account flow's business — see `domain/auth.ts`
1876
- // and `domain/account-creation.ts` in @scopetickets/checkout.
1877
- /**
1878
- * Makes an account, and signs into it.
1879
- *
1880
- * `LoginUser` defaults to `true` here and is omitted from the type's own default,
1881
- * because every caller in this workspace wants the session: an account created without
1882
- * one leaves the buyer holding credentials they would then have to spend immediately.
1883
- */
1884
- async createAccount(body) {
1885
- return this.fetch("/api/Users", {
1886
- method: "POST",
1887
- body: JSON.stringify({ LoginUser: true, ...body })
1888
- });
1889
- }
1890
- /** An address and a password. */
1891
- async signIn(body) {
1892
- return this.fetch("/api/Auth/Login", {
1893
- method: "POST",
1894
- body: JSON.stringify(body)
1895
- });
1896
- }
1897
- /** Ends the session at the platform. The caller still has to forget its own copy. */
1898
- async signOut() {
1899
- return this.fetch("/api/Auth/Logout", void 0, "USER");
1900
- }
1901
- /**
1902
- * A fresh `Authorization` for a session that still holds its refresh token.
1903
- *
1904
- * The answer carries no new refresh token, so the one held is spent again rather than
1905
- * rotated.
1906
- */
1907
- async refreshAuthorization(body) {
1908
- return this.fetch("/api/Auth/Tokens", {
1909
- method: "POST",
1910
- body: JSON.stringify(body)
1911
- });
1912
- }
1913
- /**
1914
- * WHO THE SESSION BELONGS TO. The one call that turns a header into a person: every
1915
- * door into an account answers with a `LoginResult` carrying no name, no address and no
1916
- * key, so this is what the flow asks immediately after one opens.
1917
- *
1918
- * IT NEEDS A USER SESSION, not merely the app key. Measured against staging: with no
1919
- * `Authorization` at all it answers `401 NotAuthorized`, and with the app key alone it
1920
- * answers `500` — so `hasAuthorization` gates the call rather than the answer being
1921
- * read for which of the two happened.
1922
- */
1923
- async getCurrentUser(signal) {
1924
- return this.fetch("/api/Users/Me", { signal }, "USER");
1925
- }
1926
- /** The signed-in user's own details. */
1927
- async updateUser(body) {
1928
- return this.fetchVoid("/api/Users", { method: "PUT", body: JSON.stringify(body) }, "USER");
1929
- }
1930
- /** Changes the password of the signed-in user, who therefore knows the old one. */
1931
- async updatePassword(body) {
1932
- return this.fetchVoid(
1933
- "/api/Users/Password",
1934
- { method: "PUT", body: JSON.stringify(body) },
1935
- "USER"
1936
- );
1937
- }
1938
- /** Starts recovery for somebody who cannot sign in. Needs no session, by definition. */
1939
- async requestPasswordReset(body) {
1940
- return this.fetchVoid("/api/Users/PasswordReset", {
1941
- method: "POST",
1942
- body: JSON.stringify(body)
1943
- });
1944
- }
1945
- /** Sets the signed-in user's photo. Needs the session, so it runs after creation. */
1946
- async updatePhoto(body) {
1947
- return this.fetchVoid(
1948
- "/api/Users/Photo",
1949
- { method: "PUT", body: JSON.stringify(body) },
1950
- "USER"
1951
- );
1952
- }
1953
- // ===========================================================================
1954
- // Following
1955
- // ===========================================================================
1956
- async getFollowing(userKey, signal) {
1957
- return this.fetch(
1958
- `/api/Users/${encodeURIComponent(userKey)}/Following`,
1959
- {
1960
- signal
1961
- },
1962
- "USER"
1963
- );
1964
- }
1965
- async followOrganisation(userKey, body) {
1966
- return this.fetchVoid(
1967
- `/api/Users/${encodeURIComponent(userKey)}/Following/Organisation`,
1968
- {
1969
- method: "POST",
1970
- body: JSON.stringify(body)
1971
- },
1972
- "USER"
1973
- );
1974
- }
1975
- async unfollowOrganisation(userKey, organisationKey) {
1976
- return this.fetchVoid(
1977
- `/api/Users/${encodeURIComponent(userKey)}/Following/Organisation/${encodeURIComponent(organisationKey)}`,
1978
- { method: "DELETE" },
1979
- "USER"
1980
- );
1981
- }
1982
- async followVenue(userKey, body) {
1983
- return this.fetchVoid(
1984
- `/api/Users/${encodeURIComponent(userKey)}/Following/Venue`,
1985
- {
1986
- method: "POST",
1987
- body: JSON.stringify(body)
1988
- },
1989
- "USER"
1990
- );
1991
- }
1992
- async unfollowVenue(userKey, venueKey) {
1993
- return this.fetchVoid(
1994
- `/api/Users/${encodeURIComponent(userKey)}/Following/Venue/${encodeURIComponent(venueKey)}`,
1995
- { method: "DELETE" },
1996
- "USER"
1997
- );
1998
- }
1999
- // ===========================================================================
2000
- // Passkeys
2001
- // ===========================================================================
2002
- //
2003
- // Four calls and no ceremony. The browser half cannot run in a page a customer serves —
2004
- // see `packages/passkey-host` — so these hand challenges out and take credentials back,
2005
- // and something on a Scope origin does the part in between.
2006
- /** Opens a registration. Names nobody: the user comes from the session. */
2007
- async createPasskeyRegistrationChallenge(body) {
2008
- return this.fetch(
2009
- "/api/Passkeys/Registrations/Challenges",
2010
- {
2011
- method: "POST",
2012
- body: JSON.stringify(body)
2013
- },
2014
- "USER"
2015
- );
2016
- }
2017
- /** Lodges the credential the device made. */
2018
- async registerPasskey(body) {
2019
- return this.fetchVoid(
2020
- "/api/Passkeys/Registrations",
2021
- {
2022
- method: "POST",
2023
- body: JSON.stringify(body)
2024
- },
2025
- "USER"
2026
- );
2027
- }
2028
- /** Opens a sign-in. Needs no session — proving who you are is the point of it. */
2029
- async createPasskeyAuthenticationChallenge(body) {
2030
- return this.fetch("/api/Passkeys/Authentications/Challenges", {
2031
- method: "POST",
2032
- body: JSON.stringify(body)
2033
- });
2034
- }
2035
- /** Spends the assertion, and opens a session with it. */
2036
- async authenticateWithPasskey(body) {
2037
- return this.fetch("/api/Passkeys/Authentications", {
2038
- method: "POST",
2039
- body: JSON.stringify(body)
2040
- });
2041
- }
2042
- // ===========================================================================
2043
- // Feedback
2044
- // ===========================================================================
2045
- /**
2046
- * How the buyer rated a ticket. Answers 200 and nothing else, so there is no receipt
2047
- * to hold on to — the call either went or it did not.
2048
- */
2049
- async submitFeedback(body) {
2050
- return this.fetchVoid("/api/Feedback", { method: "POST", body: JSON.stringify(body) });
2051
- }
2052
- // ===========================================================================
2053
- // Utilities
2054
- // ===========================================================================
2055
- /**
2056
- * SEND ONE TICKET TO AN ADDRESS — the platform's own email, to whoever the buyer names.
2057
- *
2058
- * `template` IS OMITTED ON PURPOSE. The parameter takes a free string, the spec documents
2059
- * no values for it and nothing else in the API names one; left off, the platform sends
2060
- * its default. Conall, 2026-09-13.
2061
- *
2062
- * IT IS A `GET` THAT SENDS MAIL, which is the platform's shape and not a choice made
2063
- * here. A `GET` is the one method browsers, proxies, prefetchers and generic retry layers
2064
- * treat as free to repeat, so at-most-once cannot be delegated to any of them: every
2065
- * caller has to fire this from one deliberate press and never from anything that can
2066
- * re-run. See `sendTicket` in the booking gateway, which is the only caller.
2067
- */
2068
- async sendTicketEmail(attendeeTicketId, email) {
2069
- const params = new URLSearchParams({
2070
- email,
2071
- attendee_ticket_id: String(attendeeTicketId)
2072
- });
2073
- await this.fetch(`/api/AttendeeTicket/SendSingleEmail?${params}`);
2074
- }
2075
- /**
2076
- * WHERE A TICKET'S APPLE WALLET PASS IS SERVED — a URL, not a fetch.
2077
- *
2078
- * THE BROWSER HAS TO NAVIGATE TO IT. Safari only offers a pass to Wallet when it arrives
2079
- * as a download with Apple's media type, so there is nothing here to read and hand on: a
2080
- * pass fetched into script and re-served from a `blob:` is not reliably offered on iOS.
2081
- * It is the same link the platform's own ticket emails carry, and it needs no
2082
- * authorization, which is why none is attached.
2083
- */
2084
- applePassUrl(attendeeTicketKey) {
2085
- const params = new URLSearchParams({ attendee_ticket_key: attendeeTicketKey });
2086
- return `${this.config.apiUrl}/api/Wallet/ApplePass?${params}`;
2087
- }
2088
- async getQrCode(content, foreground = "000000", background = "FFFFFF") {
2089
- const params = new URLSearchParams({
2090
- content,
2091
- foreground,
2092
- background,
2093
- drawQuietZone: "false"
2094
- });
2095
- return this.fetch(`/api/Utils/GetQrCodeAsSVG?${params}`);
2096
- }
2097
- };
2098
-
2099
- // ../api/src/payment-protocol/parent.ts
2100
- var CARRIED_CHECKOUT_PARAMS = ["event", "eventKey"];
2101
- function buildFrameUrl(hostUrl, cartKey, identity, options) {
2102
- const url = new URL(`/checkout/${cartKey}`, hostUrl);
2103
- url.searchParams.set("method", identity.method);
2104
- url.searchParams.set("instanceId", identity.instanceId);
2105
- if (options.checkoutSessionId !== void 0)
2106
- url.searchParams.set("checkoutSessionId", options.checkoutSessionId);
2107
- url.searchParams.set("displayMode", "prewarm");
2108
- url.searchParams.set("origin", options.parentOrigin);
2109
- if (options.debug === true) url.searchParams.set("scopePaymentDebug", "1");
2110
- if (options.retry === true) url.searchParams.set("paymentRetry", "1");
2111
- for (const name of options.carriedParams ?? []) {
2112
- const value = options.parentSearchParams?.get(name);
2113
- if (value) url.searchParams.set(name, value);
2114
- }
2115
- return url.toString();
2116
- }
2117
- function allowedFrameOrigin(hostUrl) {
2118
- try {
2119
- return new URL(hostUrl).origin;
2120
- } catch {
2121
- return hostUrl;
2122
- }
2123
- }
2124
- var PAYMENT_DIAGNOSTIC_EVENTS = /* @__PURE__ */ new Set([
2125
- "revolut.provider_init_started",
2126
- "revolut.provider_init_finished",
2127
- "revolut.provider_init_failed",
2128
- "revolut.button_pressed",
2129
- "revolut.create_order_callback_started",
2130
- "revolut.create_order_callback_returned",
2131
- "revolut.inline_journey_detected",
2132
- "revolut.external_handoff_detected",
2133
- "revolut.detector_state"
2134
- ]);
2135
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2136
- function parsePaymentDiagnostic(value) {
2137
- if (!isPlainObject(value)) return null;
2138
- const payload = value;
2139
- if (typeof payload.event !== "string" || !PAYMENT_DIAGNOSTIC_EVENTS.has(payload.event))
2140
- return null;
2141
- const sourceData = isPlainObject(payload.data) ? payload.data : void 0;
2142
- const data = {};
2143
- if (sourceData?.paymentHostClass === "local_tunnel" || sourceData?.paymentHostClass === "other") {
2144
- data.paymentHostClass = sourceData.paymentHostClass;
2145
- }
2146
- if (typeof sourceData?.active === "boolean") data.active = sourceData.active;
2147
- if (typeof sourceData?.tokenPresent === "boolean") data.tokenPresent = sourceData.tokenPresent;
2148
- if (typeof sourceData?.errorType === "string" && /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(sourceData.errorType)) {
2149
- data.errorType = sourceData.errorType;
2150
- }
2151
- if (sourceData?.evidence === "provider_frame_loaded" || sourceData?.evidence === "provider_frame_replaced" || sourceData?.evidence === "mobile_inline_provisional") {
2152
- data.evidence = sourceData.evidence;
2153
- }
2154
- if (typeof sourceData?.generation === "number" && Number.isSafeInteger(sourceData.generation)) {
2155
- data.generation = sourceData.generation;
2156
- }
2157
- if (typeof sourceData?.mobile === "boolean") data.mobile = sourceData.mobile;
2158
- if (typeof sourceData?.visible === "boolean") data.visible = sourceData.visible;
2159
- if (sourceData?.state === "initialized" || sourceData?.state === "attempt_started" || sourceData?.state === "order_returned" || sourceData?.state === "inline_provisional" || sourceData?.state === "external_handoff" || sourceData?.state === "disconnected") {
2160
- data.state = sourceData.state;
2161
- }
2162
- if (sourceData?.reason === "not_mobile" || sourceData?.reason === "no_attempt" || sourceData?.reason === "terminal" || sourceData?.reason === "external_handoff" || sourceData?.reason === "hidden") {
2163
- data.reason = sourceData.reason;
2164
- }
2165
- return { event: payload.event, ...Object.keys(data).length > 0 ? { data } : {} };
2166
- }
2167
- function parsePaymentPresentation(value, expectedInstanceId, latestGeneration) {
2168
- if (!isPlainObject(value)) return null;
2169
- const payload = value;
2170
- if (payload.instanceId !== expectedInstanceId || payload.method !== "revolut_pay" || payload.mode !== "inline_provisional" && payload.mode !== "external_handoff" || typeof payload.attemptGeneration !== "number" || !Number.isSafeInteger(payload.attemptGeneration) || payload.attemptGeneration <= 0 || payload.attemptGeneration < latestGeneration) {
2171
- return null;
2172
- }
2173
- return {
2174
- instanceId: payload.instanceId,
2175
- method: payload.method,
2176
- mode: payload.mode,
2177
- attemptGeneration: payload.attemptGeneration
2178
- };
2179
- }
2180
- function parseFrameEvent(event, expected) {
2181
- if (expected.source == null || event.origin !== expected.allowedOrigin || event.source !== expected.source || !isPlainObject(event.data))
2182
- return null;
2183
- const { type } = event.data;
2184
- if (typeof type !== "string" || !type.startsWith("SCOPE_PAYMENT_")) return null;
2185
- const payload = isPlainObject(event.data.payload) ? event.data.payload : {};
2186
- if (payload.instanceId !== void 0 && payload.instanceId !== expected.identity.instanceId)
2187
- return null;
2188
- if (payload.method !== void 0 && payload.method !== expected.identity.method) return null;
2189
- const frameMessage = { type, payload };
2190
- switch (type) {
2191
- case "SCOPE_PAYMENT_READY":
2192
- case "SCOPE_PAYMENT_CONFIG_REQUESTED":
2193
- case "SCOPE_PAYMENT_CANCELLED":
2194
- case "SCOPE_PAYMENT_SUBMIT_REQUESTED":
2195
- return frameMessage;
2196
- case "SCOPE_PAYMENT_RESIZE":
2197
- if (typeof payload.height !== "number" || !Number.isFinite(payload.height)) return null;
2198
- return frameMessage;
2199
- case "SCOPE_PAYMENT_SUCCESS":
2200
- if (typeof payload.cartKey !== "string" || !payload.cartKey) return null;
2201
- return frameMessage;
2202
- case "SCOPE_PAYMENT_ERROR":
2203
- if (typeof payload.code !== "string" || typeof payload.message !== "string") return null;
2204
- return frameMessage;
2205
- case "SCOPE_PAYMENT_METHOD_STATUS":
2206
- if (typeof payload.ready !== "boolean") return null;
2207
- if (payload.wallet !== void 0 && payload.wallet !== "applePay" && payload.wallet !== "googlePay")
2208
- return null;
2209
- return frameMessage;
2210
- case "SCOPE_PAYMENT_DIAGNOSTIC": {
2211
- const diagnostic = parsePaymentDiagnostic(payload);
2212
- return diagnostic === null ? null : { type, payload: diagnostic };
2213
- }
2214
- case "SCOPE_PAYMENT_PRESENTATION": {
2215
- const presentation = parsePaymentPresentation(payload, expected.identity.instanceId, 0);
2216
- return presentation === null ? null : { type, payload: presentation };
2217
- }
2218
- default:
2219
- return null;
2220
- }
2221
- }
2222
- function buildConfigMessage(identity, config) {
2223
- return {
2224
- type: "SCOPE_PAYMENT_CONFIG",
2225
- payload: {
2226
- ...config.apiKey === void 0 ? {} : { apiKey: config.apiKey },
2227
- ...config.selectedMethod === void 0 ? {} : { selectedMethod: config.selectedMethod },
2228
- ...config.theme === void 0 ? {} : { theme: config.theme },
2229
- instanceId: identity.instanceId,
2230
- method: identity.method
2231
- }
2232
- };
2233
- }
2234
- function buildSubmitConfirmedMessage(identity, buyer) {
2235
- return {
2236
- type: "SCOPE_PAYMENT_SUBMIT_CONFIRMED",
2237
- payload: { ...buyer, instanceId: identity.instanceId, method: identity.method }
2238
- };
2239
- }
2240
- function buildSubmitRejectedMessage(identity, reason) {
2241
- return {
2242
- type: "SCOPE_PAYMENT_SUBMIT_REJECTED",
2243
- payload: { reason, instanceId: identity.instanceId, method: identity.method }
2244
- };
2245
- }
2246
- function buildTriggerSubmitMessage(identity) {
2247
- return {
2248
- type: "SCOPE_PAYMENT_TRIGGER_SUBMIT",
2249
- payload: { instanceId: identity.instanceId, method: identity.method }
2250
- };
2251
- }
2252
- function buildCancelRequestedMessage(identity) {
2253
- return {
2254
- type: "SCOPE_PAYMENT_CANCEL_REQUESTED",
2255
- payload: { instanceId: identity.instanceId, method: identity.method }
2256
- };
2257
- }
2258
-
2259
- // ../api/src/buyer.ts
2260
- var MAX_EMAIL_LENGTH = 254;
2261
- var MAX_LOCAL_LENGTH = 64;
2262
- var MAX_LABEL_LENGTH = 63;
2263
- var MAX_DOMAIN_LENGTH = 255;
2264
- var LOCAL_PART = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
2265
- var DOMAIN_LABEL = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$/;
2266
- var TOP_LEVEL_LABEL = /^[A-Za-z]{2,}$/;
2267
- function isAcceptableEmail(value) {
2268
- const email = value.trim();
2269
- if (email.length === 0 || email.length > MAX_EMAIL_LENGTH) return false;
2270
- const at = email.lastIndexOf("@");
2271
- if (at <= 0 || at === email.length - 1) return false;
2272
- const local = email.slice(0, at);
2273
- if (local.length > MAX_LOCAL_LENGTH || !LOCAL_PART.test(local)) return false;
2274
- const domain = email.slice(at + 1);
2275
- if (domain.length > MAX_DOMAIN_LENGTH) return false;
2276
- const labels = domain.split(".");
2277
- if (labels.length < 2) return false;
2278
- if (labels.some((label) => label.length > MAX_LABEL_LENGTH || !DOMAIN_LABEL.test(label))) {
2279
- return false;
2280
- }
2281
- return TOP_LEVEL_LABEL.test(labels[labels.length - 1]);
2282
- }
2283
- var E164 = /^\+[1-9]\d{1,14}$/;
2284
- function isE164(value) {
2285
- return E164.test(value.trim());
2286
- }
2287
- var CONTROL_CHARACTERS = /[\x00-\x1F\x7F]/;
2288
- function isAcceptableName(value) {
2289
- const name = value.trim();
2290
- return name.length > 0 && name.length <= 256 && !CONTROL_CHARACTERS.test(name);
2291
- }
2292
-
2293
- // ../api/src/email-typos.ts
2294
- var KNOWN_DOMAINS = [
2295
- "gmail.com",
2296
- "googlemail.com",
2297
- "icloud.com",
2298
- "me.com",
2299
- "mac.com",
2300
- "mail.com",
2301
- "hotmail.com",
2302
- "outlook.com",
2303
- "live.com",
2304
- "yahoo.com",
2305
- "aol.com",
2306
- "proton.me",
2307
- "protonmail.com",
2308
- "eircom.net"
2309
- ];
2310
- var NEAR_MISS_TARGETS = [
2311
- "gmail.com",
2312
- "googlemail.com",
2313
- "icloud.com",
2314
- "hotmail.com",
2315
- "outlook.com",
2316
- "yahoo.com",
2317
- "protonmail.com",
2318
- "eircom.net"
2319
- ];
2320
- var MIN_DISTINCTIVE_BODY = 4;
2321
- var TOP_LEVEL_SLIPS = {
2322
- co: "com",
2323
- con: "com",
2324
- cim: "com",
2325
- cmo: "com",
2326
- ocm: "com",
2327
- comm: "com",
2328
- coom: "com",
2329
- cpm: "com",
2330
- vom: "com",
2331
- xom: "com",
2332
- nte: "net",
2333
- ner: "net",
2334
- ogr: "org",
2335
- orh: "org"
2336
- };
2337
- function editDistance(a, b) {
2338
- const columns = b.length + 1;
2339
- const d = new Uint16Array((a.length + 1) * columns);
2340
- for (let j = 0; j < columns; j += 1) d[j] = j;
2341
- for (let i = 1; i <= a.length; i += 1) {
2342
- const row = i * columns;
2343
- const previous = row - columns;
2344
- d[row] = i;
2345
- for (let j = 1; j <= b.length; j += 1) {
2346
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2347
- let best = Math.min(
2348
- (d[previous + j] ?? 0) + 1,
2349
- (d[row + j - 1] ?? 0) + 1,
2350
- (d[previous + j - 1] ?? 0) + cost
2351
- );
2352
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
2353
- best = Math.min(best, (d[previous - columns + j - 2] ?? 0) + 1);
2354
- }
2355
- d[row + j] = best;
2356
- }
2357
- }
2358
- return d[a.length * columns + b.length] ?? 0;
2359
- }
2360
- function splitDomain(domain) {
2361
- const lastDot = domain.lastIndexOf(".");
2362
- if (lastDot <= 0 || lastDot === domain.length - 1) return null;
2363
- return { body: domain.slice(0, lastDot), top: domain.slice(lastDot + 1) };
2364
- }
2365
- function nearestKnownDomain(domain) {
2366
- const typed = splitDomain(domain);
2367
- if (typed === null || typed.body.length < MIN_DISTINCTIVE_BODY) return null;
2368
- for (const candidate of NEAR_MISS_TARGETS) {
2369
- const known = splitDomain(candidate);
2370
- if (known === null || known.top !== typed.top) continue;
2371
- if (known.body.length < MIN_DISTINCTIVE_BODY) continue;
2372
- if (editDistance(typed.body, known.body) === 1) return candidate;
2373
- }
2374
- return null;
2375
- }
2376
- function repairTopLevel(domain) {
2377
- const labels = domain.split(".");
2378
- if (labels.length < 2) return null;
2379
- const top = labels[labels.length - 1];
2380
- const meant = TOP_LEVEL_SLIPS[top];
2381
- if (meant === void 0) return null;
2382
- return [...labels.slice(0, -1), meant].join(".");
2383
- }
2384
- function suspectedEmailTypo(email) {
2385
- const trimmed = email.trim().toLowerCase();
2386
- const at = trimmed.lastIndexOf("@");
2387
- if (at <= 0 || at === trimmed.length - 1) return null;
2388
- const local = trimmed.slice(0, at);
2389
- const domain = trimmed.slice(at + 1);
2390
- if (KNOWN_DOMAINS.includes(domain)) return null;
2391
- const repaired = repairTopLevel(domain);
2392
- const corrected = nearestKnownDomain(repaired ?? domain) ?? repaired;
2393
- if (corrected === null || corrected === domain) return null;
2394
- return `${local}@${corrected}`;
2395
- }
2396
-
2397
- // ../checkout-core/src/domain/contact.ts
2398
- function isValidEmail(email) {
2399
- return isAcceptableEmail(email);
2400
- }
2401
- function flagTone(flag) {
2402
- return flag === "none" ? void 0 : flag;
2403
- }
2404
- function emailFlag(email) {
2405
- if (email.length === 0) return "none";
2406
- if (!isValidEmail(email)) return "error";
2407
- return suspectedEmailTypo(email) === null ? "success" : "warning";
2408
- }
2409
- function emailFlagTitle(email) {
2410
- const meant = emailFlag(email) === "warning" ? suspectedEmailTypo(email) : null;
2411
- return meant === null ? void 0 : `Did you mean ${meant}?`;
2412
- }
2413
- var E164_MAX_DIGITS = 15;
2414
- var GENERIC_NATIONAL_DIGITS = { min: 4, max: E164_MAX_DIGITS - 1 };
2415
- var COUNTRIES = [
2416
- // ── Ireland, the default, and the United Kingdom ────────────
2417
- {
2418
- code: "IE",
2419
- name: "Ireland",
2420
- dialCode: "+353",
2421
- trunkPrefix: "0",
2422
- nationalDigits: { min: 7, max: 9 },
2423
- // `08X XXX XXXX`, which is what the design draws.
2424
- grouping: [{ startsWith: ["8"], digits: 9, groups: [2, 3, 4] }]
2425
- },
2426
- {
2427
- code: "GB",
2428
- name: "United Kingdom",
2429
- dialCode: "+44",
2430
- trunkPrefix: "0",
2431
- nationalDigits: { min: 9, max: 10 },
2432
- // London is also ten digits and is grouped `020 7946 0958`, so nothing beyond the
2433
- // `7` may be assumed.
2434
- grouping: [{ startsWith: ["7"], digits: 10, groups: [4, 6] }]
2435
- },
2436
- // ── The rest of the EU, alphabetically ──────────────────────
2437
- {
2438
- code: "AT",
2439
- name: "Austria",
2440
- dialCode: "+43",
2441
- trunkPrefix: "0",
2442
- // Austria's plan is the widest in the EU — subscriber numbers run from four digits
2443
- // to thirteen.
2444
- nationalDigits: { min: 4, max: 13 },
2445
- grouping: [{ startsWith: ["6"], digits: 10, groups: [3, 7] }]
2446
- },
2447
- {
2448
- code: "BE",
2449
- name: "Belgium",
2450
- dialCode: "+32",
2451
- trunkPrefix: "0",
2452
- nationalDigits: { min: 8, max: 9 },
2453
- grouping: [{ startsWith: ["4"], digits: 9, groups: [3, 2, 2, 2] }]
2454
- },
2455
- {
2456
- code: "BG",
2457
- name: "Bulgaria",
2458
- dialCode: "+359",
2459
- trunkPrefix: "0",
2460
- nationalDigits: { min: 8, max: 9 },
2461
- grouping: [{ startsWith: ["87", "88", "89"], digits: 9, groups: [2, 3, 4] }]
2462
- },
2463
- {
2464
- code: "HR",
2465
- name: "Croatia",
2466
- dialCode: "+385",
2467
- trunkPrefix: "0",
2468
- nationalDigits: { min: 8, max: 9 },
2469
- grouping: [{ startsWith: ["9"], digits: 9, groups: [2, 3, 4] }]
2470
- },
2471
- {
2472
- code: "CY",
2473
- name: "Cyprus",
2474
- dialCode: "+357",
2475
- nationalDigits: { min: 8, max: 8 },
2476
- grouping: [{ startsWith: ["9"], digits: 8, groups: [2, 6] }]
2477
- },
2478
- {
2479
- code: "CZ",
2480
- name: "Czechia",
2481
- dialCode: "+420",
2482
- nationalDigits: { min: 9, max: 9 },
2483
- // Threes throughout, and Czechia has no trunk prefix.
2484
- grouping: [{ digits: 9, groups: [3, 3, 3] }]
2485
- },
2486
- {
2487
- code: "DK",
2488
- name: "Denmark",
2489
- dialCode: "+45",
2490
- nationalDigits: { min: 8, max: 8 },
2491
- // Every Danish number is eight digits in pairs, mobile or not — so this needs no
2492
- // prefix to disambiguate.
2493
- grouping: [{ digits: 8, groups: [2, 2, 2, 2] }]
2494
- },
2495
- {
2496
- code: "EE",
2497
- name: "Estonia",
2498
- dialCode: "+372",
2499
- nationalDigits: { min: 7, max: 8 },
2500
- grouping: [
2501
- { startsWith: ["5"], digits: 8, groups: [4, 4] },
2502
- { startsWith: ["5"], digits: 7, groups: [3, 4] }
2503
- ]
2504
- },
2505
- {
2506
- code: "FI",
2507
- name: "Finland",
2508
- dialCode: "+358",
2509
- trunkPrefix: "0",
2510
- nationalDigits: { min: 6, max: 10 },
2511
- grouping: [{ startsWith: ["4", "5"], digits: 9, groups: [2, 3, 4] }]
2512
- },
2513
- {
2514
- code: "FR",
2515
- name: "France",
2516
- dialCode: "+33",
2517
- trunkPrefix: "0",
2518
- nationalDigits: { min: 9, max: 9 },
2519
- // Pairs throughout — `06 12 34 56 78`.
2520
- grouping: [{ startsWith: ["6", "7"], digits: 9, groups: [1, 2, 2, 2, 2] }]
2521
- },
2522
- {
2523
- code: "DE",
2524
- name: "Germany",
2525
- dialCode: "+49",
2526
- trunkPrefix: "0",
2527
- nationalDigits: { min: 6, max: 11 }
2528
- // NO GROUPING, deliberately, and the one EU country without it.
2529
- },
2530
- {
2531
- code: "GR",
2532
- name: "Greece",
2533
- dialCode: "+30",
2534
- nationalDigits: { min: 10, max: 10 },
2535
- // Ten digits, no trunk prefix, and the leading digit is kept when dialling.
2536
- grouping: [{ startsWith: ["69"], digits: 10, groups: [3, 3, 4] }]
2537
- },
2538
- {
2539
- code: "HU",
2540
- name: "Hungary",
2541
- dialCode: "+36",
2542
- // `06`, and written apart from the number — see `formatNational`.
2543
- trunkPrefix: "06",
2544
- nationalDigits: { min: 8, max: 9 },
2545
- grouping: [{ startsWith: ["20", "30", "31", "50", "70"], digits: 9, groups: [2, 3, 4] }]
2546
- },
2547
- {
2548
- code: "IT",
2549
- name: "Italy",
2550
- dialCode: "+39",
2551
- // NO TRUNK PREFIX, and Italy is the exception worth knowing: the leading `0` of a
2552
- // landline is part of the number and is dialled internationally too.
2553
- nationalDigits: { min: 6, max: 11 },
2554
- grouping: [{ startsWith: ["3"], digits: 10, groups: [3, 3, 4] }]
2555
- },
2556
- {
2557
- code: "LV",
2558
- name: "Latvia",
2559
- dialCode: "+371",
2560
- nationalDigits: { min: 8, max: 8 },
2561
- grouping: [{ startsWith: ["2"], digits: 8, groups: [2, 3, 3] }]
2562
- },
2563
- {
2564
- code: "LT",
2565
- name: "Lithuania",
2566
- dialCode: "+370",
2567
- // `8`, and written apart from the number — see `formatNational`.
2568
- trunkPrefix: "8",
2569
- nationalDigits: { min: 8, max: 8 },
2570
- grouping: [{ startsWith: ["6"], digits: 8, groups: [3, 5] }]
2571
- },
2572
- {
2573
- code: "LU",
2574
- name: "Luxembourg",
2575
- dialCode: "+352",
2576
- nationalDigits: { min: 4, max: 11 },
2577
- grouping: [{ startsWith: ["6"], digits: 9, groups: [3, 3, 3] }]
2578
- },
2579
- {
2580
- code: "MT",
2581
- name: "Malta",
2582
- dialCode: "+356",
2583
- nationalDigits: { min: 8, max: 8 },
2584
- grouping: [{ startsWith: ["7", "9"], digits: 8, groups: [4, 4] }]
2585
- },
2586
- {
2587
- code: "NL",
2588
- name: "Netherlands",
2589
- dialCode: "+31",
2590
- trunkPrefix: "0",
2591
- nationalDigits: { min: 9, max: 9 },
2592
- // `06 12345678` — the mobile prefix, then the number unbroken.
2593
- grouping: [{ startsWith: ["6"], digits: 9, groups: [1, 8] }]
2594
- },
2595
- {
2596
- code: "PL",
2597
- name: "Poland",
2598
- dialCode: "+48",
2599
- // Poland dropped its trunk prefix; the nine digits are dialled as they are.
2600
- nationalDigits: { min: 9, max: 9 },
2601
- grouping: [{ digits: 9, groups: [3, 3, 3] }]
2602
- },
2603
- {
2604
- code: "PT",
2605
- name: "Portugal",
2606
- dialCode: "+351",
2607
- nationalDigits: { min: 9, max: 9 },
2608
- grouping: [{ digits: 9, groups: [3, 3, 3] }]
2609
- },
2610
- {
2611
- code: "RO",
2612
- name: "Romania",
2613
- dialCode: "+40",
2614
- trunkPrefix: "0",
2615
- nationalDigits: { min: 9, max: 9 },
2616
- grouping: [{ startsWith: ["7"], digits: 9, groups: [3, 3, 3] }]
2617
- },
2618
- {
2619
- code: "SK",
2620
- name: "Slovakia",
2621
- dialCode: "+421",
2622
- trunkPrefix: "0",
2623
- nationalDigits: { min: 9, max: 9 },
2624
- grouping: [{ startsWith: ["9"], digits: 9, groups: [3, 3, 3] }]
2625
- },
2626
- {
2627
- code: "SI",
2628
- name: "Slovenia",
2629
- dialCode: "+386",
2630
- trunkPrefix: "0",
2631
- nationalDigits: { min: 8, max: 8 },
2632
- grouping: [{ startsWith: ["3", "4", "5", "6", "7"], digits: 8, groups: [2, 3, 3] }]
2633
- },
2634
- {
2635
- code: "ES",
2636
- name: "Spain",
2637
- dialCode: "+34",
2638
- // No trunk prefix; the nine digits are the whole number.
2639
- nationalDigits: { min: 9, max: 9 },
2640
- grouping: [{ digits: 9, groups: [3, 3, 3] }]
2641
- },
2642
- {
2643
- code: "SE",
2644
- name: "Sweden",
2645
- dialCode: "+46",
2646
- trunkPrefix: "0",
2647
- nationalDigits: { min: 7, max: 9 },
2648
- grouping: [{ startsWith: ["7"], digits: 9, groups: [2, 3, 4] }]
2649
- },
2650
- /*
2651
- * Named and length-checked so a number from one of them is not read as nonsense, but
2652
- * NOT formatted: the brief is the EU and the UK, and a grouping rule written for a
2653
- * market nobody asked about is a rule nobody will check. The NANP is the exception — it
2654
- * was already here, and it is one shape throughout.
2655
- */
2656
- {
2657
- code: "US",
2658
- name: "United States",
2659
- dialCode: "+1",
2660
- nationalDigits: { min: 10, max: 10 },
2661
- grouping: [{ digits: 10, groups: [3, 3, 4] }]
2662
- },
2663
- { code: "CH", name: "Switzerland", dialCode: "+41", trunkPrefix: "0" },
2664
- { code: "NO", name: "Norway", dialCode: "+47" },
2665
- { code: "AU", name: "Australia", dialCode: "+61", trunkPrefix: "0" },
2666
- { code: "NZ", name: "New Zealand", dialCode: "+64", trunkPrefix: "0" },
2667
- { code: "ZA", name: "South Africa", dialCode: "+27", trunkPrefix: "0" },
2668
- { code: "AE", name: "United Arab Emirates", dialCode: "+971", trunkPrefix: "0" },
2669
- { code: "IN", name: "India", dialCode: "+91", trunkPrefix: "0" },
2670
- { code: "BR", name: "Brazil", dialCode: "+55", trunkPrefix: "0" }
2671
- ];
2672
- var DEFAULT_COUNTRY_CODE = "IE";
2673
- function countryByCode(code) {
2674
- const found = COUNTRIES.find((country) => country.code === code);
2675
- if (!found) throw new Error(`unknown country: ${code}`);
2676
- return found;
2677
- }
2678
- var DEFAULT_DIAL_CODE = countryByCode(DEFAULT_COUNTRY_CODE).dialCode;
2679
- var digitsOf = (value) => value.replace(/\D/g, "");
2680
- function countryByDialCode(dialCode) {
2681
- const raw = digitsOf(dialCode);
2682
- const digits = raw.startsWith("00") && raw.length > 2 ? raw.slice(2) : raw;
2683
- if (digits.length === 0) return null;
2684
- return COUNTRIES.find((country) => country.dialCode.slice(1) === digits) ?? null;
2685
- }
2686
- function splitPhoneNumber(raw) {
2687
- const trimmed = raw.trim();
2688
- const digits = digitsOf(trimmed);
2689
- const international = trimmed.startsWith("+") || digits.startsWith("00") && digits.length > 2;
2690
- if (!international || digits.length === 0) return { dialCode: null, national: trimmed };
2691
- const body = trimmed.startsWith("+") ? digits : digits.slice(2);
2692
- const match = [...COUNTRIES].sort((a, b) => b.dialCode.length - a.dialCode.length).find((country) => body.startsWith(country.dialCode.slice(1)));
2693
- if (!match) return { dialCode: null, national: trimmed };
2694
- return { dialCode: match.dialCode, national: body.slice(match.dialCode.length - 1) };
2695
- }
2696
- var MAX_DIAL_DIGITS = Math.max(...COUNTRIES.map((country) => country.dialCode.length - 1));
2697
- var NOT_PHONE = /[^\d+]/g;
2698
- function routePhoneInput(typed, field, current) {
2699
- const raw = typed.replace(NOT_PHONE, "");
2700
- const parts = splitPhoneNumber(raw);
2701
- if (field === "national") {
2702
- if (parts.dialCode === null) return { ...current, national: raw };
2703
- return { dialCode: parts.dialCode, national: parts.national };
2704
- }
2705
- if (parts.dialCode !== null) {
2706
- return {
2707
- dialCode: parts.dialCode,
2708
- /*
2709
- * A remainder long enough to BE a number takes the row below; one too short to be
2710
- * anything replaces nothing. `+3531` is a slipped keystroke after a complete code, and
2711
- * letting its `1` overwrite an entered number is the same bug in the other direction —
2712
- * so it is dropped, unless the row below is empty and there is nothing to lose.
2713
- */
2714
- national: digitsOf(parts.national).length >= GENERIC_NATIONAL_DIGITS.min || current.national.length === 0 ? parts.national : current.national
2715
- };
2716
- }
2717
- if (digitsOf(raw).length > MAX_DIAL_DIGITS) {
2718
- return { dialCode: current.dialCode, national: raw };
2719
- }
2720
- if (raw.trim().length === 0) return { ...current, dialCode: DEFAULT_DIAL_CODE };
2721
- return { ...current, dialCode: raw };
2722
- }
2723
- function nationalDigits(phone, country) {
2724
- let digits = digitsOf(phone);
2725
- const dial = country.dialCode.slice(1);
2726
- if (digits.startsWith(dial) && digits.length > dial.length) digits = digits.slice(dial.length);
2727
- const trunk = country.trunkPrefix;
2728
- if (trunk !== void 0 && digits.startsWith(trunk)) digits = digits.slice(trunk.length);
2729
- return digits;
2730
- }
2731
- function formatNational(value, country) {
2732
- const digits = digitsOf(value);
2733
- if (digits.length === 0) return value.trim() === "+" ? "+" : "";
2734
- const trunk = country.trunkPrefix !== void 0 && digits.startsWith(country.trunkPrefix) ? country.trunkPrefix : "";
2735
- const nsn = digits.slice(trunk.length);
2736
- const pattern = country.grouping?.find(
2737
- (candidate) => nsn.length <= candidate.digits && (candidate.startsWith === void 0 || candidate.startsWith.some((start) => nsn.startsWith(start)))
2738
- );
2739
- if (pattern === void 0) return value;
2740
- const parts = [];
2741
- let at = 0;
2742
- for (const size of pattern.groups) {
2743
- if (at >= nsn.length) break;
2744
- parts.push(nsn.slice(at, at + size));
2745
- at += size;
2746
- }
2747
- if (trunk === "") return parts.join(" ");
2748
- return trunk === "0" ? [trunk + (parts[0] ?? ""), ...parts.slice(1)].join(" ") : [trunk, ...parts].join(" ");
2749
- }
2750
- function digitsAllowed(country) {
2751
- return country.nationalDigits ?? GENERIC_NATIONAL_DIGITS;
2752
- }
2753
- function isValidPhone(phone, country) {
2754
- const national = nationalDigits(phone, country);
2755
- const { min, max } = digitsAllowed(country);
2756
- return national.length >= min && national.length <= max;
2757
- }
2758
- function phoneFlag(phone, country) {
2759
- if (phone.trim().length === 0) return "none";
2760
- return isValidPhone(phone, country) ? "success" : "error";
2761
- }
2762
- function e164(dialCode, phone) {
2763
- const country = countryByDialCode(dialCode);
2764
- if (country === null) return null;
2765
- const national = nationalDigits(phone, country);
2766
- if (!isValidPhone(phone, country)) return null;
2767
- const composed = `${country.dialCode}${national}`;
2768
- return isE164(composed) ? composed : null;
2769
- }
2770
- function normalizeE164(value) {
2771
- const { dialCode, national } = splitPhoneNumber(value);
2772
- if (dialCode === null) return null;
2773
- return e164(dialCode, national);
2774
- }
2775
- function isCompleteName(firstName, lastName) {
2776
- return firstName.trim().length > 0 && lastName.trim().length > 0;
2777
- }
2778
- function splitFullName(full) {
2779
- const parts = full.trim().split(/\s+/).filter(Boolean);
2780
- if (parts.length < 2) return null;
2781
- const [firstName, ...rest] = parts;
2782
- return { firstName, lastName: rest.join(" ") };
2783
- }
2784
-
2785
- // src/island/ContentFlag.tsx
2786
- import { jsx as jsx9 } from "react/jsx-runtime";
2787
- var GLYPH = {
2788
- success: CheckInCircleFilledIcon,
2789
- warning: ExclamationMarkInCircleFilledIcon,
2790
- error: XMarkInCircleFilledIcon
2791
- };
2792
- function ContentFlag({ tone, title }) {
2793
- const Glyph = GLYPH[tone];
2794
- return /* @__PURE__ */ jsx9("span", { className: `scopetickets-island-content-flag scopetickets-island-content-flag--${tone}`, children: /* @__PURE__ */ jsx9(Glyph, { fill: true, color: "currentColor", title }) });
2795
- }
2796
-
2797
- // src/island/CounterRing.tsx
2798
- import { IconGlyph } from "@scopetickets/icons";
2799
-
2800
- // ../checkout-core/src/geometry/island-timer.ts
2801
- var TIMER_GRID = 20;
2802
- var TIMER_CENTRE = TIMER_GRID / 2;
2803
- var RING_OUTER = 10;
2804
- var RING_INNER = 8;
2805
- var RING_RADIUS = (RING_OUTER + RING_INNER) / 2;
2806
- var RING_WIDTH = RING_OUTER - RING_INNER;
2807
- var TURN_DEGREES = 360;
2808
- var SOURCE_GRID = 100;
2809
- var SOURCE_OFFSET_X = 0.2;
2810
- var SOURCE_SCALE = TIMER_GRID / SOURCE_GRID;
2811
- var HAND_SOURCE = "M55.2,49.9l-.7-26c0-1-.4-2.1-1.2-2.9-1.7-1.7-4.4-1.7-6,0s-1.2,1.8-1.2,2.9l-.7,26c0,1.3.4,2.7,1.5,3.7,2,2,5.1,2,7.1,0s1.5-2.4,1.5-3.7Z";
2812
- function n(value) {
2813
- const rounded = Number(value.toFixed(3));
2814
- return String(Object.is(rounded, -0) ? 0 : rounded);
2815
- }
2816
- function pointAt(radius, degrees) {
2817
- const radians = degrees * Math.PI / 180;
2818
- return {
2819
- x: TIMER_CENTRE + radius * Math.sin(radians),
2820
- y: TIMER_CENTRE - radius * Math.cos(radians)
2821
- };
2822
- }
2823
- function circlePath(centre, radius) {
2824
- const r = `${n(radius)},${n(radius)}`;
2825
- return `M${n(centre.x - radius)},${n(centre.y)}A${r} 0 1 0 ${n(centre.x + radius)},${n(centre.y)}A${r} 0 1 0 ${n(centre.x - radius)},${n(centre.y)}Z`;
2826
- }
2827
- function clampRemaining(remaining) {
2828
- if (!Number.isFinite(remaining)) return 0;
2829
- return Math.min(1, Math.max(0, remaining));
2830
- }
2831
- function handRotation(remaining) {
2832
- return (clampRemaining(remaining) - 1) * TURN_DEGREES;
2833
- }
2834
- function transformPath(source, degrees) {
2835
- const radians = degrees * Math.PI / 180;
2836
- const cos = Math.cos(radians);
2837
- const sin = Math.sin(radians);
2838
- const linear = (x, y) => {
2839
- const sx = x * SOURCE_SCALE;
2840
- const sy = y * SOURCE_SCALE;
2841
- return { x: sx * cos - sy * sin, y: sx * sin + sy * cos };
2842
- };
2843
- const absolute = (x, y) => {
2844
- const to = linear(x - SOURCE_OFFSET_X - SOURCE_GRID / 2, y - SOURCE_GRID / 2);
2845
- return { x: TIMER_CENTRE + to.x, y: TIMER_CENTRE + to.y };
2846
- };
2847
- const pair = (p) => `${n(p.x)},${n(p.y)}`;
2848
- const segments = source.match(/[a-zA-Z][^a-zA-Z]*/g) ?? [];
2849
- return segments.map((segment) => {
2850
- const command = segment[0];
2851
- const numbers = (segment.slice(1).match(/-?(?:\d*\.\d+|\d+)/g) ?? []).map(Number);
2852
- const deltas = (stride) => {
2853
- if (numbers.length === 0 || numbers.length % stride !== 0) {
2854
- throw new Error(`path: \`${command}\` wants multiples of ${stride}`);
2855
- }
2856
- const out = [];
2857
- for (let i = 0; i < numbers.length; i += 2) {
2858
- out.push(pair(linear(numbers[i], numbers[i + 1])));
2859
- }
2860
- return command + out.join(" ");
2861
- };
2862
- switch (command) {
2863
- case "M": {
2864
- if (numbers.length !== 2) throw new Error("path: `M` wants exactly one point");
2865
- return `M${pair(absolute(numbers[0], numbers[1]))}`;
2866
- }
2867
- case "l":
2868
- return deltas(2);
2869
- case "c":
2870
- return deltas(6);
2871
- case "s":
2872
- return deltas(4);
2873
- case "Z":
2874
- case "z":
2875
- return "Z";
2876
- default:
2877
- throw new Error(`path: unsupported command \`${command}\``);
2878
- }
2879
- }).join("");
2880
- }
2881
- function annulus(outer = RING_OUTER, inner = RING_INNER) {
2882
- const centre = pointAt(0, 0);
2883
- return circlePath(centre, outer) + circlePath(centre, inner);
2884
- }
2885
- function ringSector(fraction, outer, inner, direction = "cw") {
2886
- const filled = clampRemaining(fraction);
2887
- if (filled <= 0 || filled >= 1) return null;
2888
- const mirrored = direction === "ccw";
2889
- const sweep = filled * TURN_DEGREES * (mirrored ? -1 : 1);
2890
- const capRadius = (outer - inner) / 2;
2891
- const outerStart = pointAt(outer, 0);
2892
- const outerEnd = pointAt(outer, sweep);
2893
- const innerEnd = pointAt(inner, sweep);
2894
- const innerStart = pointAt(inner, 0);
2895
- const out = mirrored ? 0 : 1;
2896
- const back = mirrored ? 1 : 0;
2897
- const large = Math.abs(sweep) > 180 ? 1 : 0;
2898
- const cap = `${n(capRadius)},${n(capRadius)}`;
2899
- const at = (p) => `${n(p.x)},${n(p.y)}`;
2900
- return {
2901
- d: `M${at(outerStart)}A${n(outer)},${n(outer)} 0 ${large} ${out} ${at(outerEnd)}A${cap} 0 0 ${out} ${at(innerEnd)}A${n(inner)},${n(inner)} 0 ${large} ${back} ${at(innerStart)}A${cap} 0 0 ${out} ${at(outerStart)}Z`
2902
- };
2903
- }
2904
- function ringAnnulus(outer, inner) {
2905
- return { d: annulus(outer, inner), evenodd: true };
2906
- }
2907
- function trackPaths() {
2908
- return [{ d: annulus(), evenodd: true }];
2909
- }
2910
- function timerPaths(remaining) {
2911
- const left = clampRemaining(remaining);
2912
- const paths = [];
2913
- if (left >= 1) paths.push(ringAnnulus(RING_OUTER, RING_INNER));
2914
- else {
2915
- const sector = ringSector(left, RING_OUTER, RING_INNER);
2916
- if (sector) paths.push(sector);
2917
- }
2918
- paths.push({ d: transformPath(HAND_SOURCE, handRotation(left)) });
2919
- return paths;
2920
- }
2921
-
2922
- // ../checkout-core/src/geometry/island-counter-ring.ts
2923
- var RING_OUTER2 = 10;
2924
- var RING_STROKE = 2.5;
2925
- var RING_INNER2 = RING_OUTER2 - RING_STROKE;
2926
- function counterTrackPaths() {
2927
- return [ringAnnulus(RING_OUTER2, RING_INNER2)];
2928
- }
2929
- function counterRingPaths(progress, direction = "cw") {
2930
- if (progress >= 1) return [ringAnnulus(RING_OUTER2, RING_INNER2)];
2931
- const sector = ringSector(progress, RING_OUTER2, RING_INNER2, direction);
2932
- return sector ? [sector] : [];
2933
- }
2934
-
2935
- // src/island/CounterRing.tsx
2936
- import { jsx as jsx10, jsxs as jsxs6 } from "react/jsx-runtime";
2937
- var LAYER = { position: "absolute", inset: 0 };
2938
- var DEFAULT_FILL = "var(--scopetickets-island-counter-ring-fill)";
2939
- var DEFAULT_TRACK = "var(--scopetickets-island-counter-ring-track)";
2940
- function CounterRing({
2941
- progress,
2942
- complete,
2943
- size = "1em",
2944
- title,
2945
- color = DEFAULT_FILL,
2946
- trackColor = DEFAULT_TRACK,
2947
- direction = "cw",
2948
- track = true
2949
- }) {
2950
- if (complete !== void 0) {
2951
- return /* @__PURE__ */ jsx10(
2952
- "span",
2953
- {
2954
- className: "scopetickets-island-counter-ring",
2955
- style: { width: size, height: size, flex: "none" },
2956
- children: /* @__PURE__ */ jsx10(ContentFlag, { tone: complete, title })
2957
- }
2958
- );
2959
- }
2960
- return /* @__PURE__ */ jsxs6(
2961
- "span",
2962
- {
2963
- className: "scopetickets-island-counter-ring",
2964
- style: { position: "relative", display: "block", width: size, height: size, flex: "none" },
2965
- children: [
2966
- track ? /* @__PURE__ */ jsx10("span", { style: LAYER, children: /* @__PURE__ */ jsx10(
2967
- IconGlyph,
2968
- {
2969
- glyph: "StepCompletionProgressRingTrack",
2970
- paths: counterTrackPaths(),
2971
- color: trackColor,
2972
- fill: true
2973
- }
2974
- ) }) : null,
2975
- /* @__PURE__ */ jsx10("span", { style: LAYER, children: /* @__PURE__ */ jsx10(
2976
- IconGlyph,
2977
- {
2978
- glyph: "StepCompletionProgressRing",
2979
- paths: counterRingPaths(progress, direction),
2980
- color,
2981
- title,
2982
- fill: true
2983
- }
2984
- ) })
2985
- ]
2986
- }
2987
- );
2988
- }
2989
-
2990
- // src/island/TimeslotPicker.tsx
2991
- import { useMemo as useMemo3 } from "react";
2992
-
2993
- // src/island/Timeslot.tsx
2994
- import { Fragment, jsx as jsx11, jsxs as jsxs7 } from "react/jsx-runtime";
2995
- var REMAINING_SIZE = "var(--scopetickets-island-space-4)";
2996
- var SELECTED_ARC = "var(--scopetickets-island-timeslot-ring-selected)";
2997
- var TRACK = "var(--scopetickets-island-timeslot-track)";
2998
- var SELECTED_TRACK = "var(--scopetickets-island-timeslot-track-selected)";
2999
- var { soldOut: SOLD_OUT, from: FROM } = TIMESLOT_COPY;
3000
- function Timeslot({ cell, accessory, onSelect }) {
3001
- if (isDatePickerCellSelectable(cell.state)) {
3002
- return /* @__PURE__ */ jsx11(TimeslotButton, { cell, accessory, onSelect });
3003
- }
3004
- return /* @__PURE__ */ jsx11(TimeslotFixed, { cell });
3005
- }
3006
- function TimeslotRow({ cell }) {
3007
- const price = slotPrice(cell);
3008
- return /* @__PURE__ */ jsxs7("span", { className: "scopetickets-island-timeslot__times", children: [
3009
- /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__time", children: cell.slot.startTime }),
3010
- cell.slot.endTime === null ? null : /* @__PURE__ */ jsxs7(Fragment, { children: [
3011
- /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__dash", "aria-hidden": "true", children: "-" }),
3012
- /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__time", children: cell.slot.endTime })
3013
- ] }),
3014
- /* @__PURE__ */ jsxs7("span", { className: "scopetickets-island-timeslot__trailing", children: [
3015
- price === null ? null : /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__price", children: price }),
3016
- cell.state === "UNAVAILABLE" ? (
3017
- /*
3018
- * THE WORDS INSTEAD OF THE MARK, AND ONLY WHERE THE MARK WOULD SAY NOTHING.
3019
- *
3020
- * `UNAVAILABLE` is the one state the ring cannot draw: `timeslotState` reaches it
3021
- * only for `remaining <= 0`, which is an arc of zero length. A slot that has
3022
- * merely BEGUN keeps its ring — it still has seats, and "Sold Out" over them
3023
- * would be false.
3024
- */
3025
- /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__soldout", children: SOLD_OUT })
3026
- ) : cell.slot.remaining === null ? null : /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__remaining", children: /* @__PURE__ */ jsx11(
3027
- CounterRing,
3028
- {
3029
- progress: cell.slot.remaining,
3030
- color: cell.state === "SELECTED" ? SELECTED_ARC : availabilityColor(cell.slot.remaining),
3031
- trackColor: cell.state === "SELECTED" ? SELECTED_TRACK : TRACK,
3032
- size: REMAINING_SIZE
3033
- }
3034
- ) })
3035
- ] })
3036
- ] });
3037
- }
3038
- function slotPrice(cell, spoken = false) {
3039
- if (!isDatePickerCellSelectable(cell.state)) return null;
3040
- const price = cell.slot.fromPrice;
3041
- if (price === void 0 || price === null) return null;
3042
- const money = formatMoney(price.minorUnits, price.currency);
3043
- return spoken ? `${FROM} ${money}` : money;
3044
- }
3045
- function timeslotLabel(cell, announcement) {
3046
- const range = cell.slot.endTime === null ? cell.slot.startTime : `${cell.slot.startTime} - ${cell.slot.endTime}`;
3047
- return [range, cell.duration, slotPrice(cell, true), announcement].filter((part) => part !== null).join(", ");
3048
- }
3049
- function TimeslotButton({ cell, accessory, onSelect }) {
3050
- const press = useIslandPress("element");
3051
- const selected = cell.state === "SELECTED";
3052
- const availability = readAvailability(cell.slot.remaining);
3053
- return /* @__PURE__ */ jsx11(
3054
- "button",
3055
- {
3056
- type: "button",
3057
- className: "scopetickets-island-timeslot",
3058
- "aria-pressed": selected,
3059
- "aria-label": timeslotLabel(cell, availability?.announcement ?? null),
3060
- onClick: () => onSelect(cell.slot.startTime),
3061
- ...press,
3062
- children: /* @__PURE__ */ jsxs7("span", { className: "scopetickets-island-timeslot__pill", "data-state": cell.state, children: [
3063
- /* @__PURE__ */ jsx11(TimeslotRow, { cell }),
3064
- accessory === "LINE" && availability !== null ? /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__accessory", children: /* @__PURE__ */ jsx11(CalendarDayIndicator, { level: availability.level }) }) : null
3065
- ] })
3066
- }
3067
- );
3068
- }
3069
- function TimeslotFixed({ cell }) {
3070
- return /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot", children: /* @__PURE__ */ jsx11("span", { className: "scopetickets-island-timeslot__pill", "data-state": cell.state, children: /* @__PURE__ */ jsx11(TimeslotRow, { cell }) }) });
3071
- }
3072
-
3073
- // src/island/TimeslotGroupSection.tsx
3074
- import { jsx as jsx12, jsxs as jsxs8 } from "react/jsx-runtime";
3075
- function TimeslotGroupSection({ group, accessory, onSelect }) {
3076
- return /* @__PURE__ */ jsxs8("section", { className: "scopetickets-island-timeslots__group", children: [
3077
- group.label === null ? null : /* @__PURE__ */ jsx12("h4", { className: "scopetickets-island-timeslots__label", children: group.label }),
3078
- /* @__PURE__ */ jsx12("div", { className: "scopetickets-island-timeslots__list", children: group.cells.map((cell, index) => /* @__PURE__ */ jsx12(
3079
- Timeslot,
3080
- {
3081
- cell,
3082
- accessory,
3083
- onSelect
3084
- },
3085
- `${cell.slot.startTime}-${index}`
3086
- )) })
3087
- ] });
3088
- }
3089
-
3090
- // src/island/TimeslotPicker.tsx
3091
- import { jsx as jsx13 } from "react/jsx-runtime";
3092
- function TimeslotPicker({
3093
- slots,
3094
- selection,
3095
- today,
3096
- nowTime,
3097
- onSelect,
3098
- accessory,
3099
- grouping
3100
- }) {
3101
- const groups = useMemo3(
3102
- () => buildTimeslotGroups(slots, { selection, today, nowTime, grouping }),
3103
- [slots, selection, today, nowTime, grouping]
3104
- );
3105
- return /* @__PURE__ */ jsx13("div", { className: "scopetickets-island-timeslots", children: groups.map((group) => /* @__PURE__ */ jsx13(
3106
- TimeslotGroupSection,
3107
- {
3108
- group,
3109
- accessory,
3110
- onSelect
3111
- },
3112
- group.key
3113
- )) });
3114
- }
3115
-
3116
- // src/island/TimePicker.tsx
3117
- import { useEffect as useEffect6, useReducer } from "react";
3118
-
3119
- // src/island/CalendarWeekSection.tsx
3120
- import { useCallback as useCallback3, useEffect as useEffect5, useLayoutEffect, useRef as useRef4, useState as useState5 } from "react";
3121
- import { jsx as jsx14, jsxs as jsxs9 } from "react/jsx-runtime";
3122
- function CalendarWeekSection({
3123
- series,
3124
- today,
3125
- selectedDay,
3126
- onSelectDay,
3127
- remaining,
3128
- accessory,
3129
- onVisibleMonthChange
3130
- }) {
3131
- const weeks = weeksInSeries(series);
3132
- const selectedWeek = startOfWeek(selectedDay);
3133
- const selectedIndex = Math.max(weeks.indexOf(selectedWeek), 0);
3134
- const pagerRef = useRef4(null);
3135
- const pageRefs = useRef4([]);
3136
- const [visibleIndex, setVisibleIndex] = useState5(selectedIndex);
3137
- useEffect5(() => {
3138
- setVisibleIndex(selectedIndex);
3139
- }, [selectedIndex]);
3140
- const strideOf = (pager) => {
3141
- const first = pageRefs.current[0];
3142
- const second = pageRefs.current[1];
3143
- if (first && second) return second.offsetLeft - first.offsetLeft;
3144
- return first?.offsetWidth ?? pager.clientWidth;
3145
- };
3146
- const paint = useCallback3(() => {
3147
- const pager = pagerRef.current;
3148
- if (!pager) return;
3149
- const stride = strideOf(pager);
3150
- if (stride <= 0) return;
3151
- const at = pager.scrollLeft / stride;
3152
- pageRefs.current.forEach((page2, index) => {
3153
- if (!page2) return;
3154
- page2.style.setProperty(
3155
- "--scopetickets-island-week-distance",
3156
- String(Math.min(Math.abs(index - at), 1))
3157
- );
3158
- });
3159
- const page = Math.round(at);
3160
- setVisibleIndex(Math.min(Math.max(page, 0), Math.max(weeks.length - 1, 0)));
3161
- }, [weeks.length]);
3162
- useLayoutEffect(() => {
3163
- const pager = pagerRef.current;
3164
- if (!pager) return;
3165
- pager.scrollLeft = selectedIndex * strideOf(pager);
3166
- paint();
3167
- }, [selectedIndex, paint]);
3168
- const visibleWeek = weeks[Math.min(visibleIndex, weeks.length - 1)] ?? selectedWeek;
3169
- useEffect5(() => {
3170
- if (weeks.length === 0) return;
3171
- onVisibleMonthChange?.(
3172
- visibleWeek === selectedWeek ? monthOfDay(selectedDay) : monthOfWeek(visibleWeek)
3173
- );
3174
- }, [weeks.length, visibleWeek, selectedWeek, selectedDay, onVisibleMonthChange]);
3175
- if (weeks.length === 0) return null;
3176
- return /* @__PURE__ */ jsxs9("div", { className: "scopetickets-island-week", children: [
3177
- /* @__PURE__ */ jsx14(CalendarWeekdayNames, {}),
3178
- /* @__PURE__ */ jsx14("div", { className: "scopetickets-island-week__pager", ref: pagerRef, onScroll: paint, children: weeks.map((weekStart, index) => /* @__PURE__ */ jsx14(
3179
- "div",
3180
- {
3181
- className: "scopetickets-island-week__page",
3182
- ref: (node) => {
3183
- pageRefs.current[index] = node;
3184
- },
3185
- children: /* @__PURE__ */ jsx14("div", { className: "scopetickets-island-week__row", children: buildWeekRow(series, weekStart, { today, selectedDay }).map((cell, dayIndex) => /* @__PURE__ */ jsx14(
3186
- CalendarDay,
3187
- {
3188
- cell,
3189
- accessory,
3190
- remaining: cell.kind === "EMPTY" ? null : remaining?.[cell.day] ?? null,
3191
- label: cell.kind === "EMPTY" ? "" : formatDayDate(cell.day),
3192
- onSelect: onSelectDay
3193
- },
3194
- cell.kind === "EMPTY" ? `empty-${dayIndex}` : cell.day
3195
- )) })
3196
- },
3197
- weekStart
3198
- )) })
3199
- ] });
3200
- }
3201
-
3202
- // src/island/SelectedDayHeading.tsx
3203
- import { jsx as jsx15, jsxs as jsxs10 } from "react/jsx-runtime";
3204
- function SelectedDayHeading({ day }) {
3205
- return /* @__PURE__ */ jsxs10("h3", { className: "scopetickets-island-day-heading", children: [
3206
- /* @__PURE__ */ jsxs10("span", { className: "scopetickets-island-day-heading__weekday", children: [
3207
- formatDayWeekday(day),
3208
- ","
3209
- ] }),
3210
- /* @__PURE__ */ jsx15("span", { className: "scopetickets-island-day-heading__date", children: formatDayDate(day) })
3211
- ] });
3212
- }
3213
-
3214
- // ../checkout-core/src/motion/island-step-order.ts
3215
- function dayDirection(from, to) {
3216
- if (from === to) return "NONE";
3217
- return to > from ? "FORWARD" : "BACKWARD";
3218
- }
3219
- function stepDirectionSign(direction) {
3220
- if (direction === "FORWARD") return 1;
3221
- if (direction === "BACKWARD") return -1;
3222
- return 0;
3223
- }
3224
-
3225
- // ../checkout-core/src/motion/island-day-swap.ts
3226
- function daySwapAtRest(content) {
3227
- return { phase: "REST", shown: content };
3228
- }
3229
- function reduceDaySwap(state, event) {
3230
- switch (event.type) {
3231
- case "CONTENT_CHANGED": {
3232
- const next = event.content;
3233
- if (next.day === state.shown.day) {
3234
- const shown = { day: state.shown.day, slots: next.slots };
3235
- if (state.phase === "LEAVING") {
3236
- return { phase: "ENTERING", shown, sign: state.sign === 1 ? -1 : 1 };
3237
- }
3238
- if (sameTimeslots(next.slots, state.shown.slots)) return state;
3239
- return { ...state, shown };
3240
- }
3241
- if (state.phase === "LEAVING" && state.to === next.day) return state;
3242
- const sign = stepDirectionSign(dayDirection(state.shown.day, next.day));
3243
- if (sign === 0) return state;
3244
- return { phase: "LEAVING", shown: state.shown, to: next.day, sign };
3245
- }
3246
- case "LEFT":
3247
- if (state.phase !== "LEAVING") return state;
3248
- return { phase: "ENTERING", shown: event.content, sign: state.sign };
3249
- case "ARRIVED":
3250
- if (state.phase !== "ENTERING") return state;
3251
- return { phase: "REST", shown: state.shown };
3252
- }
3253
- }
3254
-
3255
- // src/island/island-day-swap-css.ts
3256
- var DAY_SWAP_OUT_ANIMATION = "scopetickets-island-day-swap-out";
3257
- var DAY_SWAP_IN_ANIMATION = "scopetickets-island-day-swap-in";
3258
-
3259
- // src/island/TimePicker.tsx
3260
- import { jsx as jsx16, jsxs as jsxs11 } from "react/jsx-runtime";
3261
- function TimePicker({
3262
- series,
3263
- today,
3264
- nowTime,
3265
- selection,
3266
- onSelectDay,
3267
- slots,
3268
- onSelectTime,
3269
- remaining,
3270
- accessory = DATE_PICKER_ACCESSORY,
3271
- onVisibleMonthChange,
3272
- grouping
3273
- }) {
3274
- const [swap, dispatch] = useReducer(reduceDaySwap, { day: selection.day, slots }, daySwapAtRest);
3275
- useEffect6(() => {
3276
- dispatch({ type: "CONTENT_CHANGED", content: { day: selection.day, slots } });
3277
- }, [selection.day, slots]);
3278
- const onSwapAnimationEnd = (event) => {
3279
- if (event.animationName === DAY_SWAP_OUT_ANIMATION) {
3280
- dispatch({ type: "LEFT", content: { day: selection.day, slots } });
3281
- } else if (event.animationName === DAY_SWAP_IN_ANIMATION) {
3282
- dispatch({ type: "ARRIVED" });
3283
- }
3284
- };
3285
- const shownSelection = swap.shown.day === selection.day ? selection : { day: swap.shown.day, startTime: null };
3286
- return /* @__PURE__ */ jsxs11("div", { className: "scopetickets-island-time", "data-accessory": accessory, children: [
3287
- /* @__PURE__ */ jsx16(
3288
- CalendarWeekSection,
3289
- {
3290
- series,
3291
- today,
3292
- selectedDay: selection.day,
3293
- onSelectDay,
3294
- remaining,
3295
- accessory,
3296
- onVisibleMonthChange
3297
- }
3298
- ),
3299
- /* @__PURE__ */ jsxs11(
3300
- "div",
3301
- {
3302
- className: "scopetickets-island-time__swap",
3303
- "data-day-swap": swap.phase,
3304
- style: swap.phase === "REST" ? void 0 : { "--scopetickets-island-swap-sign": swap.sign },
3305
- onAnimationEnd: onSwapAnimationEnd,
3306
- children: [
3307
- /* @__PURE__ */ jsx16(SelectedDayHeading, { day: swap.shown.day }),
3308
- /* @__PURE__ */ jsx16(
3309
- TimeslotPicker,
3310
- {
3311
- slots: swap.shown.slots,
3312
- selection: shownSelection,
3313
- today,
3314
- nowTime,
3315
- onSelect: onSelectTime,
3316
- accessory,
3317
- grouping
3318
- }
3319
- )
3320
- ]
3321
- }
3322
- )
3323
- ] });
3324
- }
3325
-
3326
- // src/island/CalendarGrainButton.tsx
3327
- import { useCallback as useCallback4, useLayoutEffect as useLayoutEffect2, useRef as useRef5, useState as useState6 } from "react";
3328
- import { jsx as jsx17, jsxs as jsxs12 } from "react/jsx-runtime";
3329
- function useShortenedMonth(long) {
3330
- const [short, setShort] = useState6(false);
3331
- const title = useRef5(null);
3332
- const probe = useRef5(null);
3333
- const measure = useCallback4(() => {
3334
- const box = title.current;
3335
- const full = probe.current;
3336
- if (!box || !full) return;
3337
- const wanted = Math.ceil(full.getBoundingClientRect().width);
3338
- box.style.setProperty("--scopetickets-island-grain-width", `${wanted}px`);
3339
- setShort(box.clientWidth + 1 < wanted);
3340
- }, []);
3341
- useLayoutEffect2(() => {
3342
- measure();
3343
- if (typeof ResizeObserver === "undefined") return;
3344
- const observer = new ResizeObserver(measure);
3345
- if (title.current) observer.observe(title.current);
3346
- return () => observer.disconnect();
3347
- }, [measure, long]);
3348
- return {
3349
- short,
3350
- titleRef: useCallback4(
3351
- (node) => {
3352
- title.current = node;
3353
- measure();
3354
- },
3355
- [measure]
3356
- ),
3357
- probeRef: useCallback4(
3358
- (node) => {
3359
- probe.current = node;
3360
- measure();
3361
- },
3362
- [measure]
3363
- )
3364
- };
3365
- }
3366
- function CalendarGrainButton({ month, grain, onPress }) {
3367
- const press = useIslandPress("element");
3368
- const long = grain === "YEAR" ? formatMonthYear(month) : formatMonthName(month);
3369
- const { short, titleRef, probeRef } = useShortenedMonth(long);
3370
- const shown = grain === "MONTH" && short ? formatMonthNameShort(month) : long;
3371
- const title = /* @__PURE__ */ jsxs12(
3372
- "span",
3373
- {
3374
- className: "scopetickets-island-header-button__title",
3375
- ref: titleRef,
3376
- ...grain === "MONTH" && short ? { "data-grain-short": "" } : null,
3377
- children: [
3378
- shown,
3379
- grain === "MONTH" ? /* @__PURE__ */ jsx17(
3380
- "span",
3381
- {
3382
- className: "scopetickets-island-header-button__probe",
3383
- ref: probeRef,
3384
- "aria-hidden": "true",
3385
- children: long
3386
- }
3387
- ) : null
3388
- ]
3389
- }
3390
- );
3391
- if (onPress === void 0) {
3392
- return /* @__PURE__ */ jsx17("span", { className: "scopetickets-island-chrome-pill scopetickets-island-grain-pill", children: title });
3393
- }
3394
- return /* @__PURE__ */ jsx17(
3395
- "button",
3396
- {
3397
- type: "button",
3398
- className: "scopetickets-island-chrome-pill scopetickets-island-header-button scopetickets-island-grain-pill",
3399
- onClick: onPress,
3400
- ...press,
3401
- children: title
3402
- }
3403
- );
3404
- }
3405
-
3406
- // src/island/Switch.tsx
3407
- import { jsx as jsx18 } from "react/jsx-runtime";
3408
- function Switch({ checked, onChange, label, size = "wide", disabled = false }) {
3409
- const press = useIslandPress("element");
3410
- return /* @__PURE__ */ jsx18(
3411
- "button",
3412
- {
3413
- type: "button",
3414
- role: "switch",
3415
- "aria-checked": checked,
3416
- "aria-label": label,
3417
- disabled,
3418
- className: `scopetickets-island-switch scopetickets-island-switch--${size}`,
3419
- onClick: () => onChange(!checked),
3420
- ...disabled ? {} : press,
3421
- children: /* @__PURE__ */ jsx18("span", { className: "scopetickets-island-switch__thumb", "aria-hidden": "true" })
3422
- }
3423
- );
3424
- }
3425
-
3426
- export {
3427
- SURFACE_MORPH_MS,
3428
- SURFACE_SPRING,
3429
- CARRY_SPRING,
3430
- POP_RETURN_SPRING,
3431
- settleMs,
3432
- springAt,
3433
- OUTGOING_FADE_MS,
3434
- SURFACE_MORPH_DELAY_MS,
3435
- INCOMING_FADE_DELAY_MS,
3436
- INCOMING_FADE_MS,
3437
- ARC_LEAD_BEZIER,
3438
- ARC_TRAIL_BEZIER,
3439
- CARRY_MOVE_DELAY_MS,
3440
- CARRY_MOVE_MS,
3441
- POP_SCALE,
3442
- SHIELD_POP_SCALE,
3443
- POP_RETURN_MS,
3444
- POP_MS,
3445
- PRESS_IN_MS,
3446
- PRESS_LETGO_MS,
3447
- ISLAND_TRANSITION_MS,
3448
- PROCESSING_FLOOR_MS,
3449
- PAID_GRACE_MS,
3450
- ACCOUNT_CREATING_FLOOR_MS,
3451
- HOLD_TICK_MS,
3452
- PressContext,
3453
- useIslandPress,
3454
- FIELD_COPY,
3455
- ACTION_COPY,
3456
- DISMISS_COPY,
3457
- ISLAND_COPY,
3458
- resolveEnvironmentUrls,
3459
- ApiError,
3460
- ScopeClient,
3461
- CARRIED_CHECKOUT_PARAMS,
3462
- buildFrameUrl,
3463
- allowedFrameOrigin,
3464
- parseFrameEvent,
3465
- buildConfigMessage,
3466
- buildSubmitConfirmedMessage,
3467
- buildSubmitRejectedMessage,
3468
- buildTriggerSubmitMessage,
3469
- buildCancelRequestedMessage,
3470
- isAcceptableName,
3471
- isValidEmail,
3472
- flagTone,
3473
- emailFlag,
3474
- emailFlagTitle,
3475
- DEFAULT_COUNTRY_CODE,
3476
- countryByCode,
3477
- DEFAULT_DIAL_CODE,
3478
- countryByDialCode,
3479
- routePhoneInput,
3480
- formatNational,
3481
- isValidPhone,
3482
- phoneFlag,
3483
- e164,
3484
- normalizeE164,
3485
- isCompleteName,
3486
- splitFullName,
3487
- SOLO_KEY,
3488
- groupUserTypes,
3489
- partyTypes,
3490
- assignmentFor,
3491
- userTypeNames,
3492
- clampRemaining,
3493
- trackPaths,
3494
- timerPaths,
3495
- slotFullness,
3496
- parseWallClockTime,
3497
- timeOfDayInZone,
3498
- dayInZone,
3499
- partOfDayLabel,
3500
- partOfDay,
3501
- formatSlotRange,
3502
- formatSlotDuration,
3503
- withSelectedDay,
3504
- withSelectedTime,
3505
- sameTimeslots,
3506
- buildTimeslotGroups,
3507
- timeslotRequest,
3508
- toAvailabilityLevel,
3509
- readAvailability,
3510
- availabilityColor,
3511
- isDatePickerCellSelectable,
3512
- isSelectableCalendarCell,
3513
- eventsOn,
3514
- eventKeyForDay,
3515
- dateRange,
3516
- soonestRelevantDay,
3517
- addDays,
3518
- startOfWeek,
3519
- monthOfWeek,
3520
- weeksInSeries,
3521
- weeksInCalendar,
3522
- buildWeekRow,
3523
- buildMonthGrid,
3524
- weekContainingDay,
3525
- locateDayInMonthStack,
3526
- monthOfDay,
3527
- monthsInSeries,
3528
- openingMonth,
3529
- stepMonth,
3530
- formatMonthYear,
3531
- formatMonthName,
3532
- formatMonthNameShort,
3533
- formatDayDate,
3534
- formatWeekdayAndDate,
3535
- formatDayChip,
3536
- formatDayWeekday,
3537
- DATE_PICKER_ACCESSORY,
3538
- monthStartRows,
3539
- monthAtRow,
3540
- monthOpeningRow,
3541
- toggleSelectedDay,
3542
- majorUnits,
3543
- formatMoney,
3544
- moneyParts,
3545
- widestAmount,
3546
- quoteLines,
3547
- PartyStepper,
3548
- DayPicker,
3549
- ContentFlag,
3550
- CounterRing,
3551
- TimeslotPicker,
3552
- TimePicker,
3553
- CalendarGrainButton,
3554
- Switch
3555
- };
3556
- //# sourceMappingURL=chunk-VS7ACUTQ.js.map