@jay-framework/wix-bookings 0.26.4 → 0.26.6

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,38 +1,8 @@
1
1
  import { makeJayInit, makeJayStackComponent } from "@jay-framework/fullstack-component";
2
2
  import { createJayContext, useGlobalContext, registerGlobalContext } from "@jay-framework/runtime";
3
- import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT, ensureSessionFresh } from "@jay-framework/wix-server-client/client";
4
- import { registerReactiveGlobalContext, createSignal, useReactive } from "@jay-framework/component";
3
+ import { wixFetch, ensureSessionFresh, WixApiError, WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
4
+ import { registerReactiveGlobalContext, createSignal, createEffect, useReactive } from "@jay-framework/component";
5
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
6
- const MAX_SLOTS_PER_QUERY = 200;
7
- const SERVICES_PAGE_SIZE = 100;
8
- async function queryBookingServices(client, bookingAppId) {
9
- const allServices = [];
10
- let offset = 0;
11
- let hasMorePages = true;
12
- while (hasMorePages) {
13
- const result2 = await wixFetch(
14
- client,
15
- "/bookings/v2/services/query",
16
- {
17
- method: "POST",
18
- body: {
19
- query: {
20
- filter: { appId: bookingAppId },
21
- paging: { limit: SERVICES_PAGE_SIZE, offset }
22
- },
23
- conditionalFields: ["STAFF_MEMBER_DETAILS"]
24
- }
25
- }
26
- );
27
- const batch = result2.services ?? [];
28
- allServices.push(...batch);
29
- hasMorePages = batch.length >= SERVICES_PAGE_SIZE;
30
- if (hasMorePages) {
31
- offset += SERVICES_PAGE_SIZE;
32
- }
33
- }
34
- return allServices;
35
- }
36
6
  async function getBookingServiceById(client, serviceId) {
37
7
  const result2 = await wixFetch(client, "/bookings/v2/services/query", {
38
8
  method: "POST",
@@ -45,469 +15,6 @@ async function getBookingServiceById(client, serviceId) {
45
15
  });
46
16
  return result2.services?.[0];
47
17
  }
48
- const DEFAULT_FORM_ID = "00000000-0000-0000-0000-000000000000";
49
- function participantFormId(form) {
50
- const id = form?.id ?? form?._id ?? "";
51
- return id === DEFAULT_FORM_ID ? "" : id;
52
- }
53
- function formatPrice(service) {
54
- const price = service.payment?.fixed?.price;
55
- if (!price?.value) {
56
- return "Free";
57
- }
58
- const amount = parseFloat(price.value);
59
- return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
60
- }
61
- function formatDurationMinutes(service) {
62
- const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
63
- if (!minutes) {
64
- return "";
65
- }
66
- return `${minutes} min`;
67
- }
68
- function mapService(raw) {
69
- const duration = formatDurationMinutes(raw);
70
- return {
71
- id: raw._id ?? raw.id ?? "",
72
- name: raw.name ?? "Service",
73
- type: raw.type ?? "APPOINTMENT",
74
- description: raw.description ?? "",
75
- priceLabel: formatPrice(raw),
76
- durationLabel: duration,
77
- formId: participantFormId(raw.form)
78
- };
79
- }
80
- function createSlotId(resourceId, localStartDate) {
81
- return `${resourceId}:${localStartDate}`;
82
- }
83
- function formatSlotLabel(localStartDate) {
84
- const date = new Date(localStartDate);
85
- return date.toLocaleString([], {
86
- weekday: "short",
87
- month: "short",
88
- day: "numeric",
89
- hour: "2-digit",
90
- minute: "2-digit"
91
- });
92
- }
93
- function mapAppointmentSlot(slot) {
94
- if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
95
- return null;
96
- }
97
- return {
98
- id: createSlotId(slot.scheduleId, slot.localStartDate),
99
- localStartDate: slot.localStartDate,
100
- localEndDate: slot.localEndDate,
101
- label: formatSlotLabel(slot.localStartDate),
102
- scheduleId: slot.scheduleId,
103
- serviceType: "APPOINTMENT"
104
- };
105
- }
106
- function mapClassSlot(slot) {
107
- const eventId = slot.eventInfo?.eventId;
108
- if (!eventId || !slot.localStartDate || !slot.localEndDate) {
109
- return null;
110
- }
111
- return {
112
- id: createSlotId(eventId, slot.localStartDate),
113
- localStartDate: slot.localStartDate,
114
- localEndDate: slot.localEndDate,
115
- label: formatSlotLabel(slot.localStartDate),
116
- eventId,
117
- serviceType: "CLASS"
118
- };
119
- }
120
- function localDateStrInTimeZone(date, timeZone) {
121
- const parts = new Intl.DateTimeFormat("en-US", {
122
- timeZone,
123
- year: "numeric",
124
- month: "2-digit",
125
- day: "2-digit",
126
- hour: "2-digit",
127
- minute: "2-digit",
128
- second: "2-digit",
129
- hour12: false
130
- }).formatToParts(date);
131
- const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
132
- const hour = read("hour") === "24" ? "00" : read("hour");
133
- return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
134
- }
135
- function paymentPreferenceFromService(service) {
136
- const opts = service.payment?.options ?? {};
137
- if (opts.online && !opts.inPerson) {
138
- return "ONLINE";
139
- }
140
- if (!opts.online && opts.inPerson) {
141
- return "OFFLINE";
142
- }
143
- return "ONLINE";
144
- }
145
- async function createBookingRecord(client, body) {
146
- return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
147
- }
148
- async function createBookingCart(client, bookingId, bookingAppId) {
149
- return wixFetch(client, "/ecom/v2/carts", {
150
- method: "POST",
151
- body: {
152
- catalogItems: [
153
- {
154
- quantity: 1,
155
- catalogReference: { catalogItemId: bookingId, appId: bookingAppId }
156
- }
157
- ],
158
- cart: { source: { channelType: "WEB" } }
159
- }
160
- });
161
- }
162
- async function calculateBookingCart(client, cartId) {
163
- return wixFetch(client, `/ecom/v2/carts/${cartId}/calculate`, { method: "POST", body: {} });
164
- }
165
- async function placeBookingOrder(client, cartId) {
166
- const res = await wixFetch(
167
- client,
168
- `/ecom/v2/carts/${cartId}/place-order`,
169
- { method: "POST", body: {} }
170
- );
171
- return { orderId: res?.orderId };
172
- }
173
- async function createBookingRedirectSession(client, cartId, postFlowUrl) {
174
- return wixFetch(client, "/headless/v1/redirect-session", {
175
- method: "POST",
176
- body: {
177
- ecomCheckout: { checkoutId: cartId },
178
- callbacks: { postFlowUrl }
179
- }
180
- });
181
- }
182
- async function getBookingCheckoutUrl(client, cartId) {
183
- return wixFetch(client, `/ecom/v2/carts/${cartId}/get-checkout-url`, {
184
- method: "POST",
185
- body: {}
186
- });
187
- }
188
- const AVAILABILITY_PAGE_SIZE = 100;
189
- async function listAvailabilityTimeSlots(client, input, options) {
190
- const allSlots = [];
191
- const maxSlots = options?.maxSlots;
192
- let cursor;
193
- let hasMorePages = true;
194
- while (hasMorePages) {
195
- const result2 = await wixFetch(
196
- client,
197
- "/_api/service-availability/v2/time-slots",
198
- {
199
- method: "POST",
200
- body: {
201
- serviceId: input.serviceId,
202
- fromLocalDate: input.fromLocalDate,
203
- toLocalDate: input.toLocalDate,
204
- timeZone: input.timeZone,
205
- bookable: true,
206
- cursorPaging: cursor ? { cursor, limit: AVAILABILITY_PAGE_SIZE } : { limit: AVAILABILITY_PAGE_SIZE }
207
- }
208
- }
209
- );
210
- allSlots.push(...result2.timeSlots ?? []);
211
- if (allSlots.length >= maxSlots) {
212
- return allSlots.slice(0, maxSlots);
213
- }
214
- cursor = result2.pagingMetadata?.cursors?.next;
215
- hasMorePages = !!cursor && result2.pagingMetadata?.hasNext !== false;
216
- }
217
- return allSlots;
218
- }
219
- const EVENT_SLOTS_PAGE_SIZE = 100;
220
- async function listEventTimeSlots(client, input, options) {
221
- const allSlots = [];
222
- const maxSlots = options?.maxSlots;
223
- let cursor;
224
- let hasMorePages = true;
225
- while (hasMorePages) {
226
- const result2 = await wixFetch(
227
- client,
228
- "/_api/service-availability/v2/time-slots/event",
229
- {
230
- method: "POST",
231
- body: {
232
- serviceIds: input.serviceIds,
233
- fromLocalDate: input.fromLocalDate,
234
- toLocalDate: input.toLocalDate,
235
- timeZone: input.timeZone,
236
- includeNonBookable: false,
237
- cursorPaging: cursor ? { cursor, limit: EVENT_SLOTS_PAGE_SIZE } : { limit: EVENT_SLOTS_PAGE_SIZE }
238
- }
239
- }
240
- );
241
- allSlots.push(...result2.timeSlots ?? []);
242
- if (allSlots.length >= maxSlots) {
243
- return allSlots.slice(0, maxSlots);
244
- }
245
- cursor = result2.pagingMetadata?.cursors?.next;
246
- hasMorePages = !!cursor && result2.pagingMetadata?.hasNext !== false;
247
- }
248
- return allSlots;
249
- }
250
- async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
251
- try {
252
- const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
253
- const redirectUrl = redirectData.redirectSession?.fullUrl;
254
- if (redirectUrl) {
255
- return redirectUrl;
256
- }
257
- } catch (error) {
258
- if (!(error instanceof WixApiError) || error.status !== 400 && error.status !== 404) {
259
- throw error;
260
- }
261
- }
262
- const checkoutUrlData = await getBookingCheckoutUrl(wixClient, cartId);
263
- const checkoutUrl = checkoutUrlData.checkoutUrl;
264
- if (!checkoutUrl) {
265
- throw new Error(
266
- "Checkout redirect failed. Add your site origin to Allowed redirect domains in Wix Headless Settings, or publish the site so get-checkout-url can return a checkout page."
267
- );
268
- }
269
- return checkoutUrl;
270
- }
271
- function createWixBookingsService(wixClient, config) {
272
- return {
273
- async listServices() {
274
- const items = await queryBookingServices(wixClient, config.bookingAppId);
275
- return items.filter((item) => !item.hidden).map((item) => mapService(item));
276
- },
277
- async listSlots({ serviceId, serviceType, timezone, windowDays }) {
278
- const now = /* @__PURE__ */ new Date();
279
- const tz = timezone ?? "UTC";
280
- const from = localDateStrInTimeZone(now, tz);
281
- const days = windowDays ?? config.slotWindowDays;
282
- const to = new Date(now.getTime() + days * 24 * 60 * 60 * 1e3);
283
- const toStr = localDateStrInTimeZone(to, tz);
284
- const slotQueryOptions = { maxSlots: MAX_SLOTS_PER_QUERY };
285
- if (serviceType === "APPOINTMENT") {
286
- const timeSlots2 = await listAvailabilityTimeSlots(
287
- wixClient,
288
- {
289
- serviceId,
290
- fromLocalDate: from,
291
- toLocalDate: toStr,
292
- timeZone: tz
293
- },
294
- slotQueryOptions
295
- );
296
- return timeSlots2.map((slot) => mapAppointmentSlot(slot)).filter((slot) => slot !== null);
297
- }
298
- const timeSlots = await listEventTimeSlots(
299
- wixClient,
300
- {
301
- serviceIds: [serviceId],
302
- fromLocalDate: from,
303
- toLocalDate: toStr,
304
- timeZone: tz
305
- },
306
- slotQueryOptions
307
- );
308
- return timeSlots.map((slot) => mapClassSlot(slot)).filter((slot) => slot !== null);
309
- },
310
- async createBooking(input) {
311
- const rawService = await getBookingServiceById(wixClient, input.serviceId);
312
- const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
313
- rawService
314
- ) : "ONLINE");
315
- const slotData = {
316
- serviceId: input.serviceId,
317
- startDate: input.slot.localStartDate,
318
- endDate: input.slot.localEndDate,
319
- timezone: input.timezone,
320
- location: { locationType: "OWNER_BUSINESS" },
321
- // Any staff member of the configured staff resource type; without one, the slot's own (a class
322
- // session names its staff; Wix rejects an empty resource type id).
323
- ...config.staffResourceTypeId ? {
324
- resourceSelections: [
325
- {
326
- resourceTypeId: config.staffResourceTypeId,
327
- selectionMethod: "ANY_RESOURCE"
328
- }
329
- ]
330
- } : {}
331
- };
332
- if (input.serviceType === "APPOINTMENT") {
333
- slotData.scheduleId = input.slot.scheduleId;
334
- } else {
335
- slotData.eventId = input.slot.eventId;
336
- }
337
- const bookingData = await createBookingRecord(wixClient, {
338
- booking: {
339
- bookedEntity: { slot: slotData },
340
- selectedPaymentOption: paymentPreference,
341
- totalParticipants: 1
342
- },
343
- formSubmission: input.formValues
344
- });
345
- const bookingId = bookingData.booking.id;
346
- const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
347
- const cartId = cartData.cart.id;
348
- const calcData = await calculateBookingCart(wixClient, cartId);
349
- const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
350
- if (total > 0) {
351
- const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
352
- const redirectUrl = await resolvePaidCheckoutRedirectUrl(
353
- wixClient,
354
- cartId,
355
- postFlowUrl
356
- );
357
- return { outcome: "redirect", redirectUrl };
358
- }
359
- const { orderId } = await placeBookingOrder(wixClient, cartId);
360
- return { outcome: "confirmed", ...orderId ? { orderId } : {} };
361
- }
362
- };
363
- }
364
- function canBookOnline(features, type, step) {
365
- if (type === "COURSE") return step !== "form" || features.courses;
366
- return type === "CLASS" ? features.groups : features.appointments;
367
- }
368
- const WIX_BOOKINGS_CONTEXT = createJayContext("wix:bookings");
369
- function createWixBookingsContext(wixClient, config) {
370
- let settings;
371
- const readSettings = () => {
372
- if (!settings) {
373
- settings = wixFetch(
374
- wixClient,
375
- "/_api/bookings-settings/v2/settings?fields=FEATURES&fields=SITE_PROPERTIES"
376
- ).then((res) => res.bookingsSettings).catch(() => {
377
- settings = void 0;
378
- return void 0;
379
- });
380
- }
381
- return settings;
382
- };
383
- const service = createWixBookingsService(wixClient, config);
384
- const ownBookings = async (filter) => {
385
- const res = await wixFetch(wixClient, "/_api/bookings-reader/v2/extended-bookings/query", {
386
- method: "POST",
387
- body: {
388
- query: { filter, cursorPaging: { limit: 100 } },
389
- withBookingAllowedActions: false
390
- }
391
- }).catch(() => ({ extendedBookings: [] }));
392
- return (res.extendedBookings ?? []).map((e) => e.booking ?? {});
393
- };
394
- return {
395
- async features() {
396
- const f = (await readSettings())?.features ?? {};
397
- return {
398
- groups: Boolean(f.bookingsGroups?.enabled),
399
- appointments: Boolean(f.bookingsAppointments?.enabled),
400
- courses: Boolean(f.bookingsCourses?.enabled),
401
- payments: Boolean(f.bookingsPayments?.enabled)
402
- };
403
- },
404
- async timeZone() {
405
- return (await readSettings())?.siteProperties?.timeZone ?? "UTC";
406
- },
407
- async serviceBySlug(slug) {
408
- const res = await wixFetch(
409
- wixClient,
410
- "/bookings/v2/services/query",
411
- {
412
- method: "POST",
413
- body: {
414
- query: {
415
- filter: { "supportedSlugs.name": slug, hidden: false },
416
- paging: { limit: 1 }
417
- }
418
- }
419
- }
420
- );
421
- return res.services?.[0];
422
- },
423
- serviceById(id) {
424
- return getBookingServiceById(wixClient, id);
425
- },
426
- async timeSlots(query) {
427
- const res = await wixFetch(
428
- wixClient,
429
- "/_api/service-availability/v2/time-slots/event",
430
- {
431
- method: "POST",
432
- body: {
433
- serviceIds: query.serviceIds,
434
- timeZone: query.timeZone,
435
- fromLocalDate: query.fromLocalDate,
436
- toLocalDate: query.toLocalDate,
437
- includeNonBookable: query.includeNonBookable ?? true,
438
- ...query.maxSlotsPerDay ? { maxSlotsPerDay: query.maxSlotsPerDay } : {},
439
- eventFilter: {},
440
- cursorPaging: { limit: query.limit ?? 1e3 }
441
- }
442
- }
443
- );
444
- return res.timeSlots ?? [];
445
- },
446
- createBooking: service.createBooking,
447
- async serviceBookings(serviceId) {
448
- return (await ownBookings({
449
- "bookedEntity.slot.serviceId": serviceId,
450
- status: { $in: ["CONFIRMED", "PENDING"] }
451
- })).filter((b) => b.id || b.startDate);
452
- },
453
- async bookingById(bookingId) {
454
- return (await ownBookings({ id: bookingId }))[0];
455
- },
456
- async orderById(orderId) {
457
- try {
458
- const res = await wixFetch(
459
- wixClient,
460
- `/ecom/v1/orders/${encodeURIComponent(orderId)}`
461
- );
462
- return res.order;
463
- } catch (error) {
464
- if (error instanceof WixApiError) return void 0;
465
- throw error;
466
- }
467
- }
468
- };
469
- }
470
- function provideWixBookingsContext(config) {
471
- const client = useGlobalContext(WIX_CLIENT_CONTEXT)?.client;
472
- if (!client) return void 0;
473
- const context = createWixBookingsContext(client, config);
474
- registerGlobalContext(WIX_BOOKINGS_CONTEXT, context);
475
- return context;
476
- }
477
- const init = makeJayInit().withClient(async ({ config }) => {
478
- provideWixBookingsContext(config);
479
- });
480
- var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
481
- ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
482
- ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
483
- ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
484
- return ServicesFailure2;
485
- })(ServicesFailure || {});
486
- var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
487
- SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
488
- SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
489
- return SlotsFailure2;
490
- })(SlotsFailure || {});
491
- var BookingState = /* @__PURE__ */ ((BookingState2) => {
492
- BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
493
- BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
494
- BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
495
- BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
496
- return BookingState2;
497
- })(BookingState || {});
498
- var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
499
- BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
500
- BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
501
- BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
502
- BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
503
- BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
504
- BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
505
- BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
506
- return BookingFailure2;
507
- })(BookingFailure || {});
508
- const listServices = createActionCaller("wixBookings.listServices", "GET");
509
- const listSlots = createActionCaller("wixBookings.listSlots", "GET");
510
- const createBooking = createActionCaller("wixBookings.createBooking", "POST");
511
18
  const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
512
19
  function canonicalFormId(raw) {
513
20
  if (typeof raw !== "string") return void 0;
@@ -521,7 +28,7 @@ const EMIT_SUBMIT_START = Symbol("wix-forms.emitSubmitStart");
521
28
  function provideWixFormsContext() {
522
29
  return registerReactiveGlobalContext(WIX_FORMS_CONTEXT, createWixFormsContextState);
523
30
  }
524
- function registeredFieldChecks(context, formId) {
31
+ function registeredFields(context, formId) {
525
32
  const canonical = canonicalFormId(formId);
526
33
  return canonical ? context[REGISTERED_CHECKS](canonical) : [];
527
34
  }
@@ -534,18 +41,19 @@ function emitSubmitStart(context, event) {
534
41
  function createWixFormsContextState() {
535
42
  const registrationsByFormId = /* @__PURE__ */ new Map();
536
43
  const keysWarnedAbout = /* @__PURE__ */ new Set();
537
- function registerFieldChecks(formId, checks) {
44
+ function registerFieldChecks(formId, checks, options = {}) {
538
45
  const canonical = canonicalFormId(formId);
539
46
  if (!canonical) {
540
47
  warnAboutNonFormIdKey(formId);
541
48
  return () => {
542
49
  };
543
50
  }
544
- registrationsByFormId.set(canonical, [...registrationsFor(canonical), checks]);
51
+ const registration = { checks, messages: options.messages ?? {} };
52
+ registrationsByFormId.set(canonical, [...registrationsFor(canonical), registration]);
545
53
  return () => {
546
54
  registrationsByFormId.set(
547
55
  canonical,
548
- registrationsFor(canonical).filter((registered) => registered !== checks)
56
+ registrationsFor(canonical).filter((registered) => registered !== registration)
549
57
  );
550
58
  };
551
59
  }
@@ -594,8 +102,24 @@ makeJayInit().withClient(async () => {
594
102
  provideWixFormsContext();
595
103
  console.log("[wix-forms] Client ready");
596
104
  });
597
- const getFormSummary = createActionCaller("wixForms.getFormSummary", "GET");
105
+ createActionCaller("wixForms.getFormSummary", "GET");
598
106
  const submitForm = createActionCaller("wixForms.submitForm", "POST");
107
+ const ADDRESS_PARTS = [
108
+ "country",
109
+ "addressLine",
110
+ "addressLine2",
111
+ "streetName",
112
+ "streetNumber",
113
+ "city",
114
+ "subdivision",
115
+ "postalCode"
116
+ ];
117
+ const LAYOUT_PARTS = ADDRESS_PARTS.filter(
118
+ (part) => part !== "country"
119
+ );
120
+ function isLayoutPart(value) {
121
+ return typeof value === "string" && LAYOUT_PARTS.includes(value);
122
+ }
599
123
  var FieldRule = /* @__PURE__ */ ((FieldRule2) => {
600
124
  FieldRule2[FieldRule2["NONE"] = 0] = "NONE";
601
125
  FieldRule2[FieldRule2["REQUIRED"] = 1] = "REQUIRED";
@@ -2797,28 +2321,192 @@ function isFromAllowedCountry(number, allowedCountries) {
2797
2321
  if (number.country) return allowedCountries.includes(number.country);
2798
2322
  return callingCodesOf(allowedCountries).includes(`+${number.countryCallingCode}`);
2799
2323
  }
2800
- function validateFormSummaryField(field, value) {
2801
- const trimmed = (value ?? "").trim();
2802
- if (field.required && !trimmed) {
2803
- return `${field.label} is required.`;
2324
+ const ADDRESS_TEMPLATE_IDS = {
2325
+ MLA_COMMON: "0d5dcb6d-1403-4b80-b73e-6d90a2245561"
2326
+ };
2327
+ const COMMON_TEMPLATE_ID = ADDRESS_TEMPLATE_IDS.MLA_COMMON;
2328
+ const addressMessages = {
2329
+ required: (label) => `${label} is required.`,
2330
+ countryNotOffered: () => "Choose a country from the list.",
2331
+ tooManyCharacters: (label, maxLength) => `${label} must be at most ${maxLength} characters.`,
2332
+ /** Correct only for `^.{0,50}$`, the one pattern every template uses (pinned by test A1). */
2333
+ patternFailed: (label) => `${label} is too long.`,
2334
+ notInList: (label) => `Choose a ${label} from the list.`,
2335
+ cannotAccept: (countryName) => `This address cannot be accepted for ${countryName}. Please contact us.`,
2336
+ checkValue: (label) => `${label}: please check this value.`
2337
+ };
2338
+ function layoutOf(spec, country) {
2339
+ if (!country) return void 0;
2340
+ const base = spec.layouts[spec.templateOf[country] ?? COMMON_TEMPLATE_ID] ?? spec.layouts[COMMON_TEMPLATE_ID];
2341
+ if (!base) return void 0;
2342
+ const withReveals = withRevealedParts(spec, base, spec.revealedPartsOf[country] ?? []);
2343
+ const learned = spec.subdivisionsOf[country];
2344
+ return learned && hasPart(withReveals, "subdivision") && !withReveals.subdivisions?.length ? { ...withReveals, subdivisions: learned } : withReveals;
2345
+ }
2346
+ function withRevealedParts(spec, layout, revealed) {
2347
+ const missing = revealed.filter((part) => !hasPart(layout, part));
2348
+ if (!missing.length) return layout;
2349
+ const parts = [...layout.parts];
2350
+ for (const part of missing) {
2351
+ const added = { part, label: spec.partLabels[part], required: true };
2352
+ const order = ADDRESS_PARTS.indexOf(part);
2353
+ const before = parts.findIndex((existing) => ADDRESS_PARTS.indexOf(existing.part) > order);
2354
+ parts.splice(before === -1 ? parts.length : before, 0, added);
2355
+ }
2356
+ const subdivisionLabel = missing.includes("subdivision") ? spec.partLabels.subdivision : layout.subdivisionLabel;
2357
+ return { ...layout, parts, ...subdivisionLabel ? { subdivisionLabel } : {} };
2358
+ }
2359
+ function hasPart(layout, part) {
2360
+ return layout.parts.some((spec) => spec.part === part);
2361
+ }
2362
+ function withLearnedFacts(spec, facts) {
2363
+ const offered = new Set(spec.countries.map((country) => country.value));
2364
+ const subdivisionsOf = { ...spec.subdivisionsOf };
2365
+ const revealedPartsOf = { ...spec.revealedPartsOf };
2366
+ let changed = false;
2367
+ for (const [country, options] of Object.entries(facts.subdivisionsOf ?? {})) {
2368
+ if (!offered.has(country) || !options?.length || isListedByTemplate(spec, country))
2369
+ continue;
2370
+ subdivisionsOf[country] = options;
2371
+ changed = true;
2372
+ }
2373
+ for (const [country, parts] of Object.entries(facts.revealedPartsOf ?? {})) {
2374
+ const known = (parts ?? []).filter(isLayoutPart);
2375
+ if (!offered.has(country) || !known.length) continue;
2376
+ revealedPartsOf[country] = [.../* @__PURE__ */ new Set([...revealedPartsOf[country] ?? [], ...known])];
2377
+ changed = true;
2378
+ }
2379
+ return changed ? { ...spec, subdivisionsOf, revealedPartsOf } : spec;
2380
+ }
2381
+ function isListedByTemplate(spec, country) {
2382
+ const layout = spec.layouts[spec.templateOf[country] ?? COMMON_TEMPLATE_ID];
2383
+ return Boolean(layout?.subdivisions?.length);
2384
+ }
2385
+ function initialAddressValue(spec) {
2386
+ return spec.initialCountry ? { country: spec.initialCountry } : {};
2387
+ }
2388
+ function nextAddressValue(spec, current, part, value) {
2389
+ if (part !== "country" || value === current.country) return { ...current, [part]: value };
2390
+ const layout = layoutOf(spec, value);
2391
+ const previous = layoutOf(spec, current.country);
2392
+ const next = { country: value };
2393
+ for (const shown of layout?.parts ?? []) {
2394
+ const kept = current[shown.part];
2395
+ if (kept === void 0 || previous && !hasPart(previous, shown.part)) continue;
2396
+ if (shown.part === "subdivision" && !isListed(layout, kept)) continue;
2397
+ next[shown.part] = kept;
2398
+ }
2399
+ return next;
2400
+ }
2401
+ function isListed(layout, code) {
2402
+ return (layout.subdivisions ?? []).some((option) => option.value === code);
2403
+ }
2404
+ function isBlankAddress(value) {
2405
+ return ADDRESS_PARTS.every((part) => part === "country" || !value[part]?.trim());
2406
+ }
2407
+ function toWixAddress(spec, value) {
2408
+ if (isBlankAddress(value) && !value.country?.trim()) return void 0;
2409
+ const country = value.country?.trim().toUpperCase();
2410
+ const payload = country ? { country } : {};
2411
+ for (const { part } of layoutOf(spec, country ?? "")?.parts ?? []) {
2412
+ const trimmed = value[part]?.trim();
2413
+ if (trimmed) payload[part] = trimmed;
2804
2414
  }
2805
- if (!trimmed) {
2806
- return "";
2415
+ if (!country) {
2416
+ for (const part of ADDRESS_PARTS) {
2417
+ const trimmed = value[part]?.trim();
2418
+ if (trimmed) payload[part] = trimmed;
2419
+ }
2420
+ }
2421
+ return payload;
2422
+ }
2423
+ function validateAddressValue(spec, value, required) {
2424
+ const address = value ?? {};
2425
+ if (!required && isBlankAddress(address)) return {};
2426
+ const country = address.country?.trim().toUpperCase();
2427
+ if (!country) return { country: addressMessages.required(spec.partLabels.country) };
2428
+ if (!spec.countries.some((option) => option.value === country)) {
2429
+ return { country: addressMessages.countryNotOffered() };
2430
+ }
2431
+ const errors = {};
2432
+ const layout = layoutOf(spec, country);
2433
+ const isLearnedList = Boolean(spec.subdivisionsOf[country]?.length);
2434
+ for (const partSpec of layout.parts) {
2435
+ const message = partError(
2436
+ layout,
2437
+ partSpec,
2438
+ address[partSpec.part]?.trim() ?? "",
2439
+ isLearnedList
2440
+ );
2441
+ if (message) errors[partSpec.part] = message;
2807
2442
  }
2808
- if (field.type === "EMAIL" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
2809
- return "Please enter a valid email address.";
2443
+ return errors;
2444
+ }
2445
+ function partError(layout, partSpec, value, isLearnedList) {
2446
+ if (!value && partSpec.required && partSpec.part === "subdivision" && isLearnedList) {
2447
+ return addressMessages.notInList(layout.subdivisionLabel ?? partSpec.label);
2810
2448
  }
2811
- if (field.type === "URL" && !/^https?:\/\/.+/.test(trimmed)) {
2812
- return "Please enter a valid URL.";
2449
+ if (!value) return partSpec.required ? addressMessages.required(partSpec.label) : "";
2450
+ if (partSpec.maxLength !== void 0 && value.length > partSpec.maxLength) {
2451
+ return addressMessages.tooManyCharacters(partSpec.label, partSpec.maxLength);
2813
2452
  }
2814
- if (field.type === "PHONE" && !/^[+()\-\s\d]{7,}$/.test(trimmed)) {
2815
- return "Please enter a valid phone number.";
2453
+ if (partSpec.pattern && !matchesPattern(partSpec.pattern, value)) {
2454
+ return addressMessages.patternFailed(partSpec.label);
2816
2455
  }
2817
- if (field.type === "NUMBER" && !/^-?\d+(\.\d+)?$/.test(trimmed)) {
2818
- return "Please enter a valid number.";
2456
+ if (partSpec.part === "subdivision" && layout.subdivisions?.length && !isListed(layout, value)) {
2457
+ return addressMessages.notInList(layout.subdivisionLabel ?? partSpec.label);
2819
2458
  }
2820
2459
  return "";
2821
2460
  }
2461
+ function matchesPattern(pattern, value) {
2462
+ try {
2463
+ return new RegExp(pattern).test(value);
2464
+ } catch {
2465
+ return true;
2466
+ }
2467
+ }
2468
+ function readAddressValue(raw) {
2469
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
2470
+ const value = {};
2471
+ for (const part of ADDRESS_PARTS) {
2472
+ const entry = Object.hasOwn(raw, part) ? raw[part] : void 0;
2473
+ if (typeof entry === "string") value[part] = entry;
2474
+ }
2475
+ return value;
2476
+ }
2477
+ function addressErrorKey(target, part) {
2478
+ return `${target}/${part}`;
2479
+ }
2480
+ function splitErrorKey(key) {
2481
+ const slash = key.lastIndexOf("/");
2482
+ const part = key.slice(slash + 1);
2483
+ if (slash <= 0 || !ADDRESS_PARTS.includes(part)) return { target: key };
2484
+ return { target: key.slice(0, slash), part };
2485
+ }
2486
+ function isAddressValue(value) {
2487
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2488
+ }
2489
+ function countryNameOf(spec, country) {
2490
+ const code = country?.toUpperCase() ?? "";
2491
+ return spec.countries.find((option) => option.value === code)?.label ?? code;
2492
+ }
2493
+ function fieldErrorsOf(field, value) {
2494
+ if (field.inputType === "address" && field.address) {
2495
+ const normalised = toWixAddress(field.address, isAddressValue(value) ? value : {});
2496
+ const errors = validateAddressValue(field.address, normalised, field.required);
2497
+ return Object.fromEntries(
2498
+ Object.entries(errors).map(([part, message2]) => [
2499
+ addressErrorKey(field.target, part),
2500
+ message2
2501
+ ])
2502
+ );
2503
+ }
2504
+ const message = validateFormField(field, value);
2505
+ return message ? { [field.target]: message } : {};
2506
+ }
2507
+ function validateFormField(field, value) {
2508
+ return checkFormField(field, value).message;
2509
+ }
2822
2510
  function checkFormField(field, value) {
2823
2511
  if (field.inputType === "checkbox") {
2824
2512
  return field.required && value !== true ? requiredFailure(field) : PASSED$1;
@@ -2827,6 +2515,7 @@ function checkFormField(field, value) {
2827
2515
  const empty = !Array.isArray(value) || value.length === 0;
2828
2516
  return field.required && empty ? requiredFailure(field) : PASSED$1;
2829
2517
  }
2518
+ if (field.inputType === "address") return checkAddressField(field, value);
2830
2519
  const trimmed = (typeof value === "string" ? value : "").trim();
2831
2520
  if (field.required && !trimmed) {
2832
2521
  return requiredFailure(field);
@@ -2837,6 +2526,14 @@ function checkFormField(field, value) {
2837
2526
  return checkTextRules(field, trimmed);
2838
2527
  }
2839
2528
  const PASSED$1 = { rule: FieldRule.NONE, message: "" };
2529
+ function checkAddressField(field, value) {
2530
+ const [message] = Object.values(fieldErrorsOf(field, value));
2531
+ if (!message) return PASSED$1;
2532
+ return {
2533
+ rule: message.endsWith(" is required.") ? FieldRule.REQUIRED : FieldRule.PATTERN,
2534
+ message
2535
+ };
2536
+ }
2840
2537
  function requiredFailure(field) {
2841
2538
  return failure(FieldRule.REQUIRED, field);
2842
2539
  }
@@ -2856,7 +2553,7 @@ function defaultFieldMessage(rule, field) {
2856
2553
  case FieldRule.URL:
2857
2554
  return "Please enter a valid URL.";
2858
2555
  case FieldRule.PHONE:
2859
- return "Please enter a valid phone number.";
2556
+ return INVALID_PHONE_MESSAGE;
2860
2557
  case FieldRule.PATTERN:
2861
2558
  return `${field.label} is not in the expected format.`;
2862
2559
  case FieldRule.PHONE_COUNTRY:
@@ -2865,6 +2562,7 @@ function defaultFieldMessage(rule, field) {
2865
2562
  return void 0;
2866
2563
  }
2867
2564
  }
2565
+ const INVALID_PHONE_MESSAGE = "Please enter a valid phone number.";
2868
2566
  function phoneCountryMessage(allowedCountries) {
2869
2567
  if (!allowedCountries?.length) return "Please include the country code, starting with +.";
2870
2568
  const codes = callingCodesOf(allowedCountries).join(", ");
@@ -2902,7 +2600,51 @@ function checkPattern(field, trimmed) {
2902
2600
  return PASSED$1;
2903
2601
  }
2904
2602
  }
2603
+ const BLUR_ANNOUNCE_DELAY_MS = 0;
2604
+ const REPEAT_MARKER = " ";
2605
+ function distinctFromLastWrite(text, lastWritten) {
2606
+ return lastWritten === text ? text + REPEAT_MARKER : text;
2607
+ }
2608
+ function createBlurAnnouncer(options) {
2609
+ const { setStatusMessage, delayMs = BLUR_ANNOUNCE_DELAY_MS } = options;
2610
+ let pendingTimer;
2611
+ let pendingTarget;
2612
+ let owner;
2613
+ let lastWritten;
2614
+ function clearPending() {
2615
+ clearTimeout(pendingTimer);
2616
+ pendingTimer = void 0;
2617
+ pendingTarget = void 0;
2618
+ }
2619
+ return {
2620
+ announce(target, text) {
2621
+ clearPending();
2622
+ setStatusMessage("");
2623
+ owner = void 0;
2624
+ pendingTarget = target;
2625
+ pendingTimer = setTimeout(() => {
2626
+ pendingTimer = void 0;
2627
+ pendingTarget = void 0;
2628
+ lastWritten = distinctFromLastWrite(text, lastWritten);
2629
+ setStatusMessage(lastWritten);
2630
+ owner = target;
2631
+ }, delayMs);
2632
+ },
2633
+ withdraw(target) {
2634
+ if (pendingTarget === target) clearPending();
2635
+ if (owner === target) {
2636
+ owner = void 0;
2637
+ setStatusMessage("");
2638
+ }
2639
+ },
2640
+ cancel() {
2641
+ clearPending();
2642
+ owner = void 0;
2643
+ }
2644
+ };
2645
+ }
2905
2646
  const PASSED = { rule: FieldRule.NONE, message: "" };
2647
+ const UNWORDABLE_RULES = /* @__PURE__ */ new Set([FieldRule.NONE, FieldRule.CUSTOM, FieldRule.HOOK]);
2906
2648
  function createPageCheckRunner(formId, fields) {
2907
2649
  const visibleTargets = new Set(
2908
2650
  fields.filter((field) => !field.hidden).map((field) => field.target)
@@ -2911,9 +2653,13 @@ function createPageCheckRunner(formId, fields) {
2911
2653
  const registrationsScanned = /* @__PURE__ */ new WeakSet();
2912
2654
  const checksLoggedAbout = /* @__PURE__ */ new WeakSet();
2913
2655
  function warnAboutUnknownTargets(registrations) {
2914
- const unscanned = registrations.filter((checks) => !registrationsScanned.has(checks));
2915
- unscanned.forEach((checks) => registrationsScanned.add(checks));
2916
- for (const target of unscanned.flatMap((checks) => Object.keys(checks))) {
2656
+ const unscanned = registrations.filter((record) => !registrationsScanned.has(record));
2657
+ unscanned.forEach((record) => registrationsScanned.add(record));
2658
+ const targets = unscanned.flatMap((record) => [
2659
+ ...Object.keys(record.checks),
2660
+ ...Object.keys(record.messages)
2661
+ ]);
2662
+ for (const target of targets) {
2917
2663
  if (visibleTargets.has(target) || targetsWarnedAbout.has(target)) continue;
2918
2664
  targetsWarnedAbout.add(target);
2919
2665
  console.warn(
@@ -2936,13 +2682,24 @@ function createPageCheckRunner(formId, fields) {
2936
2682
  return void 0;
2937
2683
  }
2938
2684
  }
2939
- return (field, value, values) => {
2685
+ function currentRegistrations() {
2940
2686
  const context = useGlobalContext(WIX_FORMS_CONTEXT);
2941
- if (!context) return PASSED;
2942
- const registrations = registeredFieldChecks(context, formId);
2687
+ if (!context) return [];
2688
+ const registrations = registeredFields(context, formId);
2943
2689
  warnAboutUnknownTargets(registrations);
2944
- for (const checks of registrations) {
2945
- const fieldChecks = Object.prototype.hasOwnProperty.call(checks, field.target) ? checks[field.target] : [];
2690
+ return registrations;
2691
+ }
2692
+ const pageWordingFor = (field, rule) => {
2693
+ if (UNWORDABLE_RULES.has(rule)) return void 0;
2694
+ for (const { messages } of currentRegistrations()) {
2695
+ const wording = ownEntry(messages, field.target)?.[rule];
2696
+ if (typeof wording === "string" && wording) return wording;
2697
+ }
2698
+ return void 0;
2699
+ };
2700
+ const runPageChecks = (field, value, values) => {
2701
+ for (const { checks } of currentRegistrations()) {
2702
+ const fieldChecks = ownEntry(checks, field.target);
2946
2703
  for (const check of Array.isArray(fieldChecks) ? fieldChecks : []) {
2947
2704
  const message = runCheck(check, value, values);
2948
2705
  if (typeof message === "string" && message) {
@@ -2952,6 +2709,10 @@ function createPageCheckRunner(formId, fields) {
2952
2709
  }
2953
2710
  return PASSED;
2954
2711
  };
2712
+ return { runPageChecks, pageWordingFor };
2713
+ }
2714
+ function ownEntry(record, key) {
2715
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : void 0;
2955
2716
  }
2956
2717
  function createSubmitOutcomeReporter(formId) {
2957
2718
  const reportedFormId = canonicalFormId(formId) ?? formId;
@@ -2994,7 +2755,15 @@ function presentSubmitRejection(result2, fields) {
2994
2755
  const statusLines = result2.message ? [result2.message] : [];
2995
2756
  for (const [target, message] of Object.entries(result2.fieldErrors ?? {})) {
2996
2757
  const field = fields.find((candidate) => candidate.target === target);
2997
- if (field && !field.hidden) {
2758
+ const addressTarget = splitErrorKey(target).target;
2759
+ const addressField = fields.find(
2760
+ (candidate) => candidate.inputType === "address" && candidate.target === addressTarget
2761
+ );
2762
+ if (addressField && target !== addressTarget) {
2763
+ view.errorByTarget[target] = message;
2764
+ view.invalidByTarget[target] = true;
2765
+ view.ruleByTarget[target] = FieldRule.SERVER;
2766
+ } else if (field && !field.hidden) {
2998
2767
  const rule = serverRuleOf(result2, target);
2999
2768
  view.errorByTarget[target] = serverFieldMessage(rule, field, message);
3000
2769
  view.invalidByTarget[target] = true;
@@ -3009,6 +2778,22 @@ function presentSubmitRejection(result2, fields) {
3009
2778
  }
3010
2779
  return view;
3011
2780
  }
2781
+ function learnedAddressSpecs(result2, fields) {
2782
+ const view = { addressSpecs: {}, clearedSubdivisions: [] };
2783
+ for (const field of fields) {
2784
+ const country = result2.factsCountry?.[field.target];
2785
+ if (field.inputType !== "address" || !field.address || !country) continue;
2786
+ const options = result2.fieldOptions?.[`${field.target}/subdivision`];
2787
+ const revealed = result2.revealedParts?.[field.target];
2788
+ if (!options && !revealed) continue;
2789
+ view.addressSpecs[field.target] = withLearnedFacts(field.address, {
2790
+ ...options ? { subdivisionsOf: { [country]: options } } : {},
2791
+ ...revealed ? { revealedPartsOf: { [country]: revealed } } : {}
2792
+ });
2793
+ if (options) view.clearedSubdivisions.push(field.target);
2794
+ }
2795
+ return view;
2796
+ }
3012
2797
  function serverRuleOf(result2, target) {
3013
2798
  if (result2.fromHook) return FieldRule.HOOK;
3014
2799
  return result2.fieldRules?.[target] ?? FieldRule.SERVER;
@@ -3034,16 +2819,28 @@ function toSitePath(candidate) {
3034
2819
  function emptyValueFor(field) {
3035
2820
  if (field.inputType === "checkbox") return false;
3036
2821
  if (field.inputType === "multiselect") return [];
2822
+ if (field.inputType === "address")
2823
+ return field.address ? initialAddressValue(field.address) : {};
3037
2824
  return "";
3038
2825
  }
3039
2826
  function projectSubmissionValues(fields, store) {
3040
2827
  const values = {};
3041
2828
  for (const field of fields) {
3042
2829
  const raw = field.target in store ? store[field.target] : emptyValueFor(field);
2830
+ if (field.inputType === "address") {
2831
+ const address = submittedAddressOf(field, raw);
2832
+ if (address) values[field.target] = address;
2833
+ continue;
2834
+ }
3043
2835
  values[field.target] = submittedValueOf(field, raw);
3044
2836
  }
3045
2837
  return values;
3046
2838
  }
2839
+ function submittedAddressOf(field, raw) {
2840
+ const address = isAddressValue(raw) ? raw : {};
2841
+ if (!field.required && isBlankAddress(address)) return void 0;
2842
+ return field.address ? toWixAddress(field.address, address) : void 0;
2843
+ }
3047
2844
  const TRIMMED_KINDS = /* @__PURE__ */ new Set(["text", "textarea", "email", "tel", "url"]);
3048
2845
  function submittedValueOf(field, raw) {
3049
2846
  const isTrimmed = !field.hidden && TRIMMED_KINDS.has(field.inputType) && typeof raw === "string";
@@ -3100,14 +2897,14 @@ function toPostedValues(fields, values) {
3100
2897
  for (const field of fields) {
3101
2898
  const value = posted[field.target];
3102
2899
  if (field.inputType !== "tel" || typeof value !== "string") continue;
3103
- posted[field.target] = postedPhone(value, field);
2900
+ posted[field.target] = postedPhone(value, field.phone);
3104
2901
  }
3105
2902
  return posted;
3106
2903
  }
3107
- function postedPhone(value, field) {
2904
+ function postedPhone(value, rules) {
3108
2905
  const trimmed = value.trim();
3109
2906
  if (!trimmed) return trimmed;
3110
- const phone = checkPhone(trimmed, field.phone);
2907
+ const phone = checkPhone(trimmed, rules);
3111
2908
  return phone.rule === FieldRule.NONE ? phone.e164 : value;
3112
2909
  }
3113
2910
  var __assign = function() {
@@ -3202,7 +2999,8 @@ function contractTagName(target) {
3202
2999
  const name = camelCase(target);
3203
3000
  return RESERVED_TAG_NAMES.has(name) ? `${name}Field` : name;
3204
3001
  }
3205
- function fieldToViewState(field, state) {
3002
+ function fieldToViewState(field, state, errorByTarget) {
3003
+ if (field.inputType === "address") return addressViewState(field, state.value, errorByTarget);
3206
3004
  const viewState = {
3207
3005
  label: field.label,
3208
3006
  required: field.required,
@@ -3233,12 +3031,16 @@ function fieldToViewState(field, state) {
3233
3031
  function buildFieldsViewState(fields, errorByTarget = {}, invalidByTarget = {}, valueByTarget = {}, ruleByTarget = {}) {
3234
3032
  const viewState = {};
3235
3033
  for (const field of fields) {
3236
- viewState[contractTagName(field.target)] = fieldToViewState(field, {
3237
- error: errorByTarget[field.target] ?? "",
3238
- invalid: invalidByTarget[field.target] ?? false,
3239
- errorRule: ruleByTarget[field.target] ?? FieldRule.NONE,
3240
- value: valueByTarget[field.target] ?? ""
3241
- });
3034
+ viewState[contractTagName(field.target)] = fieldToViewState(
3035
+ field,
3036
+ {
3037
+ error: errorByTarget[field.target] ?? "",
3038
+ invalid: invalidByTarget[field.target] ?? false,
3039
+ errorRule: ruleByTarget[field.target] ?? FieldRule.NONE,
3040
+ value: valueByTarget[field.target] ?? ""
3041
+ },
3042
+ errorByTarget
3043
+ );
3242
3044
  }
3243
3045
  return viewState;
3244
3046
  }
@@ -3266,6 +3068,51 @@ function submitStateOf(overrides) {
3266
3068
  if (overrides.submitFailure) return SubmitState.FAILED;
3267
3069
  return SubmitState.IDLE;
3268
3070
  }
3071
+ function addressViewState(field, value, errors = {}) {
3072
+ const spec = field.address;
3073
+ const address = isAddressValue(value) ? value : initialAddressValue(spec);
3074
+ const layout = layoutOf(spec, address.country);
3075
+ const errorOf = (part) => errors[addressErrorKey(field.target, part)] ?? "";
3076
+ const firstError = ADDRESS_PARTS.map(errorOf).find(Boolean) ?? "";
3077
+ const view = {
3078
+ label: field.label,
3079
+ required: field.required,
3080
+ error: firstError,
3081
+ invalid: Boolean(firstError),
3082
+ country: {
3083
+ label: spec.partLabels.country,
3084
+ value: address.country ?? "",
3085
+ error: errorOf("country"),
3086
+ invalid: Boolean(errorOf("country")),
3087
+ options: spec.countries
3088
+ }
3089
+ };
3090
+ for (const part of LAYOUT_PARTS) {
3091
+ view[part] = partViewState(part, layout, address, errorOf(part));
3092
+ }
3093
+ return view;
3094
+ }
3095
+ function partViewState(part, layout, address, error) {
3096
+ const position = layout?.parts.findIndex((candidate) => candidate.part === part) ?? -1;
3097
+ const partSpec = position >= 0 ? layout.parts[position] : void 0;
3098
+ const view = {
3099
+ shown: Boolean(partSpec),
3100
+ order: position + 1,
3101
+ required: partSpec?.required ?? false,
3102
+ label: partSpec?.label ?? "",
3103
+ value: partSpec ? address[part] ?? "" : "",
3104
+ error,
3105
+ invalid: Boolean(error)
3106
+ };
3107
+ if (part === "subdivision") {
3108
+ const options = partSpec ? layout?.subdivisions ?? [] : [];
3109
+ view.listed = options.length > 0;
3110
+ view.options = options;
3111
+ } else {
3112
+ view.maxLength = partSpec?.maxLength ?? 0;
3113
+ }
3114
+ return view;
3115
+ }
3269
3116
  function createSubmitFlight() {
3270
3117
  let generation = 0;
3271
3118
  return {
@@ -3322,13 +3169,24 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3322
3169
  const [submitFailure, setSubmitFailure] = createSignal(SubmitFailure.NONE);
3323
3170
  const [values, setValues] = createSignal({});
3324
3171
  const dirtyTargets = /* @__PURE__ */ new Set();
3172
+ const dirtyAddressParts = /* @__PURE__ */ new Set();
3325
3173
  let honeypotValue = "";
3326
3174
  const submitFlight = createSubmitFlight();
3327
3175
  const selectBaselineByTarget = /* @__PURE__ */ new Map();
3328
- const runPageChecks = createPageCheckRunner(carryForward.formId, carryForward.fields);
3176
+ const { runPageChecks, pageWordingFor } = createPageCheckRunner(carryForward.formId, carryForward.fields);
3177
+ const [addressSpecs, setAddressSpecs] = createSignal(Object.fromEntries(carryForward.fields.flatMap((field) => field.address ? [[field.target, field.address]] : [])));
3178
+ function currentFields() {
3179
+ const specs = addressSpecs();
3180
+ return carryForward.fields.map((field) => field.inputType === "address" ? { ...field, address: specs[field.target] } : field);
3181
+ }
3182
+ function currentField(target) {
3183
+ return currentFields().find((field) => field.target === target);
3184
+ }
3329
3185
  const reportSubmitOutcome = createSubmitOutcomeReporter(carryForward.formId);
3330
3186
  const reportSubmitStart = createSubmitStartReporter(carryForward.formId);
3331
3187
  const [isHandedOff, setIsHandedOff] = createSignal(false);
3188
+ const blurAnnouncer = createBlurAnnouncer({ setStatusMessage });
3189
+ createEffect(() => () => blurAnnouncer.cancel());
3332
3190
  function setBusy(value) {
3333
3191
  setIsSubmitting(value);
3334
3192
  if (!value)
@@ -3338,13 +3196,23 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3338
3196
  setValues((current) => ({ ...current, [target]: value }));
3339
3197
  }
3340
3198
  function readFormValues() {
3341
- return projectSubmissionValues(carryForward.fields, values());
3199
+ return projectSubmissionValues(currentFields(), values());
3342
3200
  }
3343
3201
  function checkField(field, value = values()[field.target] ?? emptyValueFor(field), allValues = readFormValues()) {
3344
3202
  const builtIn = checkFormField(field, value);
3345
- return builtIn.rule === FieldRule.NONE ? runPageChecks(field, submittedValueOf(field, value), allValues) : builtIn;
3203
+ if (builtIn.rule === FieldRule.NONE) {
3204
+ return runPageChecks(field, submittedValueOf(field, value), allValues);
3205
+ }
3206
+ return {
3207
+ rule: builtIn.rule,
3208
+ message: pageWordingFor(field, builtIn.rule) ?? builtIn.message
3209
+ };
3346
3210
  }
3347
3211
  function validateField(field) {
3212
+ if (field.inputType === "address") {
3213
+ showAddressErrors(currentField(field.target));
3214
+ return;
3215
+ }
3348
3216
  const { rule, message } = checkField(field);
3349
3217
  setErrorByTarget((current) => ({ ...current, [field.target]: message }));
3350
3218
  setInvalidByTarget((current) => ({ ...current, [field.target]: Boolean(message) }));
@@ -3354,9 +3222,67 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3354
3222
  setErrorByTarget((current) => ({ ...current, [field.target]: "" }));
3355
3223
  setInvalidByTarget((current) => ({ ...current, [field.target]: false }));
3356
3224
  setRuleByTarget((current) => ({ ...current, [field.target]: FieldRule.NONE }));
3225
+ blurAnnouncer.withdraw(field.target);
3226
+ }
3227
+ function withdrawIfFixed(field) {
3228
+ if (!errorByTarget()[field.target])
3229
+ blurAnnouncer.withdraw(field.target);
3230
+ }
3231
+ function showAddressErrors(field) {
3232
+ const errors = fieldErrorsOf(field, values()[field.target] ?? emptyValueFor(field));
3233
+ const keys = ADDRESS_PARTS.map((part) => addressErrorKey(field.target, part));
3234
+ const pick = (of) => Object.fromEntries(keys.map((key) => [key, of(key)]));
3235
+ setErrorByTarget((current) => ({ ...current, ...pick((key) => errors[key] ?? "") }));
3236
+ setInvalidByTarget((current) => ({ ...current, ...pick((key) => Boolean(errors[key])) }));
3237
+ setRuleByTarget((current) => ({
3238
+ ...current,
3239
+ ...pick((key) => errors[key] ? FieldRule.PATTERN : FieldRule.NONE)
3240
+ }));
3241
+ }
3242
+ function hasAddressError(target) {
3243
+ return ADDRESS_PARTS.some((part) => errorByTarget()[addressErrorKey(target, part)]);
3244
+ }
3245
+ function handleAddressInput(field, part, value) {
3246
+ dirtyTargets.add(field.target);
3247
+ dirtyAddressParts.add(addressErrorKey(field.target, part));
3248
+ const spec = currentField(field.target).address;
3249
+ const stored = values()[field.target];
3250
+ const current = isAddressValue(stored) ? stored : {};
3251
+ const next = nextAddressValue(spec, current, part, value);
3252
+ setFieldValue(field.target, next);
3253
+ if (part === "country")
3254
+ reflectToInput(field, next);
3255
+ if (hasAddressError(field.target))
3256
+ showAddressErrors(currentField(field.target));
3257
+ const countryChanged = part === "country" && value !== current.country;
3258
+ withdrawClearedAddressParts(currentField(field.target), countryChanged);
3259
+ }
3260
+ function withdrawClearedAddressParts(field, countryChanged) {
3261
+ const value = values()[field.target];
3262
+ const layout = layoutOf(field.address, isAddressValue(value) ? value.country : void 0);
3263
+ for (const part of ADDRESS_PARTS) {
3264
+ const key = addressErrorKey(field.target, part);
3265
+ const vanished = part !== "country" && !layout?.parts.some((shown) => shown.part === part);
3266
+ const switched = countryChanged && part === "subdivision";
3267
+ if (!errorByTarget()[key] || vanished || switched)
3268
+ blurAnnouncer.withdraw(key);
3269
+ }
3270
+ }
3271
+ function handleAddressBlur(field, part) {
3272
+ if (!(dirtyTargets.has(field.target) || hasAddressError(field.target)))
3273
+ return;
3274
+ const key = addressErrorKey(field.target, part);
3275
+ const wasShown = Boolean(errorByTarget()[key]);
3276
+ validateField(field);
3277
+ if (dirtyAddressParts.has(key) || wasShown)
3278
+ announceLeave(key);
3357
3279
  }
3358
3280
  function reflectToInput(field, value) {
3359
3281
  const fieldRef = refs[contractTagName(field.target)];
3282
+ if (field.inputType === "address") {
3283
+ reflectAddressInputs(fieldRef, value);
3284
+ return;
3285
+ }
3360
3286
  fieldRef?.input?.exec$((element) => {
3361
3287
  if (field.inputType === "checkbox") {
3362
3288
  element.checked = value === true;
@@ -3377,8 +3303,17 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3377
3303
  }
3378
3304
  }
3379
3305
  function handleNativeBlur(field) {
3380
- if (dirtyTargets.has(field.target) || errorByTarget()[field.target])
3381
- validateField(field);
3306
+ if (!(dirtyTargets.has(field.target) || errorByTarget()[field.target]))
3307
+ return;
3308
+ validateField(field);
3309
+ announceLeave(field.target);
3310
+ }
3311
+ function announceLeave(key) {
3312
+ const message = errorByTarget()[key];
3313
+ if (!message)
3314
+ blurAnnouncer.withdraw(key);
3315
+ else if (!isSubmitting() && !isSubmitted())
3316
+ blurAnnouncer.announce(key, message);
3382
3317
  }
3383
3318
  function handleNativeInput(field, event) {
3384
3319
  dirtyTargets.add(field.target);
@@ -3393,17 +3328,21 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3393
3328
  setFieldValue(field.target, value);
3394
3329
  reflectToInput(field, value);
3395
3330
  validateField(field);
3331
+ withdrawIfFixed(field);
3396
3332
  }
3397
3333
  function handleOptionToggle(field, change) {
3398
3334
  dirtyTargets.add(field.target);
3399
3335
  setFieldValue(field.target, toggleSelection(field, { current: values()[field.target], ...change }));
3400
3336
  validateField(field);
3337
+ withdrawIfFixed(field);
3401
3338
  }
3402
3339
  wireFieldEvents(refs, carryForward.fields, {
3403
3340
  onNativeInput: handleNativeInput,
3404
3341
  onNativeBlur: handleNativeBlur,
3405
3342
  onControl: handleControl,
3406
- onOptionToggle: handleOptionToggle
3343
+ onOptionToggle: handleOptionToggle,
3344
+ onAddressInput: handleAddressInput,
3345
+ onAddressBlur: handleAddressBlur
3407
3346
  });
3408
3347
  wireHoneypot(refs, (value) => {
3409
3348
  honeypotValue = value;
@@ -3413,8 +3352,16 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3413
3352
  void reactive.toBeClean().then(work);
3414
3353
  }
3415
3354
  afterRemount(() => wireNativeFormSubmit(refs, submit));
3355
+ afterRemount(reflectAddressFields);
3416
3356
  afterRemount(() => void seedAndReflect().then(captureSelectBaselines));
3417
3357
  afterRemount(() => watchControlValues(refs, carryForward.fields, seedAndReflect));
3358
+ function reflectAddressFields() {
3359
+ for (const field of carryForward.fields) {
3360
+ if (field.inputType !== "address")
3361
+ continue;
3362
+ reflectToInput(field, values()[field.target] ?? emptyValueFor(field));
3363
+ }
3364
+ }
3418
3365
  async function seedAndReflect() {
3419
3366
  const changedTargets = await seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
3420
3367
  for (const field of carryForward.fields) {
@@ -3447,30 +3394,33 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3447
3394
  }
3448
3395
  function resetForm() {
3449
3396
  submitFlight.invalidate();
3450
- setValues(emptyStoreFor(carryForward.fields));
3397
+ setValues(emptyStoreFor(currentFields()));
3451
3398
  setErrorByTarget({});
3452
3399
  setInvalidByTarget({});
3453
3400
  setRuleByTarget({});
3401
+ blurAnnouncer.cancel();
3454
3402
  setStatusMessage("");
3455
3403
  setSubmitFailure(SubmitFailure.NONE);
3456
3404
  setIsSubmitted(false);
3457
3405
  setBusy(false);
3458
3406
  dirtyTargets.clear();
3407
+ dirtyAddressParts.clear();
3459
3408
  honeypotValue = "";
3460
3409
  clearNativeInputsAfterRemount();
3461
3410
  afterRemount(() => focusFirstFieldInput(refs, carryForward.fields, () => true));
3462
3411
  }
3463
3412
  function showSubmitted() {
3413
+ blurAnnouncer.cancel();
3464
3414
  setValues((current) => trimTextValues(carryForward.fields, current));
3465
3415
  setIsSubmitted(true);
3466
3416
  afterRemount(() => void refs.confirmation?.exec$((element) => element.focus()));
3467
3417
  }
3468
3418
  function showFieldErrors(errors) {
3469
- focusFirstFieldInput(refs, carryForward.fields, (field) => Boolean(errors[field.target]));
3419
+ focusFirstFieldInput(refs, carryForward.fields, (field) => Boolean(errors[field.target]) || Object.keys(errors).some((key) => splitErrorKey(key).target === field.target), errors);
3470
3420
  }
3471
3421
  function clearNativeInputsAfterRemount() {
3472
3422
  afterRemount(() => {
3473
- for (const field of carryForward.fields) {
3423
+ for (const field of currentFields()) {
3474
3424
  reflectToInput(field, emptyValueFor(field));
3475
3425
  }
3476
3426
  selectBaselineByTarget.clear();
@@ -3498,24 +3448,32 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3498
3448
  if (event.persisted)
3499
3449
  setBusy(false);
3500
3450
  });
3451
+ window.addEventListener("pagehide", () => blurAnnouncer.cancel());
3501
3452
  }
3502
3453
  async function submit() {
3503
3454
  if (isSubmitting())
3504
3455
  return;
3456
+ blurAnnouncer.cancel();
3505
3457
  setStatusMessage("");
3506
3458
  setSubmitFailure(SubmitFailure.NONE);
3507
3459
  setErrorByTarget({});
3508
3460
  setInvalidByTarget({});
3509
3461
  setRuleByTarget({});
3510
3462
  if (honeypotValue.trim()) {
3511
- showSubmitted();
3512
- reportSubmitOutcome({ outcome: "succeeded" });
3463
+ showHoneypotSuccess();
3513
3464
  return;
3514
3465
  }
3515
3466
  setBusy(true);
3516
3467
  const generation = submitFlight.begin();
3517
3468
  let hasHandedOff = false;
3518
3469
  try {
3470
+ const liveHoneypotValue = await readHoneypotDomValue(refs);
3471
+ if (!submitFlight.isCurrent(generation))
3472
+ return;
3473
+ if (liveHoneypotValue.trim()) {
3474
+ showHoneypotSuccess();
3475
+ return;
3476
+ }
3519
3477
  await reconcileNativeInputs();
3520
3478
  if (!submitFlight.isCurrent(generation))
3521
3479
  return;
@@ -3523,7 +3481,7 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3523
3481
  if (!submitFlight.isCurrent(generation))
3524
3482
  return;
3525
3483
  const submissionValues = readFormValues();
3526
- const clientFailures = validateVisibleFields(carryForward.fields, submissionValues, (field, value) => checkField(field, value, submissionValues));
3484
+ const clientFailures = expandAddressFailures(validateVisibleFields(currentFields(), submissionValues, (field, value) => checkField(field, value, submissionValues)), submissionValues);
3527
3485
  if (Object.keys(clientFailures).length) {
3528
3486
  showClientErrors(clientFailures);
3529
3487
  return;
@@ -3538,7 +3496,7 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3538
3496
  ensureSessionFresh,
3539
3497
  submitForm,
3540
3498
  formId: carryForward.formId,
3541
- submissionValues: toPostedValues(carryForward.fields, submissionValues),
3499
+ submissionValues: toPostedValues(currentFields(), submissionValues),
3542
3500
  presentSubmitResult,
3543
3501
  navigate: (path) => window.location.assign(path),
3544
3502
  onNetworkFailure: () => {
@@ -3552,6 +3510,24 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3552
3510
  setBusy(false);
3553
3511
  }
3554
3512
  }
3513
+ function expandAddressFailures(failures, submissionValues) {
3514
+ const expanded = {};
3515
+ for (const [target, failure2] of Object.entries(failures)) {
3516
+ const field = currentField(target);
3517
+ if (field?.inputType !== "address") {
3518
+ expanded[target] = failure2;
3519
+ continue;
3520
+ }
3521
+ for (const [key, message] of Object.entries(fieldErrorsOf(field, submissionValues[target] ?? {}))) {
3522
+ expanded[key] = { rule: failure2.rule, message };
3523
+ }
3524
+ }
3525
+ return expanded;
3526
+ }
3527
+ function showHoneypotSuccess() {
3528
+ showSubmitted();
3529
+ reportSubmitOutcome({ outcome: "succeeded" });
3530
+ }
3555
3531
  function showClientErrors(failures) {
3556
3532
  const targets = Object.keys(failures);
3557
3533
  const errors = Object.fromEntries(targets.map((target) => [target, failures[target].message]));
@@ -3566,10 +3542,18 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3566
3542
  fieldErrors: errors
3567
3543
  });
3568
3544
  }
3545
+ function inPageWording(rejection) {
3546
+ return Object.fromEntries(Object.entries(rejection.errorByTarget).map(([target, message]) => {
3547
+ const field = carryForward.fields.find((candidate) => candidate.target === target);
3548
+ const wording = field && pageWordingFor(field, rejection.ruleByTarget[target]);
3549
+ return [target, wording ?? message];
3550
+ }));
3551
+ }
3569
3552
  function presentSubmitResult(result2) {
3570
3553
  if (!result2.success) {
3571
- const rejection = presentSubmitRejection(result2, carryForward.fields);
3572
- setErrorByTarget(rejection.errorByTarget);
3554
+ const rejection = presentSubmitRejection(result2, currentFields());
3555
+ applyLearnedAddressSpecs(learnedAddressSpecs(result2, currentFields()));
3556
+ setErrorByTarget(inPageWording(rejection));
3573
3557
  setInvalidByTarget(rejection.invalidByTarget);
3574
3558
  setRuleByTarget(rejection.ruleByTarget);
3575
3559
  setStatusMessage(rejection.statusMessage);
@@ -3590,6 +3574,18 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3590
3574
  reportSubmitOutcome(redirectPath === void 0 ? { outcome: "succeeded" } : { outcome: "succeeded", redirectTo: redirectPath });
3591
3575
  return redirectPath;
3592
3576
  }
3577
+ function applyLearnedAddressSpecs(rejection) {
3578
+ if (!Object.keys(rejection.addressSpecs).length)
3579
+ return;
3580
+ setAddressSpecs((current) => ({ ...current, ...rejection.addressSpecs }));
3581
+ for (const target of rejection.clearedSubdivisions) {
3582
+ const current = values()[target];
3583
+ const next = { ...isAddressValue(current) ? current : {}, subdivision: "" };
3584
+ blurAnnouncer.withdraw(addressErrorKey(target, "subdivision"));
3585
+ setFieldValue(target, next);
3586
+ reflectToInput(currentField(target), next);
3587
+ }
3588
+ }
3593
3589
  function reportSubmitRejection(result2) {
3594
3590
  reportSubmitOutcome({
3595
3591
  outcome: "failed",
@@ -3600,7 +3596,7 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3600
3596
  });
3601
3597
  }
3602
3598
  return {
3603
- render: () => buildFormViewState(carryForward.fields, {
3599
+ render: () => buildFormViewState(currentFields(), {
3604
3600
  isSubmitting: isSubmitting(),
3605
3601
  isHandedOff: isHandedOff(),
3606
3602
  statusMessage: statusMessage(),
@@ -3614,11 +3610,38 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
3614
3610
  })
3615
3611
  };
3616
3612
  }
3613
+ function wireAddressEvents(fieldRef, field, handlers) {
3614
+ for (const part of ADDRESS_PARTS) {
3615
+ for (const channel of ["input", "text"]) {
3616
+ const ref = fieldRef?.[part]?.[channel];
3617
+ if (!ref)
3618
+ continue;
3619
+ const read = ({ event }) => handlers.onAddressInput(field, part, event.target.value ?? "");
3620
+ ref.oninput?.(read);
3621
+ ref.onchange?.(read);
3622
+ ref.onblur?.(() => handlers.onAddressBlur(field, part));
3623
+ }
3624
+ }
3625
+ }
3626
+ function reflectAddressInputs(fieldRef, value) {
3627
+ const address = isAddressValue(value) ? value : {};
3628
+ for (const part of ADDRESS_PARTS) {
3629
+ for (const channel of ["input", "text"]) {
3630
+ void fieldRef?.[part]?.[channel]?.exec$?.((element) => {
3631
+ element.value = address[part] ?? "";
3632
+ });
3633
+ }
3634
+ }
3635
+ }
3617
3636
  function wireFieldEvents(refs, fields, handlers) {
3618
3637
  for (const field of fields) {
3619
3638
  const fieldRef = refs[contractTagName(field.target)];
3620
3639
  if (!fieldRef)
3621
3640
  continue;
3641
+ if (field.inputType === "address") {
3642
+ wireAddressEvents(fieldRef, field, handlers);
3643
+ continue;
3644
+ }
3622
3645
  fieldRef.input?.oninput(({ event }) => handlers.onNativeInput(field, event));
3623
3646
  fieldRef.input?.onblur(() => handlers.onNativeBlur(field));
3624
3647
  fieldRef.control?.onclick(({ event }) => handlers.onControl(field, event));
@@ -3631,14 +3654,19 @@ function wireFieldEvents(refs, fields, handlers) {
3631
3654
  }
3632
3655
  }
3633
3656
  }
3634
- function focusFirstFieldInput(refs, fields, matches) {
3635
- const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && focusableRef(refs, candidate));
3657
+ function focusFirstFieldInput(refs, fields, matches, errors = {}) {
3658
+ const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && focusableRef(refs, candidate, errors));
3636
3659
  if (!field)
3637
3660
  return;
3638
- void focusableRef(refs, field).exec$((element) => element.focus());
3661
+ void focusableRef(refs, field, errors).exec$((element) => element.focus());
3639
3662
  }
3640
- function focusableRef(refs, field) {
3663
+ function focusableRef(refs, field, errors = {}) {
3641
3664
  const fieldRef = refs[contractTagName(field.target)];
3665
+ if (field.inputType === "address") {
3666
+ const part = ADDRESS_PARTS.find((candidate) => errors[addressErrorKey(field.target, candidate)]);
3667
+ const partRef = fieldRef?.[part ?? "country"];
3668
+ return partRef?.input ?? partRef?.text ?? fieldRef?.country?.input;
3669
+ }
3642
3670
  if (field.inputType === "multiselect") {
3643
3671
  const firstChip = fieldRef?.options?.toggle?.find(() => true);
3644
3672
  if (firstChip)
@@ -3693,7 +3721,7 @@ function watchControlValues(refs, fields, onControlValueChange) {
3693
3721
  }
3694
3722
  }
3695
3723
  function reconcilableFields(fields) {
3696
- return fields.filter((field) => !field.hidden && field.inputType !== "checkbox" && field.inputType !== "multiselect");
3724
+ return fields.filter((field) => !field.hidden && field.inputType !== "checkbox" && field.inputType !== "multiselect" && field.inputType !== "address");
3697
3725
  }
3698
3726
  function readBoundInputValue(refs, field) {
3699
3727
  const input = refs[contractTagName(field.target)]?.input;
@@ -3701,33 +3729,337 @@ function readBoundInputValue(refs, field) {
3701
3729
  return Promise.resolve(void 0);
3702
3730
  return input.exec$((element) => element.value);
3703
3731
  }
3704
- function wireHoneypot(refs, record) {
3705
- refs.honeypot?.oninput(({ event }) => {
3706
- record(event.target.value ?? "");
3732
+ async function readHoneypotDomValue(refs) {
3733
+ const input = refs.honeypot;
3734
+ if (!input?.exec$)
3735
+ return "";
3736
+ return await input.exec$((element) => element.value) ?? "";
3737
+ }
3738
+ function wireHoneypot(refs, record) {
3739
+ refs.honeypot?.oninput(({ event }) => {
3740
+ record(event.target.value ?? "");
3741
+ });
3742
+ }
3743
+ function readNativeValue(field, target) {
3744
+ if (field.inputType === "checkbox") {
3745
+ return target?.checked ?? false;
3746
+ }
3747
+ if (field.inputType === "multiselect") {
3748
+ const select = target;
3749
+ return select ? Array.from(select.selectedOptions).map((option) => option.value) : [];
3750
+ }
3751
+ const element = target;
3752
+ return element?.value ?? "";
3753
+ }
3754
+ function readControlValue(target) {
3755
+ const element = target;
3756
+ if (!element)
3757
+ return "";
3758
+ const dataValue = element.getAttribute?.("data-value");
3759
+ if (dataValue !== null && dataValue !== void 0) {
3760
+ return dataValue;
3761
+ }
3762
+ return element.value ?? "";
3763
+ }
3764
+ makeJayStackComponent().withProps().withInteractive(WixFormInteractive);
3765
+ function parseBookingFormViolations(responseBody) {
3766
+ const items = envelopeItems(responseBody, "formViolations");
3767
+ return uniqueViolations(
3768
+ items.map(
3769
+ (item) => locatedViolation(
3770
+ item.fieldName,
3771
+ item.ruleName,
3772
+ item.data?.allowedValues,
3773
+ item.description
3774
+ )
3775
+ )
3776
+ );
3777
+ }
3778
+ function envelopeItems(responseBody, member) {
3779
+ try {
3780
+ const parsed = JSON.parse(responseBody);
3781
+ const details = parsed?.details;
3782
+ const fieldViolations = details?.validationError?.fieldViolations ?? [];
3783
+ return [
3784
+ ...fieldViolations.flatMap((violation) => violation?.data?.[member] ?? []),
3785
+ ...details?.applicationError?.data?.[member] ?? []
3786
+ ];
3787
+ } catch {
3788
+ return [];
3789
+ }
3790
+ }
3791
+ function locatedViolation(key, ruleName, allowedValues, wixMessage) {
3792
+ if (!key) return void 0;
3793
+ const codes = (allowedValues ?? []).filter(
3794
+ (value) => typeof value === "string"
3795
+ );
3796
+ return {
3797
+ key,
3798
+ ruleName: ruleName ?? "",
3799
+ ...allowedValues ? { allowedValues: codes } : {},
3800
+ ...wixMessage ? { wixMessage } : {}
3801
+ };
3802
+ }
3803
+ function uniqueViolations(items) {
3804
+ const seen = /* @__PURE__ */ new Set();
3805
+ const unique = [];
3806
+ for (const item of items) {
3807
+ if (!item) continue;
3808
+ const identity = `${item.key}\0${item.ruleName}`;
3809
+ if (seen.has(identity)) continue;
3810
+ seen.add(identity);
3811
+ unique.push(item);
3812
+ }
3813
+ return unique;
3814
+ }
3815
+ function addressMessageFor(field, value, violation) {
3816
+ const { target, part } = splitErrorKey(violation.key);
3817
+ if (target !== field.target || !field.address) return addressMessages.checkValue(field.label);
3818
+ if (!part) {
3819
+ return violation.ruleName === "REQUIRED_VALUE_ERROR" ? addressMessages.required(field.label) : addressMessages.checkValue(field.label);
3820
+ }
3821
+ const spec = field.address;
3822
+ const layout = layoutOf(spec, value.country?.toUpperCase());
3823
+ const partSpec = layout?.parts.find((candidate) => candidate.part === part);
3824
+ const label = partSpec?.label ?? spec.partLabels[part];
3825
+ switch (violation.ruleName) {
3826
+ case "REQUIRED_VALUE_ERROR":
3827
+ return addressMessages.required(label);
3828
+ case "NOT_ALLOWED_VALUE_ERROR":
3829
+ if (part === "country") return addressMessages.countryNotOffered();
3830
+ return addressMessages.notInList(
3831
+ part === "subdivision" ? layout?.subdivisionLabel ?? label : label
3832
+ );
3833
+ case "MAX_LENGTH_ERROR":
3834
+ return partSpec?.maxLength === void 0 ? addressMessages.checkValue(label) : addressMessages.tooManyCharacters(label, partSpec.maxLength);
3835
+ case "INVALID_VALUE_FOR_PATTERN_ERROR":
3836
+ return addressMessages.patternFailed(label);
3837
+ case "UNKNOWN_VALUE_ERROR":
3838
+ return addressMessages.cannotAccept(countryNameOf(spec, value.country));
3839
+ default:
3840
+ return addressMessages.checkValue(label);
3841
+ }
3842
+ }
3843
+ const DRIFT_DOC = 'See "Address drift" in @jay-framework/wix-forms docs/01-setup-and-troubleshooting.md.';
3844
+ const driftLoggedByStore = /* @__PURE__ */ new WeakMap();
3845
+ function mapAddressViolations(input) {
3846
+ const result2 = {
3847
+ fieldErrors: {},
3848
+ fieldOptions: {},
3849
+ revealedParts: {},
3850
+ factsCountry: {},
3851
+ unhandled: []
3852
+ };
3853
+ for (const violation of input.violations) {
3854
+ const { target } = splitErrorKey(violation.key);
3855
+ const field = input.fields.find(
3856
+ (candidate) => candidate.target === target || violation.key.startsWith(`${candidate.target}/`)
3857
+ );
3858
+ if (!field?.address) result2.unhandled.push(violation);
3859
+ else mapOne(input, field, violation, result2);
3860
+ }
3861
+ return result2;
3862
+ }
3863
+ function mapOne(input, field, violation, result2) {
3864
+ var _a, _b, _c;
3865
+ const value = readAddressValue(input.values[field.target]);
3866
+ const country = value.country?.trim().toUpperCase() ?? "";
3867
+ const { part } = splitErrorKey(violation.key);
3868
+ const drift = (key) => logDrift(input, { key, ruleName: violation.ruleName, country, field });
3869
+ if (!part && violation.key !== field.target) {
3870
+ const key = addressErrorKey(field.target, "country");
3871
+ (_a = result2.fieldErrors)[key] ?? (_a[key] = addressMessageFor(field, value, {
3872
+ ...violation,
3873
+ key,
3874
+ ruleName: "UNKNOWN_VALUE_ERROR"
3875
+ }));
3876
+ drift(violation.key);
3877
+ return;
3878
+ }
3879
+ (_b = result2.fieldErrors)[_c = violation.key] ?? (_b[_c] = addressMessageFor(field, value, violation));
3880
+ if (!part || !country) return;
3881
+ const layout = layoutOf(field.address, country);
3882
+ const isShown = Boolean(layout?.parts.some((candidate) => candidate.part === part));
3883
+ if (violation.ruleName === "NOT_ALLOWED_VALUE_ERROR" && part === "subdivision") {
3884
+ learnSubdivisions(
3885
+ input,
3886
+ field,
3887
+ country,
3888
+ violation,
3889
+ result2,
3890
+ isTemplateListed(field, country),
3891
+ drift
3892
+ );
3893
+ } else if (violation.ruleName === "REQUIRED_VALUE_ERROR" && isLayoutPart(part) && !isShown) {
3894
+ input.facts.revealPart(country, part);
3895
+ result2.revealedParts[field.target] = [...result2.revealedParts[field.target] ?? [], part];
3896
+ result2.factsCountry[field.target] = country;
3897
+ drift(violation.key);
3898
+ } else if (violation.ruleName === "UNKNOWN_VALUE_ERROR") {
3899
+ drift(violation.key);
3900
+ }
3901
+ }
3902
+ function learnSubdivisions(input, field, country, violation, result2, isListed2, drift) {
3903
+ if (isListed2) {
3904
+ drift(violation.key);
3905
+ return;
3906
+ }
3907
+ if (!violation.allowedValues?.length) return;
3908
+ input.facts.learnSubdivisions(country, violation.allowedValues);
3909
+ const learned = input.facts.snapshot().subdivisionsOf?.[country];
3910
+ if (!learned) return;
3911
+ result2.fieldOptions[violation.key] = learned;
3912
+ result2.factsCountry[field.target] = country;
3913
+ }
3914
+ function isTemplateListed(field, country) {
3915
+ const spec = field.address;
3916
+ const base = spec.layouts[spec.templateOf[country] ?? COMMON_TEMPLATE_ID];
3917
+ return Boolean(base?.subdivisions?.length);
3918
+ }
3919
+ function logDrift(input, details) {
3920
+ const logged = driftLoggedByStore.get(input.facts) ?? /* @__PURE__ */ new Set();
3921
+ driftLoggedByStore.set(input.facts, logged);
3922
+ const identity = `${details.key}|${details.ruleName}|${details.country}`;
3923
+ if (logged.has(identity)) return;
3924
+ logged.add(identity);
3925
+ const templateId = layoutOf(details.field.address, details.country)?.templateId ?? "none";
3926
+ (input.log ?? console.warn)(
3927
+ `[wix-forms] address drift: Wix rejected ${details.key} (${details.ruleName}) for ${details.country || "no country"}; layout ${templateId}. ${DRIFT_DOC}`
3928
+ );
3929
+ }
3930
+ function paymentPreferenceFromService(service) {
3931
+ const opts = service.payment?.options ?? {};
3932
+ if (opts.online && !opts.inPerson) {
3933
+ return "ONLINE";
3934
+ }
3935
+ if (!opts.online && opts.inPerson) {
3936
+ return "OFFLINE";
3937
+ }
3938
+ return "ONLINE";
3939
+ }
3940
+ async function createBookingRecord(client, body) {
3941
+ return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
3942
+ }
3943
+ async function createBookingCart(client, bookingId, bookingAppId) {
3944
+ return wixFetch(client, "/ecom/v2/carts", {
3945
+ method: "POST",
3946
+ body: {
3947
+ catalogItems: [
3948
+ {
3949
+ quantity: 1,
3950
+ catalogReference: { catalogItemId: bookingId, appId: bookingAppId }
3951
+ }
3952
+ ],
3953
+ cart: { source: { channelType: "WEB" } }
3954
+ }
3955
+ });
3956
+ }
3957
+ async function calculateBookingCart(client, cartId) {
3958
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/calculate`, { method: "POST", body: {} });
3959
+ }
3960
+ async function placeBookingOrder(client, cartId) {
3961
+ const res = await wixFetch(
3962
+ client,
3963
+ `/ecom/v2/carts/${cartId}/place-order`,
3964
+ { method: "POST", body: {} }
3965
+ );
3966
+ return { orderId: res?.orderId };
3967
+ }
3968
+ async function createBookingRedirectSession(client, cartId, postFlowUrl) {
3969
+ return wixFetch(client, "/headless/v1/redirect-session", {
3970
+ method: "POST",
3971
+ body: {
3972
+ ecomCheckout: { checkoutId: cartId },
3973
+ callbacks: { postFlowUrl }
3974
+ }
3975
+ });
3976
+ }
3977
+ async function getBookingCheckoutUrl(client, cartId) {
3978
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/get-checkout-url`, {
3979
+ method: "POST",
3980
+ body: {}
3707
3981
  });
3708
3982
  }
3709
- function readNativeValue(field, target) {
3710
- if (field.inputType === "checkbox") {
3711
- return target?.checked ?? false;
3712
- }
3713
- if (field.inputType === "multiselect") {
3714
- const select = target;
3715
- return select ? Array.from(select.selectedOptions).map((option) => option.value) : [];
3716
- }
3717
- const element = target;
3718
- return element?.value ?? "";
3983
+ function toFormFieldView(view) {
3984
+ const { type, longText, ...field } = view;
3985
+ return { ...field, inputType: inputTypeOf(type, longText) };
3719
3986
  }
3720
- function readControlValue(target) {
3721
- const element = target;
3722
- if (!element)
3723
- return "";
3724
- const dataValue = element.getAttribute?.("data-value");
3725
- if (dataValue !== null && dataValue !== void 0) {
3726
- return dataValue;
3987
+ function inputTypeOf(type, longText) {
3988
+ switch (type) {
3989
+ case "STRING":
3990
+ return longText ? "textarea" : "text";
3991
+ case "EMAIL":
3992
+ return "email";
3993
+ case "PHONE":
3994
+ return "tel";
3995
+ case "URL":
3996
+ return "url";
3997
+ case "BOOLEAN":
3998
+ return "checkbox";
3999
+ case "ADDRESS":
4000
+ return "address";
4001
+ }
4002
+ }
4003
+ function blockingFieldLabels(projected) {
4004
+ return projected.unsupportedFields.filter((field) => field.required === true).map((field) => field.label);
4005
+ }
4006
+ function participantFieldErrors(fields, values) {
4007
+ const fieldErrors = {};
4008
+ for (const field of fields) {
4009
+ const formField = toFormFieldView(field);
4010
+ if (field.type === "ADDRESS") {
4011
+ Object.assign(
4012
+ fieldErrors,
4013
+ fieldErrorsOf(formField, readAddressValue(values[field.target]))
4014
+ );
4015
+ continue;
4016
+ }
4017
+ const empty = formField.inputType === "checkbox" ? false : "";
4018
+ const message = validateFormField(formField, values[field.target] ?? empty);
4019
+ if (message) fieldErrors[field.target] = message;
3727
4020
  }
3728
- return element.value ?? "";
4021
+ return fieldErrors;
3729
4022
  }
3730
- makeJayStackComponent().withProps().withInteractive(WixFormInteractive);
4023
+ function postedParticipantValues(fields, values) {
4024
+ return toPostedValues(fields.map(toFormFieldView), values);
4025
+ }
4026
+ function normalisedAddress(field, value) {
4027
+ const address = readAddressValue(value);
4028
+ if (!field.required && isBlankAddress(address)) return void 0;
4029
+ return toWixAddress(field.address, address);
4030
+ }
4031
+ var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
4032
+ ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
4033
+ ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
4034
+ ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
4035
+ return ServicesFailure2;
4036
+ })(ServicesFailure || {});
4037
+ var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
4038
+ SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
4039
+ SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
4040
+ return SlotsFailure2;
4041
+ })(SlotsFailure || {});
4042
+ var BookingState = /* @__PURE__ */ ((BookingState2) => {
4043
+ BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
4044
+ BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
4045
+ BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
4046
+ BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
4047
+ return BookingState2;
4048
+ })(BookingState || {});
4049
+ var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
4050
+ BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
4051
+ BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
4052
+ BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
4053
+ BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
4054
+ BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
4055
+ BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
4056
+ BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
4057
+ BookingFailure2[BookingFailure2["FORM_UNSUPPORTED"] = 7] = "FORM_UNSUPPORTED";
4058
+ return BookingFailure2;
4059
+ })(BookingFailure || {});
4060
+ const FORM_UNAVAILABLE_MESSAGE = "Could not load the participant form. Please try again later.";
4061
+ const RATE_LIMITED_MESSAGE = "Booking is busy right now. Please wait a minute and try again.";
4062
+ const RATE_LIMITED_AFTER_BOOKING_MESSAGE = "Your booking was received, but we couldn't open payment. Please check your email before booking again.";
3731
4063
  function describeBookingError(error) {
3732
4064
  const rawMessage = error instanceof Error ? error.message : "";
3733
4065
  if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
@@ -3748,28 +4080,259 @@ function describeBookingError(error) {
3748
4080
  message: "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site)."
3749
4081
  };
3750
4082
  }
4083
+ if (rawMessage.startsWith("Wix API 429")) {
4084
+ const message = rawMessage.includes("/ecom/") ? RATE_LIMITED_AFTER_BOOKING_MESSAGE : RATE_LIMITED_MESSAGE;
4085
+ return { failure: BookingFailure.UNKNOWN, message };
4086
+ }
3751
4087
  return {
3752
4088
  failure: BookingFailure.UNKNOWN,
3753
4089
  message: rawMessage || "Booking failed. Please try again."
3754
4090
  };
3755
4091
  }
4092
+ function describeUnsupportedForm(labels) {
4093
+ return `This booking form has a required field this site cannot show yet: ${labels.join(", ")}. Booking is disabled until the site is updated.`;
4094
+ }
3756
4095
  function bookingStateOf(state) {
3757
4096
  if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
3758
4097
  if (state.isBooking) return BookingState.BOOKING;
3759
4098
  if (state.isConfirmed) return BookingState.CONFIRMED;
3760
4099
  return BookingState.IDLE;
3761
4100
  }
3762
- const DEFAULT_PARTICIPANT_FIELDS = [
3763
- { target: "first_name", label: "First Name", type: "STRING", required: true },
3764
- { target: "last_name", label: "Last Name", type: "STRING", required: true },
3765
- { target: "email", label: "Email", type: "EMAIL", required: true }
3766
- ];
4101
+ async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
4102
+ try {
4103
+ const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
4104
+ const redirectUrl = redirectData.redirectSession?.fullUrl;
4105
+ if (redirectUrl) {
4106
+ return redirectUrl;
4107
+ }
4108
+ } catch (error) {
4109
+ if (!(error instanceof WixApiError) || error.status !== 400 && error.status !== 404) {
4110
+ throw error;
4111
+ }
4112
+ }
4113
+ const checkoutUrlData = await getBookingCheckoutUrl(wixClient, cartId);
4114
+ const checkoutUrl = checkoutUrlData.checkoutUrl;
4115
+ if (!checkoutUrl) {
4116
+ throw new Error(
4117
+ "Checkout redirect failed. Add your site origin to Allowed redirect domains in Wix Headless Settings, or publish the site so get-checkout-url can return a checkout page."
4118
+ );
4119
+ }
4120
+ return checkoutUrl;
4121
+ }
4122
+ function createUncheckedBooking(wixClient, config) {
4123
+ return async (input) => {
4124
+ const service = await getBookingServiceById(wixClient, input.serviceId);
4125
+ return bookAndCheckout(wixClient, config, service, input);
4126
+ };
4127
+ }
4128
+ async function bookAndCheckout(wixClient, config, rawService, input, checked) {
4129
+ const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
4130
+ rawService
4131
+ ) : "ONLINE");
4132
+ const slotData = {
4133
+ serviceId: input.serviceId,
4134
+ startDate: input.slot.localStartDate,
4135
+ endDate: input.slot.localEndDate,
4136
+ timezone: input.timezone,
4137
+ location: { locationType: "OWNER_BUSINESS" },
4138
+ // Any staff member of the configured staff resource type; without one, the slot's own (a class
4139
+ // session names its staff; Wix rejects an empty resource type id).
4140
+ ...config.staffResourceTypeId ? {
4141
+ resourceSelections: [
4142
+ {
4143
+ resourceTypeId: config.staffResourceTypeId,
4144
+ selectionMethod: "ANY_RESOURCE"
4145
+ }
4146
+ ]
4147
+ } : {}
4148
+ };
4149
+ if (input.serviceType === "APPOINTMENT") {
4150
+ slotData.scheduleId = input.slot.scheduleId;
4151
+ } else {
4152
+ slotData.eventId = input.slot.eventId;
4153
+ }
4154
+ let bookingData;
4155
+ try {
4156
+ bookingData = await createBookingRecord(wixClient, {
4157
+ booking: {
4158
+ bookedEntity: { slot: slotData },
4159
+ selectedPaymentOption: paymentPreference,
4160
+ totalParticipants: 1
4161
+ },
4162
+ formSubmission: input.formValues
4163
+ });
4164
+ } catch (error) {
4165
+ const invalid = checked ? invalidFromFormViolations(error, input, checked) : void 0;
4166
+ if (invalid) return invalid;
4167
+ throw error;
4168
+ }
4169
+ const bookingId = bookingData.booking.id;
4170
+ const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
4171
+ const cartId = cartData.cart.id;
4172
+ const calcData = await calculateBookingCart(wixClient, cartId);
4173
+ const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
4174
+ if (total > 0) {
4175
+ const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
4176
+ const redirectUrl = await resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl);
4177
+ return { outcome: "redirect", redirectUrl };
4178
+ }
4179
+ const { orderId } = await placeBookingOrder(wixClient, cartId);
4180
+ return { outcome: "confirmed", ...orderId ? { orderId } : {} };
4181
+ }
4182
+ function invalidFromFormViolations(error, input, checked) {
4183
+ var _a;
4184
+ if (!(error instanceof WixApiError) || error.status !== 400) return void 0;
4185
+ const violations = parseBookingFormViolations(error.responseBody);
4186
+ if (!violations.length) return void 0;
4187
+ const views = checked.fields.map(toFormFieldView);
4188
+ const mapped = mapAddressViolations({
4189
+ violations,
4190
+ fields: views.filter((field) => field.inputType === "address"),
4191
+ values: input.formValues,
4192
+ facts: checked.forms.learnedAddressFacts()
4193
+ });
4194
+ const fieldErrors = { ...mapped.fieldErrors };
4195
+ for (const violation of mapped.unhandled) {
4196
+ const field = views.find((candidate) => candidate.target === violation.key);
4197
+ fieldErrors[_a = violation.key] ?? (fieldErrors[_a] = field ? addressMessageFor(field, readAddressValue(void 0), violation) : violation.wixMessage ?? "Please check this value.");
4198
+ }
4199
+ return {
4200
+ outcome: "invalid",
4201
+ fieldErrors,
4202
+ ...Object.keys(mapped.fieldOptions).length ? { fieldOptions: mapped.fieldOptions } : {},
4203
+ ...Object.keys(mapped.revealedParts).length ? { revealedParts: mapped.revealedParts } : {},
4204
+ ...Object.keys(mapped.factsCountry).length ? { factsCountry: mapped.factsCountry } : {}
4205
+ };
4206
+ }
4207
+ function canBookOnline(features, type, step) {
4208
+ if (type === "COURSE") return step !== "form" || features.courses;
4209
+ return type === "CLASS" ? features.groups : features.appointments;
4210
+ }
4211
+ const WIX_BOOKINGS_CONTEXT = createJayContext("wix:bookings");
4212
+ function createWixBookingsContext(wixClient, config) {
4213
+ let settings;
4214
+ const readSettings = () => {
4215
+ if (!settings) {
4216
+ settings = wixFetch(
4217
+ wixClient,
4218
+ "/_api/bookings-settings/v2/settings?fields=FEATURES&fields=SITE_PROPERTIES"
4219
+ ).then((res) => res.bookingsSettings).catch(() => {
4220
+ settings = void 0;
4221
+ return void 0;
4222
+ });
4223
+ }
4224
+ return settings;
4225
+ };
4226
+ const createBooking2 = createUncheckedBooking(wixClient, config);
4227
+ const ownBookings = async (filter) => {
4228
+ const res = await wixFetch(wixClient, "/_api/bookings-reader/v2/extended-bookings/query", {
4229
+ method: "POST",
4230
+ body: {
4231
+ query: { filter, cursorPaging: { limit: 100 } },
4232
+ withBookingAllowedActions: false
4233
+ }
4234
+ }).catch(() => ({ extendedBookings: [] }));
4235
+ return (res.extendedBookings ?? []).map((e) => e.booking ?? {});
4236
+ };
4237
+ return {
4238
+ async features() {
4239
+ const f = (await readSettings())?.features ?? {};
4240
+ return {
4241
+ groups: Boolean(f.bookingsGroups?.enabled),
4242
+ appointments: Boolean(f.bookingsAppointments?.enabled),
4243
+ courses: Boolean(f.bookingsCourses?.enabled),
4244
+ payments: Boolean(f.bookingsPayments?.enabled)
4245
+ };
4246
+ },
4247
+ async timeZone() {
4248
+ return (await readSettings())?.siteProperties?.timeZone ?? "UTC";
4249
+ },
4250
+ async serviceBySlug(slug) {
4251
+ const res = await wixFetch(
4252
+ wixClient,
4253
+ "/bookings/v2/services/query",
4254
+ {
4255
+ method: "POST",
4256
+ body: {
4257
+ query: {
4258
+ filter: { "supportedSlugs.name": slug, hidden: false },
4259
+ paging: { limit: 1 }
4260
+ }
4261
+ }
4262
+ }
4263
+ );
4264
+ return res.services?.[0];
4265
+ },
4266
+ serviceById(id) {
4267
+ return getBookingServiceById(wixClient, id);
4268
+ },
4269
+ async timeSlots(query) {
4270
+ const res = await wixFetch(
4271
+ wixClient,
4272
+ "/_api/service-availability/v2/time-slots/event",
4273
+ {
4274
+ method: "POST",
4275
+ body: {
4276
+ serviceIds: query.serviceIds,
4277
+ timeZone: query.timeZone,
4278
+ fromLocalDate: query.fromLocalDate,
4279
+ toLocalDate: query.toLocalDate,
4280
+ includeNonBookable: query.includeNonBookable ?? true,
4281
+ ...query.maxSlotsPerDay ? { maxSlotsPerDay: query.maxSlotsPerDay } : {},
4282
+ eventFilter: {},
4283
+ cursorPaging: { limit: query.limit ?? 1e3 }
4284
+ }
4285
+ }
4286
+ );
4287
+ return res.timeSlots ?? [];
4288
+ },
4289
+ createBooking: createBooking2,
4290
+ async serviceBookings(serviceId) {
4291
+ return (await ownBookings({
4292
+ "bookedEntity.slot.serviceId": serviceId,
4293
+ status: { $in: ["CONFIRMED", "PENDING"] }
4294
+ })).filter((b) => b.id || b.startDate);
4295
+ },
4296
+ async bookingById(bookingId) {
4297
+ return (await ownBookings({ id: bookingId }))[0];
4298
+ },
4299
+ async orderById(orderId) {
4300
+ try {
4301
+ const res = await wixFetch(
4302
+ wixClient,
4303
+ `/ecom/v1/orders/${encodeURIComponent(orderId)}`
4304
+ );
4305
+ return res.order;
4306
+ } catch (error) {
4307
+ if (error instanceof WixApiError) return void 0;
4308
+ throw error;
4309
+ }
4310
+ }
4311
+ };
4312
+ }
4313
+ function provideWixBookingsContext(config) {
4314
+ const client = useGlobalContext(WIX_CLIENT_CONTEXT)?.client;
4315
+ if (!client) return void 0;
4316
+ const context = createWixBookingsContext(client, config);
4317
+ registerGlobalContext(WIX_BOOKINGS_CONTEXT, context);
4318
+ return context;
4319
+ }
4320
+ const init = makeJayInit().withClient(async ({ config }) => {
4321
+ provideWixBookingsContext(config);
4322
+ });
4323
+ const listServices = createActionCaller("wixBookings.listServices", "GET");
4324
+ const listSlots = createActionCaller("wixBookings.listSlots", "GET");
4325
+ const getParticipantForm = createActionCaller("wixBookings.getParticipantForm", "GET");
4326
+ const createBooking = createActionCaller("wixBookings.createBooking", "POST");
3767
4327
  function toBookingService(service) {
3768
4328
  return {
3769
4329
  ...service,
3770
4330
  type: service.type
3771
4331
  };
3772
4332
  }
4333
+ function toContractFormField(field) {
4334
+ return { target: field.target, label: field.label, type: field.type, required: field.required };
4335
+ }
3773
4336
  function toContractSlot(slot) {
3774
4337
  return {
3775
4338
  id: slot.id,
@@ -3780,6 +4343,40 @@ function toContractSlot(slot) {
3780
4343
  eventId: slot.eventId ?? ""
3781
4344
  };
3782
4345
  }
4346
+ function absentAddressViewState() {
4347
+ const part = {
4348
+ shown: false,
4349
+ required: false,
4350
+ order: 0,
4351
+ label: "",
4352
+ value: "",
4353
+ error: "",
4354
+ invalid: false
4355
+ };
4356
+ return {
4357
+ present: false,
4358
+ label: "",
4359
+ required: false,
4360
+ error: "",
4361
+ invalid: false,
4362
+ country: { label: "", value: "", error: "", invalid: false, options: [] },
4363
+ addressLine: { ...part, maxLength: 0 },
4364
+ addressLine2: { ...part, maxLength: 0 },
4365
+ streetName: { ...part, maxLength: 0 },
4366
+ streetNumber: { ...part, maxLength: 0 },
4367
+ city: { ...part, maxLength: 0 },
4368
+ subdivision: { ...part, listed: false, options: [] },
4369
+ postalCode: { ...part, maxLength: 0 }
4370
+ };
4371
+ }
4372
+ function toAddressViewState(field, value, errors) {
4373
+ if (!field?.address)
4374
+ return absentAddressViewState();
4375
+ return {
4376
+ present: true,
4377
+ ...addressViewState(toFormFieldView(field), value, errors)
4378
+ };
4379
+ }
3783
4380
  function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3784
4381
  const [services] = viewStateSignals.services;
3785
4382
  const [showServices, setShowServices] = createSignal(true);
@@ -3803,6 +4400,54 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3803
4400
  const [bookingError, setBookingError] = createSignal("");
3804
4401
  const [bookingFailure, setBookingFailure] = createSignal(BookingFailure.NONE);
3805
4402
  const [isConfirmed, setIsConfirmed] = createSignal(false);
4403
+ const [addressField, setAddressField] = createSignal(null);
4404
+ const [addressValue, setAddressValue] = createSignal({});
4405
+ const [addressErrors, setAddressErrors] = createSignal({});
4406
+ const reactive = useReactive();
4407
+ function resetAddress(field) {
4408
+ const initial = field?.address ? initialAddressValue(field.address) : {};
4409
+ setAddressField(field);
4410
+ setAddressValue(initial);
4411
+ setAddressErrors({});
4412
+ void reactive.toBeClean().then(() => reflectAddressInputs2(initial));
4413
+ }
4414
+ function onAddressInput(part, value) {
4415
+ const field = addressField();
4416
+ if (!field?.address)
4417
+ return;
4418
+ const next = nextAddressValue(field.address, addressValue(), part, value);
4419
+ setAddressValue(next);
4420
+ if (part === "country")
4421
+ reflectAddressInputs2(next);
4422
+ const key = `${field.target}/${part}`;
4423
+ if (addressErrors()[key] && !addressErrorsNow()[key])
4424
+ clearAddressError(key);
4425
+ }
4426
+ function onAddressBlur(part) {
4427
+ const field = addressField();
4428
+ if (!field)
4429
+ return;
4430
+ const key = `${field.target}/${part}`;
4431
+ const message = addressErrorsNow()[key] ?? "";
4432
+ setAddressErrors((current) => ({ ...current, [key]: message }));
4433
+ }
4434
+ function addressErrorsNow() {
4435
+ const field = addressField();
4436
+ return field ? fieldErrorsOf(toFormFieldView(field), addressValue()) : {};
4437
+ }
4438
+ function clearAddressError(key) {
4439
+ setAddressErrors((current) => ({ ...current, [key]: "" }));
4440
+ }
4441
+ function reflectAddressInputs2(value) {
4442
+ const addressRefs = refs.address;
4443
+ for (const part of ADDRESS_PARTS) {
4444
+ for (const channel of ["input", "text"]) {
4445
+ void addressRefs?.[part]?.[channel]?.exec$?.((element) => {
4446
+ element.value = value[part] ?? "";
4447
+ });
4448
+ }
4449
+ }
4450
+ }
3806
4451
  function resetBookingMessages() {
3807
4452
  setBookingStatus("");
3808
4453
  setBookingError("");
@@ -3854,21 +4499,21 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3854
4499
  setShowForm(true);
3855
4500
  setFormLoading(true);
3856
4501
  setFormFields([]);
4502
+ resetAddress(null);
3857
4503
  try {
3858
- if (!service.formId) {
3859
- setFormFields(DEFAULT_PARTICIPANT_FIELDS);
4504
+ const participantForm = await getParticipantForm({ serviceId: service.id });
4505
+ const blocking = blockingFieldLabels(participantForm);
4506
+ if (blocking.length) {
4507
+ failBooking(BookingFailure.FORM_UNSUPPORTED, describeUnsupportedForm(blocking));
4508
+ setShowForm(false);
3860
4509
  return;
3861
4510
  }
3862
- const result2 = await getFormSummary({ formId: service.formId });
3863
- setFormFields(result2.fields.map((field) => ({
3864
- target: field.target,
3865
- label: field.label,
3866
- type: field.type,
3867
- required: field.required
3868
- })));
4511
+ const fields = participantForm.fields;
4512
+ setFormFields(fields.filter((field) => field.type !== "ADDRESS"));
4513
+ resetAddress(fields.find((field) => field.type === "ADDRESS") ?? null);
3869
4514
  } catch (error) {
3870
- const message = error instanceof Error ? error.message : "Could not load participant form fields.";
3871
- failBooking(BookingFailure.FORM_UNAVAILABLE, message);
4515
+ console.warn("[wix-bookings] participant form could not load:", error);
4516
+ failBooking(BookingFailure.FORM_UNAVAILABLE, FORM_UNAVAILABLE_MESSAGE);
3872
4517
  setShowForm(false);
3873
4518
  } finally {
3874
4519
  setFormLoading(false);
@@ -3876,14 +4521,18 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3876
4521
  }
3877
4522
  async function readFormValues() {
3878
4523
  const formValues = {};
3879
- const reads = refs.formFields?.formInputs?.map((input, field) => input.exec$((element) => ({
3880
- target: field.target,
3881
- value: element.value
4524
+ const reads = refs.formFields?.formInputs?.map((input, field2) => input.exec$((element) => ({
4525
+ target: field2.target,
4526
+ value: field2.type === "BOOLEAN" ? element.checked : element.value
3882
4527
  }))) ?? [];
3883
4528
  const resolved = await Promise.all(reads);
3884
4529
  for (const entry of resolved) {
3885
4530
  formValues[entry.target] = entry.value;
3886
4531
  }
4532
+ const field = addressField();
4533
+ const address = field ? normalisedAddress(field, addressValue()) : void 0;
4534
+ if (field && address)
4535
+ formValues[field.target] = address;
3887
4536
  return formValues;
3888
4537
  }
3889
4538
  async function onConfirmBooking() {
@@ -3894,13 +4543,15 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3894
4543
  }
3895
4544
  resetBookingMessages();
3896
4545
  const formValues = await readFormValues();
3897
- const fields = formFields();
3898
- for (const field of fields) {
3899
- const validationError = validateFormSummaryField(field, formValues[field.target] ?? "");
3900
- if (validationError) {
3901
- failBooking(BookingFailure.VALIDATION, validationError);
3902
- return;
3903
- }
4546
+ const partErrors = addressErrorsNow();
4547
+ setAddressErrors(partErrors);
4548
+ const [validationError] = [
4549
+ ...Object.values(participantFieldErrors(formFields(), formValues)),
4550
+ ...Object.values(partErrors)
4551
+ ];
4552
+ if (validationError) {
4553
+ failBooking(BookingFailure.VALIDATION, validationError);
4554
+ return;
3904
4555
  }
3905
4556
  setIsBooking(true);
3906
4557
  try {
@@ -3913,18 +4564,11 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3913
4564
  scheduleId: slot.scheduleId,
3914
4565
  eventId: slot.eventId
3915
4566
  },
3916
- formValues,
4567
+ formValues: postedParticipantValues(formFields(), formValues),
3917
4568
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
3918
4569
  siteOrigin: window.location.origin
3919
4570
  });
3920
- if (result2.outcome === "redirect") {
3921
- window.location.href = result2.redirectUrl;
3922
- return;
3923
- }
3924
- setBookingStatus("Booking confirmed!");
3925
- setIsConfirmed(true);
3926
- setShowForm(false);
3927
- setSelectedSlot(null);
4571
+ showBookingOutcome(result2);
3928
4572
  } catch (error) {
3929
4573
  const { failure: failure2, message } = describeBookingError(error);
3930
4574
  failBooking(failure2, message);
@@ -3932,6 +4576,59 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3932
4576
  setIsBooking(false);
3933
4577
  }
3934
4578
  }
4579
+ function showBookingOutcome(result2) {
4580
+ switch (result2.outcome) {
4581
+ case "redirect":
4582
+ window.location.href = result2.redirectUrl;
4583
+ return;
4584
+ case "confirmed":
4585
+ setBookingStatus("Booking confirmed!");
4586
+ setIsConfirmed(true);
4587
+ setShowForm(false);
4588
+ setSelectedSlot(null);
4589
+ return;
4590
+ case "invalid":
4591
+ showAddressRejection(result2);
4592
+ failBooking(BookingFailure.VALIDATION, firstFieldError(result2.fieldErrors));
4593
+ return;
4594
+ case "formUnavailable":
4595
+ failBooking(BookingFailure[result2.failure], result2.message);
4596
+ setShowForm(false);
4597
+ return;
4598
+ default: {
4599
+ const unhandled = result2;
4600
+ throw new Error(`Unknown booking outcome: ${JSON.stringify(unhandled)}`);
4601
+ }
4602
+ }
4603
+ }
4604
+ function firstFieldError(fieldErrors) {
4605
+ const rendered = formFields().find((field) => fieldErrors[field.target]);
4606
+ return rendered ? fieldErrors[rendered.target] : Object.values(fieldErrors)[0] ?? "";
4607
+ }
4608
+ function showAddressRejection(result2) {
4609
+ const field = addressField();
4610
+ if (!field?.address)
4611
+ return;
4612
+ const partErrors = Object.fromEntries(Object.entries(result2.fieldErrors).filter(([key]) => splitErrorKey(key).target === field.target && key !== field.target));
4613
+ setAddressErrors(partErrors);
4614
+ const country = result2.factsCountry?.[field.target];
4615
+ const listKey = `${field.target}/subdivision`;
4616
+ const options = result2.fieldOptions?.[listKey];
4617
+ const revealed = result2.revealedParts?.[field.target];
4618
+ if (!country || !options && !revealed)
4619
+ return;
4620
+ setAddressField({
4621
+ ...field,
4622
+ address: withLearnedFacts(field.address, {
4623
+ ...options ? { subdivisionsOf: { [country]: options } } : {},
4624
+ ...revealed ? { revealedPartsOf: { [country]: revealed } } : {}
4625
+ })
4626
+ });
4627
+ if (options && addressValue().country === country) {
4628
+ setAddressValue({ ...addressValue(), subdivision: "" });
4629
+ reflectAddressInputs2(addressValue());
4630
+ }
4631
+ }
3935
4632
  function onBackToServices() {
3936
4633
  resetBookingMessages();
3937
4634
  setShowServices(true);
@@ -3945,6 +4642,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3945
4642
  setSlotsFailure(SlotsFailure.NONE);
3946
4643
  setHasSlots(false);
3947
4644
  setFormFields([]);
4645
+ resetAddress(null);
3948
4646
  }
3949
4647
  refs.services?.serviceButtons?.onclick(({ coordinate }) => {
3950
4648
  const serviceId = coordinate[0];
@@ -3960,6 +4658,16 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3960
4658
  void onSelectSlot(slot);
3961
4659
  }
3962
4660
  });
4661
+ for (const part of ADDRESS_PARTS) {
4662
+ const partRefs = refs.address?.[part];
4663
+ for (const channel of ["input", "text"]) {
4664
+ const ref = partRefs?.[channel];
4665
+ const read = ({ event }) => onAddressInput(part, event.target.value ?? "");
4666
+ ref?.oninput?.(read);
4667
+ ref?.onchange?.(read);
4668
+ ref?.onblur?.(() => onAddressBlur(part));
4669
+ }
4670
+ }
3963
4671
  refs.bookButton?.onclick(() => {
3964
4672
  void onConfirmBooking();
3965
4673
  });
@@ -3982,7 +4690,8 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
3982
4690
  slotsMessage: slotsMessage(),
3983
4691
  slotsFailure: slotsFailure(),
3984
4692
  hasSlots: hasSlots(),
3985
- formFields: formFields(),
4693
+ formFields: formFields().map(toContractFormField),
4694
+ address: toAddressViewState(addressField(), addressValue(), addressErrors()),
3986
4695
  formLoading: formLoading(),
3987
4696
  isBooking: isBooking(),
3988
4697
  bookingStatus: bookingStatus(),
@@ -4003,6 +4712,7 @@ export {
4003
4712
  canBookOnline,
4004
4713
  createBooking,
4005
4714
  createWixBookingsContext,
4715
+ getParticipantForm,
4006
4716
  init,
4007
4717
  listServices,
4008
4718
  listSlots