@jay-framework/wix-bookings 0.25.4 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,505 @@
1
1
  import { makeJayInit, makeJayStackComponent } from "@jay-framework/fullstack-component";
2
- import { createSignal } from "@jay-framework/component";
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 { createSignal, createEffect } from "@jay-framework/component";
3
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
4
- import { WixApiError } from "@jay-framework/wix-server-client/client";
5
- const init = makeJayInit().withClient(async () => {
6
- console.log("[wix-bookings] Client ready (no client context required)");
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 result = 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 = result.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
+ async function getBookingServiceById(client, serviceId) {
37
+ const result = await wixFetch(client, "/bookings/v2/services/query", {
38
+ method: "POST",
39
+ body: {
40
+ query: {
41
+ filter: { _id: serviceId },
42
+ paging: { limit: 1 }
43
+ }
44
+ }
45
+ });
46
+ return result.services?.[0];
47
+ }
48
+ function formatPrice(service) {
49
+ const price = service.payment?.fixed?.price;
50
+ if (!price?.value) {
51
+ return "Free";
52
+ }
53
+ const amount = parseFloat(price.value);
54
+ return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
55
+ }
56
+ function formatDurationMinutes(service) {
57
+ const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
58
+ if (!minutes) {
59
+ return "";
60
+ }
61
+ return `${minutes} min`;
62
+ }
63
+ function mapService(raw) {
64
+ const duration = formatDurationMinutes(raw);
65
+ return {
66
+ id: raw._id ?? raw.id ?? "",
67
+ name: raw.name ?? "Service",
68
+ type: raw.type ?? "APPOINTMENT",
69
+ description: raw.description ?? "",
70
+ priceLabel: formatPrice(raw),
71
+ durationLabel: duration,
72
+ formId: raw.form?._id ?? ""
73
+ };
74
+ }
75
+ function createSlotId(resourceId, localStartDate) {
76
+ return `${resourceId}:${localStartDate}`;
77
+ }
78
+ function formatSlotLabel(localStartDate) {
79
+ const date = new Date(localStartDate);
80
+ return date.toLocaleString([], {
81
+ weekday: "short",
82
+ month: "short",
83
+ day: "numeric",
84
+ hour: "2-digit",
85
+ minute: "2-digit"
86
+ });
87
+ }
88
+ function mapAppointmentSlot(slot) {
89
+ if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
90
+ return null;
91
+ }
92
+ return {
93
+ id: createSlotId(slot.scheduleId, slot.localStartDate),
94
+ localStartDate: slot.localStartDate,
95
+ localEndDate: slot.localEndDate,
96
+ label: formatSlotLabel(slot.localStartDate),
97
+ scheduleId: slot.scheduleId,
98
+ serviceType: "APPOINTMENT"
99
+ };
100
+ }
101
+ function mapClassSlot(slot) {
102
+ const eventId = slot.eventInfo?.eventId;
103
+ if (!eventId || !slot.localStartDate || !slot.localEndDate) {
104
+ return null;
105
+ }
106
+ return {
107
+ id: createSlotId(eventId, slot.localStartDate),
108
+ localStartDate: slot.localStartDate,
109
+ localEndDate: slot.localEndDate,
110
+ label: formatSlotLabel(slot.localStartDate),
111
+ eventId,
112
+ serviceType: "CLASS"
113
+ };
114
+ }
115
+ function localDateStrInTimeZone(date, timeZone) {
116
+ const parts = new Intl.DateTimeFormat("en-US", {
117
+ timeZone,
118
+ year: "numeric",
119
+ month: "2-digit",
120
+ day: "2-digit",
121
+ hour: "2-digit",
122
+ minute: "2-digit",
123
+ second: "2-digit",
124
+ hour12: false
125
+ }).formatToParts(date);
126
+ const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
127
+ const hour = read("hour") === "24" ? "00" : read("hour");
128
+ return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
129
+ }
130
+ function paymentPreferenceFromService(service) {
131
+ const opts = service.payment?.options ?? {};
132
+ if (opts.online && !opts.inPerson) {
133
+ return "ONLINE";
134
+ }
135
+ if (!opts.online && opts.inPerson) {
136
+ return "OFFLINE";
137
+ }
138
+ return "ONLINE";
139
+ }
140
+ async function createBookingRecord(client, body) {
141
+ return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
142
+ }
143
+ async function createBookingCart(client, bookingId, bookingAppId) {
144
+ return wixFetch(client, "/ecom/v2/carts", {
145
+ method: "POST",
146
+ body: {
147
+ catalogItems: [
148
+ {
149
+ quantity: 1,
150
+ catalogReference: { catalogItemId: bookingId, appId: bookingAppId }
151
+ }
152
+ ],
153
+ cart: { source: { channelType: "WEB" } }
154
+ }
155
+ });
156
+ }
157
+ async function calculateBookingCart(client, cartId) {
158
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/calculate`, { method: "POST", body: {} });
159
+ }
160
+ async function placeBookingOrder(client, cartId) {
161
+ const res = await wixFetch(
162
+ client,
163
+ `/ecom/v2/carts/${cartId}/place-order`,
164
+ { method: "POST", body: {} }
165
+ );
166
+ return { orderId: res?.orderId };
167
+ }
168
+ async function createBookingRedirectSession(client, cartId, postFlowUrl) {
169
+ return wixFetch(client, "/headless/v1/redirect-session", {
170
+ method: "POST",
171
+ body: {
172
+ ecomCheckout: { checkoutId: cartId },
173
+ callbacks: { postFlowUrl }
174
+ }
175
+ });
176
+ }
177
+ async function getBookingCheckoutUrl(client, cartId) {
178
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/get-checkout-url`, {
179
+ method: "POST",
180
+ body: {}
181
+ });
182
+ }
183
+ const AVAILABILITY_PAGE_SIZE = 100;
184
+ async function listAvailabilityTimeSlots(client, input, options) {
185
+ const allSlots = [];
186
+ const maxSlots = options?.maxSlots;
187
+ let cursor;
188
+ let hasMorePages = true;
189
+ while (hasMorePages) {
190
+ const result = await wixFetch(
191
+ client,
192
+ "/_api/service-availability/v2/time-slots",
193
+ {
194
+ method: "POST",
195
+ body: {
196
+ serviceId: input.serviceId,
197
+ fromLocalDate: input.fromLocalDate,
198
+ toLocalDate: input.toLocalDate,
199
+ timeZone: input.timeZone,
200
+ bookable: true,
201
+ cursorPaging: cursor ? { cursor, limit: AVAILABILITY_PAGE_SIZE } : { limit: AVAILABILITY_PAGE_SIZE }
202
+ }
203
+ }
204
+ );
205
+ allSlots.push(...result.timeSlots ?? []);
206
+ if (allSlots.length >= maxSlots) {
207
+ return allSlots.slice(0, maxSlots);
208
+ }
209
+ cursor = result.pagingMetadata?.cursors?.next;
210
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
211
+ }
212
+ return allSlots;
213
+ }
214
+ const EVENT_SLOTS_PAGE_SIZE = 100;
215
+ async function listEventTimeSlots(client, input, options) {
216
+ const allSlots = [];
217
+ const maxSlots = options?.maxSlots;
218
+ let cursor;
219
+ let hasMorePages = true;
220
+ while (hasMorePages) {
221
+ const result = await wixFetch(
222
+ client,
223
+ "/_api/service-availability/v2/time-slots/event",
224
+ {
225
+ method: "POST",
226
+ body: {
227
+ serviceIds: input.serviceIds,
228
+ fromLocalDate: input.fromLocalDate,
229
+ toLocalDate: input.toLocalDate,
230
+ timeZone: input.timeZone,
231
+ includeNonBookable: false,
232
+ cursorPaging: cursor ? { cursor, limit: EVENT_SLOTS_PAGE_SIZE } : { limit: EVENT_SLOTS_PAGE_SIZE }
233
+ }
234
+ }
235
+ );
236
+ allSlots.push(...result.timeSlots ?? []);
237
+ if (allSlots.length >= maxSlots) {
238
+ return allSlots.slice(0, maxSlots);
239
+ }
240
+ cursor = result.pagingMetadata?.cursors?.next;
241
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
242
+ }
243
+ return allSlots;
244
+ }
245
+ async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
246
+ try {
247
+ const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
248
+ const redirectUrl = redirectData.redirectSession?.fullUrl;
249
+ if (redirectUrl) {
250
+ return redirectUrl;
251
+ }
252
+ } catch (error) {
253
+ if (!(error instanceof WixApiError) || error.status !== 400 && error.status !== 404) {
254
+ throw error;
255
+ }
256
+ }
257
+ const checkoutUrlData = await getBookingCheckoutUrl(wixClient, cartId);
258
+ const checkoutUrl = checkoutUrlData.checkoutUrl;
259
+ if (!checkoutUrl) {
260
+ throw new Error(
261
+ "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."
262
+ );
263
+ }
264
+ return checkoutUrl;
265
+ }
266
+ function createWixBookingsService(wixClient, config) {
267
+ return {
268
+ async listServices() {
269
+ const items = await queryBookingServices(wixClient, config.bookingAppId);
270
+ return items.filter((item) => !item.hidden).map((item) => mapService(item));
271
+ },
272
+ async listSlots({ serviceId, serviceType, timezone, windowDays }) {
273
+ const now = /* @__PURE__ */ new Date();
274
+ const tz = timezone ?? "UTC";
275
+ const from = localDateStrInTimeZone(now, tz);
276
+ const days = windowDays ?? config.slotWindowDays;
277
+ const to = new Date(now.getTime() + days * 24 * 60 * 60 * 1e3);
278
+ const toStr = localDateStrInTimeZone(to, tz);
279
+ const slotQueryOptions = { maxSlots: MAX_SLOTS_PER_QUERY };
280
+ if (serviceType === "APPOINTMENT") {
281
+ const timeSlots2 = await listAvailabilityTimeSlots(
282
+ wixClient,
283
+ {
284
+ serviceId,
285
+ fromLocalDate: from,
286
+ toLocalDate: toStr,
287
+ timeZone: tz
288
+ },
289
+ slotQueryOptions
290
+ );
291
+ return timeSlots2.map((slot) => mapAppointmentSlot(slot)).filter((slot) => slot !== null);
292
+ }
293
+ const timeSlots = await listEventTimeSlots(
294
+ wixClient,
295
+ {
296
+ serviceIds: [serviceId],
297
+ fromLocalDate: from,
298
+ toLocalDate: toStr,
299
+ timeZone: tz
300
+ },
301
+ slotQueryOptions
302
+ );
303
+ return timeSlots.map((slot) => mapClassSlot(slot)).filter((slot) => slot !== null);
304
+ },
305
+ async createBooking(input) {
306
+ const rawService = await getBookingServiceById(wixClient, input.serviceId);
307
+ const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
308
+ rawService
309
+ ) : "ONLINE");
310
+ const slotData = {
311
+ serviceId: input.serviceId,
312
+ startDate: input.slot.localStartDate,
313
+ endDate: input.slot.localEndDate,
314
+ timezone: input.timezone,
315
+ location: { locationType: "OWNER_BUSINESS" },
316
+ // Any staff member of the configured staff resource type; without one, the slot's own (a class
317
+ // session names its staff; Wix rejects an empty resource type id).
318
+ ...config.staffResourceTypeId ? {
319
+ resourceSelections: [
320
+ {
321
+ resourceTypeId: config.staffResourceTypeId,
322
+ selectionMethod: "ANY_RESOURCE"
323
+ }
324
+ ]
325
+ } : {}
326
+ };
327
+ if (input.serviceType === "APPOINTMENT") {
328
+ slotData.scheduleId = input.slot.scheduleId;
329
+ } else {
330
+ slotData.eventId = input.slot.eventId;
331
+ }
332
+ const bookingData = await createBookingRecord(wixClient, {
333
+ booking: {
334
+ bookedEntity: { slot: slotData },
335
+ selectedPaymentOption: paymentPreference,
336
+ totalParticipants: 1
337
+ },
338
+ formSubmission: input.formValues
339
+ });
340
+ const bookingId = bookingData.booking.id;
341
+ const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
342
+ const cartId = cartData.cart.id;
343
+ const calcData = await calculateBookingCart(wixClient, cartId);
344
+ const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
345
+ if (total > 0) {
346
+ const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
347
+ const redirectUrl = await resolvePaidCheckoutRedirectUrl(
348
+ wixClient,
349
+ cartId,
350
+ postFlowUrl
351
+ );
352
+ return { outcome: "redirect", redirectUrl };
353
+ }
354
+ const { orderId } = await placeBookingOrder(wixClient, cartId);
355
+ return { outcome: "confirmed", ...orderId ? { orderId } : {} };
356
+ }
357
+ };
358
+ }
359
+ function canBookOnline(features, type, step) {
360
+ if (type === "COURSE") return step !== "form" || features.courses;
361
+ return type === "CLASS" ? features.groups : features.appointments;
362
+ }
363
+ const WIX_BOOKINGS_CONTEXT = createJayContext("wix:bookings");
364
+ function createWixBookingsContext(wixClient, config) {
365
+ let settings;
366
+ const readSettings = () => {
367
+ if (!settings) {
368
+ settings = wixFetch(
369
+ wixClient,
370
+ "/_api/bookings-settings/v2/settings?fields=FEATURES&fields=SITE_PROPERTIES"
371
+ ).then((res) => res.bookingsSettings).catch(() => {
372
+ settings = void 0;
373
+ return void 0;
374
+ });
375
+ }
376
+ return settings;
377
+ };
378
+ const service = createWixBookingsService(wixClient, config);
379
+ const ownBookings = async (filter) => {
380
+ const res = await wixFetch(wixClient, "/_api/bookings-reader/v2/extended-bookings/query", {
381
+ method: "POST",
382
+ body: {
383
+ query: { filter, cursorPaging: { limit: 100 } },
384
+ withBookingAllowedActions: false
385
+ }
386
+ }).catch(() => ({ extendedBookings: [] }));
387
+ return (res.extendedBookings ?? []).map((e) => e.booking ?? {});
388
+ };
389
+ return {
390
+ async features() {
391
+ const f = (await readSettings())?.features ?? {};
392
+ return {
393
+ groups: Boolean(f.bookingsGroups?.enabled),
394
+ appointments: Boolean(f.bookingsAppointments?.enabled),
395
+ courses: Boolean(f.bookingsCourses?.enabled),
396
+ payments: Boolean(f.bookingsPayments?.enabled)
397
+ };
398
+ },
399
+ async timeZone() {
400
+ return (await readSettings())?.siteProperties?.timeZone ?? "UTC";
401
+ },
402
+ async serviceBySlug(slug) {
403
+ const res = await wixFetch(
404
+ wixClient,
405
+ "/bookings/v2/services/query",
406
+ {
407
+ method: "POST",
408
+ body: {
409
+ query: {
410
+ filter: { "supportedSlugs.name": slug, hidden: false },
411
+ paging: { limit: 1 }
412
+ }
413
+ }
414
+ }
415
+ );
416
+ return res.services?.[0];
417
+ },
418
+ serviceById(id) {
419
+ return getBookingServiceById(wixClient, id);
420
+ },
421
+ async timeSlots(query) {
422
+ const res = await wixFetch(
423
+ wixClient,
424
+ "/_api/service-availability/v2/time-slots/event",
425
+ {
426
+ method: "POST",
427
+ body: {
428
+ serviceIds: query.serviceIds,
429
+ timeZone: query.timeZone,
430
+ fromLocalDate: query.fromLocalDate,
431
+ toLocalDate: query.toLocalDate,
432
+ includeNonBookable: query.includeNonBookable ?? true,
433
+ ...query.maxSlotsPerDay ? { maxSlotsPerDay: query.maxSlotsPerDay } : {},
434
+ eventFilter: {},
435
+ cursorPaging: { limit: query.limit ?? 1e3 }
436
+ }
437
+ }
438
+ );
439
+ return res.timeSlots ?? [];
440
+ },
441
+ createBooking: service.createBooking,
442
+ async serviceBookings(serviceId) {
443
+ return (await ownBookings({
444
+ "bookedEntity.slot.serviceId": serviceId,
445
+ status: { $in: ["CONFIRMED", "PENDING"] }
446
+ })).filter((b) => b.id || b.startDate);
447
+ },
448
+ async bookingById(bookingId) {
449
+ return (await ownBookings({ id: bookingId }))[0];
450
+ },
451
+ async orderById(orderId) {
452
+ try {
453
+ const res = await wixFetch(
454
+ wixClient,
455
+ `/ecom/v1/orders/${encodeURIComponent(orderId)}`
456
+ );
457
+ return res.order;
458
+ } catch (error) {
459
+ if (error instanceof WixApiError) return void 0;
460
+ throw error;
461
+ }
462
+ }
463
+ };
464
+ }
465
+ function provideWixBookingsContext(config) {
466
+ const client = useGlobalContext(WIX_CLIENT_CONTEXT)?.client;
467
+ if (!client) return void 0;
468
+ const context = createWixBookingsContext(client, config);
469
+ registerGlobalContext(WIX_BOOKINGS_CONTEXT, context);
470
+ return context;
471
+ }
472
+ const init = makeJayInit().withClient(async ({ config }) => {
473
+ provideWixBookingsContext(config);
7
474
  });
475
+ var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
476
+ ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
477
+ ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
478
+ ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
479
+ return ServicesFailure2;
480
+ })(ServicesFailure || {});
481
+ var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
482
+ SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
483
+ SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
484
+ return SlotsFailure2;
485
+ })(SlotsFailure || {});
486
+ var BookingState = /* @__PURE__ */ ((BookingState2) => {
487
+ BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
488
+ BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
489
+ BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
490
+ BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
491
+ return BookingState2;
492
+ })(BookingState || {});
493
+ var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
494
+ BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
495
+ BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
496
+ BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
497
+ BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
498
+ BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
499
+ BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
500
+ BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
501
+ return BookingFailure2;
502
+ })(BookingFailure || {});
8
503
  const listServices = createActionCaller("wixBookings.listServices", "GET");
9
504
  const listSlots = createActionCaller("wixBookings.listSlots", "GET");
10
505
  const createBooking = createActionCaller("wixBookings.createBooking", "POST");
@@ -36,7 +531,14 @@ function validateFormSummaryField(field, value) {
36
531
  return "";
37
532
  }
38
533
  function validateFormField(field, value) {
39
- const trimmed = (value ?? "").trim();
534
+ if (field.inputType === "checkbox") {
535
+ return field.required && value !== true ? `${field.label} is required.` : "";
536
+ }
537
+ if (field.inputType === "multiselect") {
538
+ const empty = !Array.isArray(value) || value.length === 0;
539
+ return field.required && empty ? `${field.label} is required.` : "";
540
+ }
541
+ const trimmed = (typeof value === "string" ? value : "").trim();
40
542
  if (field.required && !trimmed) {
41
543
  return `${field.label} is required.`;
42
544
  }
@@ -69,127 +571,583 @@ function validateFormField(field, value) {
69
571
  }
70
572
  return "";
71
573
  }
72
- function parseSubmissionFieldErrors(responseBody) {
73
- try {
74
- const parsed = JSON.parse(responseBody);
75
- const fieldErrors = {};
76
- const violations = parsed.details?.validationError?.fieldViolations ?? [];
77
- for (const violation of violations) {
78
- for (const fieldError of violation.data?.errors ?? []) {
79
- if (fieldError.errorPath && !fieldErrors[fieldError.errorPath]) {
80
- fieldErrors[fieldError.errorPath] = fieldError.errorMessage ?? "Invalid value";
81
- }
82
- }
574
+ const SUBMIT_FAILED_MESSAGE = "We could not complete your request. Please try again.";
575
+ var SubmitState = /* @__PURE__ */ ((SubmitState2) => {
576
+ SubmitState2[SubmitState2["IDLE"] = 0] = "IDLE";
577
+ SubmitState2[SubmitState2["SUBMITTING"] = 1] = "SUBMITTING";
578
+ SubmitState2[SubmitState2["SUCCEEDED"] = 2] = "SUCCEEDED";
579
+ SubmitState2[SubmitState2["FAILED"] = 3] = "FAILED";
580
+ return SubmitState2;
581
+ })(SubmitState || {});
582
+ var SubmitFailure = /* @__PURE__ */ ((SubmitFailure2) => {
583
+ SubmitFailure2[SubmitFailure2["NONE"] = 0] = "NONE";
584
+ SubmitFailure2[SubmitFailure2["VALIDATION"] = 1] = "VALIDATION";
585
+ SubmitFailure2[SubmitFailure2["REJECTED"] = 2] = "REJECTED";
586
+ SubmitFailure2[SubmitFailure2["PERMISSION"] = 3] = "PERMISSION";
587
+ SubmitFailure2[SubmitFailure2["NETWORK"] = 4] = "NETWORK";
588
+ SubmitFailure2[SubmitFailure2["UNKNOWN"] = 5] = "UNKNOWN";
589
+ return SubmitFailure2;
590
+ })(SubmitFailure || {});
591
+ function presentSubmitRejection(result, fields) {
592
+ const view = { errorByTarget: {}, invalidByTarget: {}, statusMessage: "" };
593
+ const statusLines = result.message ? [result.message] : [];
594
+ for (const [target, message] of Object.entries(result.fieldErrors ?? {})) {
595
+ const field = fields.find((candidate) => candidate.target === target);
596
+ if (field && !field.hidden) {
597
+ view.errorByTarget[target] = message;
598
+ view.invalidByTarget[target] = true;
599
+ } else {
600
+ statusLines.push(`${field?.label || target}: ${message}`);
83
601
  }
84
- return fieldErrors;
602
+ }
603
+ view.statusMessage = statusLines.join(" ");
604
+ if (!view.statusMessage && !Object.keys(view.errorByTarget).length) {
605
+ view.statusMessage = SUBMIT_FAILED_MESSAGE;
606
+ }
607
+ return view;
608
+ }
609
+ const PROBE_ORIGIN = "https://site.invalid";
610
+ function toSitePath(candidate) {
611
+ if (typeof candidate !== "string" || !candidate.startsWith("/") || /[\u0000-\u001F\u007F\\]/.test(candidate)) {
612
+ return void 0;
613
+ }
614
+ try {
615
+ const url = new URL(candidate, PROBE_ORIGIN);
616
+ if (url.origin !== PROBE_ORIGIN) return void 0;
617
+ const path = url.pathname + url.search + url.hash;
618
+ return path.startsWith("//") ? void 0 : path;
85
619
  } catch {
86
- return {};
620
+ return void 0;
621
+ }
622
+ }
623
+ function emptyValueFor(field) {
624
+ if (field.inputType === "checkbox") return false;
625
+ if (field.inputType === "multiselect") return [];
626
+ return "";
627
+ }
628
+ function projectSubmissionValues(fields, store) {
629
+ const values = {};
630
+ for (const field of fields) {
631
+ values[field.target] = field.target in store ? store[field.target] : emptyValueFor(field);
632
+ }
633
+ return values;
634
+ }
635
+ function emptyStoreFor(fields) {
636
+ const store = {};
637
+ for (const field of fields) {
638
+ store[field.target] = emptyValueFor(field);
639
+ }
640
+ return store;
641
+ }
642
+ function seedControlValues(store, seeds) {
643
+ const seeded = { ...store };
644
+ for (const { target, value, dirty } of seeds) {
645
+ if (dirty || target in seeded || !hasValue(value)) {
646
+ continue;
647
+ }
648
+ seeded[target] = value;
649
+ }
650
+ return seeded;
651
+ }
652
+ function hasValue(value) {
653
+ if (typeof value === "string") return value.length > 0;
654
+ if (Array.isArray(value)) return value.length > 0;
655
+ return value === true;
656
+ }
657
+ function validateVisibleFields(fields, values) {
658
+ const errors = {};
659
+ for (const field of fields) {
660
+ if (field.hidden) continue;
661
+ const message = validateFormField(field, values[field.target] ?? emptyValueFor(field));
662
+ if (message) errors[field.target] = message;
87
663
  }
664
+ return errors;
88
665
  }
89
- function toContractFields(fields) {
90
- return fields.map((field) => ({
91
- target: field.target,
666
+ var __assign = function() {
667
+ __assign = Object.assign || function __assign2(t) {
668
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
669
+ s = arguments[i];
670
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
671
+ }
672
+ return t;
673
+ };
674
+ return __assign.apply(this, arguments);
675
+ };
676
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
677
+ var e = new Error(message);
678
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
679
+ };
680
+ function lowerCase(str) {
681
+ return str.toLowerCase();
682
+ }
683
+ var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
684
+ var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
685
+ function noCase(input, options) {
686
+ if (options === void 0) {
687
+ options = {};
688
+ }
689
+ var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
690
+ var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
691
+ var start = 0;
692
+ var end = result.length;
693
+ while (result.charAt(start) === "\0")
694
+ start++;
695
+ while (result.charAt(end - 1) === "\0")
696
+ end--;
697
+ return result.slice(start, end).split("\0").map(transform).join(delimiter);
698
+ }
699
+ function replace(input, re, value) {
700
+ if (re instanceof RegExp)
701
+ return input.replace(re, value);
702
+ return re.reduce(function(input2, re2) {
703
+ return input2.replace(re2, value);
704
+ }, input);
705
+ }
706
+ function pascalCaseTransform(input, index) {
707
+ var firstChar = input.charAt(0);
708
+ var lowerChars = input.substr(1).toLowerCase();
709
+ if (index > 0 && firstChar >= "0" && firstChar <= "9") {
710
+ return "_" + firstChar + lowerChars;
711
+ }
712
+ return "" + firstChar.toUpperCase() + lowerChars;
713
+ }
714
+ function pascalCase(input, options) {
715
+ if (options === void 0) {
716
+ options = {};
717
+ }
718
+ return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
719
+ }
720
+ function camelCaseTransform(input, index) {
721
+ if (index === 0)
722
+ return input.toLowerCase();
723
+ return pascalCaseTransform(input, index);
724
+ }
725
+ function camelCase$1(input, options) {
726
+ if (options === void 0) {
727
+ options = {};
728
+ }
729
+ return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
730
+ }
731
+ function camelCase(value) {
732
+ let leadingUnderscores = 0;
733
+ for (const char of value) {
734
+ if (char === "_") leadingUnderscores++;
735
+ else break;
736
+ }
737
+ if (leadingUnderscores === 0) return camelCase$1(value);
738
+ const withoutLeadingUnderscores = value.slice(leadingUnderscores);
739
+ return "_".repeat(leadingUnderscores) + camelCase$1(withoutLeadingUnderscores);
740
+ }
741
+ const RESERVED_TAG_NAMES = /* @__PURE__ */ new Set([
742
+ "isLoading",
743
+ "loadError",
744
+ "isSubmitting",
745
+ "isSubmitted",
746
+ "statusMessage",
747
+ "submitState",
748
+ "submitFailure",
749
+ "submitButton",
750
+ "resetButton",
751
+ "honeypot",
752
+ "confirmation"
753
+ ]);
754
+ function contractTagName(target) {
755
+ const name = camelCase(target);
756
+ return RESERVED_TAG_NAMES.has(name) ? `${name}Field` : name;
757
+ }
758
+ function fieldToViewState(field, state) {
759
+ const viewState = {
92
760
  label: field.label,
93
- inputType: field.inputType,
94
- isTextarea: field.inputType === "textarea",
95
761
  required: field.required,
96
- placeholder: field.placeholder,
97
- hasOptions: field.options.length > 0
98
- }));
762
+ error: state.error,
763
+ invalid: state.invalid
764
+ };
765
+ if (field.inputType === "checkbox") {
766
+ viewState.value = state.value === true;
767
+ } else if (field.inputType === "select" || field.inputType === "multiselect") {
768
+ const selectedValues = Array.isArray(state.value) ? state.value : [];
769
+ viewState.options = field.options.map((option) => {
770
+ const optionView = {
771
+ value: option.value,
772
+ label: option.label
773
+ };
774
+ if (field.inputType === "multiselect") {
775
+ optionView.selected = selectedValues.includes(option.value);
776
+ }
777
+ return optionView;
778
+ });
779
+ } else {
780
+ viewState.placeholder = field.placeholder;
781
+ viewState.value = typeof state.value === "string" ? state.value : "";
782
+ }
783
+ return viewState;
784
+ }
785
+ function buildFieldsViewState(fields, errorByTarget = {}, invalidByTarget = {}, valueByTarget = {}) {
786
+ const viewState = {};
787
+ for (const field of fields) {
788
+ viewState[contractTagName(field.target)] = fieldToViewState(field, {
789
+ error: errorByTarget[field.target] ?? "",
790
+ invalid: invalidByTarget[field.target] ?? false,
791
+ value: valueByTarget[field.target] ?? ""
792
+ });
793
+ }
794
+ return viewState;
795
+ }
796
+ function buildFormViewState(fields, overrides) {
797
+ return {
798
+ ...buildFieldsViewState(
799
+ fields,
800
+ overrides.errorByTarget,
801
+ overrides.invalidByTarget,
802
+ overrides.valueByTarget
803
+ ),
804
+ isLoading: fields.length === 0 && !overrides.loadError,
805
+ loadError: overrides.loadError,
806
+ isSubmitting: overrides.isSubmitting,
807
+ statusMessage: overrides.statusMessage,
808
+ isSubmitted: overrides.isSubmitted ?? false,
809
+ submitState: submitStateOf(overrides),
810
+ submitFailure: overrides.submitFailure ?? SubmitFailure.NONE
811
+ };
812
+ }
813
+ function submitStateOf(overrides) {
814
+ if (overrides.isSubmitted) return SubmitState.SUCCEEDED;
815
+ if (overrides.isSubmitting) return SubmitState.SUBMITTING;
816
+ if (overrides.submitFailure) return SubmitState.FAILED;
817
+ return SubmitState.IDLE;
99
818
  }
100
- function WixFormInteractive(props, refs, viewStateSignals, carryForward) {
819
+ function createSubmitFlight() {
820
+ let generation = 0;
821
+ return {
822
+ begin() {
823
+ return ++generation;
824
+ },
825
+ invalidate() {
826
+ generation++;
827
+ },
828
+ isCurrent(generationAtStart) {
829
+ return generationAtStart === generation;
830
+ }
831
+ };
832
+ }
833
+ async function runFormSubmit(params) {
834
+ if (params.isSubmitting()) return;
835
+ const generation = params.flight.begin();
836
+ params.setIsSubmitting(true);
837
+ let result;
838
+ try {
839
+ await params.ensureSessionFresh();
840
+ result = await params.submitForm({
841
+ formId: params.formId,
842
+ values: params.submissionValues
843
+ });
844
+ } catch {
845
+ if (!params.flight.isCurrent(generation)) return;
846
+ params.onNetworkFailure();
847
+ params.setIsSubmitting(false);
848
+ return;
849
+ }
850
+ if (!params.flight.isCurrent(generation)) return;
851
+ const redirectPath = params.presentSubmitResult(result);
852
+ if (redirectPath) {
853
+ params.navigate(redirectPath);
854
+ } else {
855
+ params.setIsSubmitting(false);
856
+ }
857
+ }
858
+ const guardedForms = /* @__PURE__ */ new WeakSet();
859
+ function guardNativeFormSubmit(form, submit) {
860
+ if (!form || guardedForms.has(form)) return;
861
+ guardedForms.add(form);
862
+ form.addEventListener("submit", (event) => {
863
+ event.preventDefault();
864
+ void submit();
865
+ });
866
+ }
867
+ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
101
868
  const [isSubmitting, setIsSubmitting] = createSignal(false);
102
869
  const [statusMessage, setStatusMessage] = createSignal("");
103
- const [fieldErrors, setFieldErrors] = createSignal([]);
104
- async function readFormValues() {
105
- const values = {};
106
- const inputReads = refs.fields?.formInputs?.map((input, field) => input.exec$((element) => ({
107
- target: field.target,
108
- value: element.value
109
- }))) ?? [];
110
- const textareaReads = refs.fields?.formTextareas?.map((textarea, field) => textarea.exec$((element) => ({
111
- target: field.target,
112
- value: element.value
113
- }))) ?? [];
114
- const selectReads = refs.fields?.formSelects?.map((select, field) => select.exec$((element) => ({
115
- target: field.target,
116
- value: element.value
117
- }))) ?? [];
118
- const resolved = await Promise.all([...inputReads, ...textareaReads, ...selectReads]);
119
- for (const entry of resolved) {
120
- values[entry.target] = entry.value;
121
- }
122
- return values;
123
- }
124
- async function clearFormValues() {
125
- const clears = [
126
- ...refs.fields?.formInputs?.map((input) => input.exec$((element) => {
127
- element.value = "";
128
- })) ?? [],
129
- ...refs.fields?.formTextareas?.map((textarea) => textarea.exec$((element) => {
130
- element.value = "";
131
- })) ?? [],
132
- ...refs.fields?.formSelects?.map((select) => select.exec$((element) => {
133
- element.value = "";
134
- })) ?? []
135
- ];
136
- await Promise.all(clears);
137
- }
138
- refs.submitButton?.onclick(async () => {
870
+ const [errorByTarget, setErrorByTarget] = createSignal({});
871
+ const [invalidByTarget, setInvalidByTarget] = createSignal({});
872
+ const [isSubmitted, setIsSubmitted] = createSignal(false);
873
+ const [submitFailure, setSubmitFailure] = createSignal(SubmitFailure.NONE);
874
+ const [values, setValues] = createSignal({});
875
+ const dirtyTargets = /* @__PURE__ */ new Set();
876
+ let honeypotValue = "";
877
+ const submitFlight = createSubmitFlight();
878
+ function setFieldValue(target, value) {
879
+ setValues((current) => ({ ...current, [target]: value }));
880
+ }
881
+ function readFormValues() {
882
+ return projectSubmissionValues(carryForward.fields, values());
883
+ }
884
+ function validateField(field) {
885
+ const message = validateFormField(field, values()[field.target] ?? emptyValueFor(field));
886
+ setErrorByTarget((current) => ({ ...current, [field.target]: message }));
887
+ setInvalidByTarget((current) => ({ ...current, [field.target]: Boolean(message) }));
888
+ }
889
+ function clearFieldError(field) {
890
+ setErrorByTarget((current) => ({ ...current, [field.target]: "" }));
891
+ setInvalidByTarget((current) => ({ ...current, [field.target]: false }));
892
+ }
893
+ function reflectToInput(field, value) {
894
+ refs[contractTagName(field.target)]?.input?.exec$((element) => {
895
+ if (field.inputType === "checkbox") {
896
+ element.checked = value === true;
897
+ } else if (field.inputType === "multiselect") {
898
+ const selected = Array.isArray(value) ? value : [];
899
+ for (const option of Array.from(element.options)) {
900
+ option.selected = selected.includes(option.value);
901
+ }
902
+ } else {
903
+ element.value = typeof value === "string" ? value : "";
904
+ }
905
+ });
906
+ }
907
+ function handleNativeInput(field, event) {
908
+ dirtyTargets.add(field.target);
909
+ setFieldValue(field.target, readNativeValue(field, event.target));
910
+ clearFieldError(field);
911
+ }
912
+ function handleControl(field, event) {
913
+ dirtyTargets.add(field.target);
914
+ const value = readControlValue(event.target);
915
+ setFieldValue(field.target, value);
916
+ reflectToInput(field, value);
917
+ validateField(field);
918
+ }
919
+ wireFieldEvents(refs, carryForward.fields, {
920
+ onNativeInput: handleNativeInput,
921
+ onNativeBlur: validateField,
922
+ onControl: handleControl
923
+ });
924
+ wireHoneypot(refs, (value) => {
925
+ honeypotValue = value;
926
+ });
927
+ createEffect(() => {
928
+ void seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
929
+ });
930
+ afterRemount(() => wireNativeFormSubmit(refs, submit));
931
+ function resetForm() {
932
+ submitFlight.invalidate();
933
+ setValues(emptyStoreFor(carryForward.fields));
934
+ setErrorByTarget({});
935
+ setInvalidByTarget({});
139
936
  setStatusMessage("");
140
- setFieldErrors([]);
141
- const values = await readFormValues();
142
- const clientErrors = [];
143
- for (const field of carryForward.fields) {
144
- const errorMessage = validateFormField(field, values[field.target] ?? "");
145
- if (errorMessage) {
146
- clientErrors.push({ target: field.target, errorMessage });
937
+ setSubmitFailure(SubmitFailure.NONE);
938
+ setIsSubmitted(false);
939
+ setIsSubmitting(false);
940
+ dirtyTargets.clear();
941
+ honeypotValue = "";
942
+ clearNativeInputsAfterRemount();
943
+ afterRemount(() => focusFirstFieldInput(refs, carryForward.fields, () => true));
944
+ }
945
+ function showSubmitted() {
946
+ setIsSubmitted(true);
947
+ afterRemount(() => void refs.confirmation?.exec$((element) => element.focus()));
948
+ }
949
+ function showFieldErrors(errors) {
950
+ focusFirstFieldInput(refs, carryForward.fields, (field) => Boolean(errors[field.target]));
951
+ }
952
+ function clearNativeInputsAfterRemount() {
953
+ afterRemount(() => {
954
+ for (const field of carryForward.fields) {
955
+ reflectToInput(field, emptyValueFor(field));
147
956
  }
957
+ wireNativeFormSubmit(refs, submit);
958
+ });
959
+ }
960
+ refs.resetButton?.onclick(({ event }) => {
961
+ event.preventDefault();
962
+ resetForm();
963
+ });
964
+ refs.submitButton?.onclick(({ event }) => {
965
+ const form = owningSubmitForm(event.target);
966
+ if (form) {
967
+ guardNativeFormSubmit(form, submit);
968
+ return;
148
969
  }
149
- if (clientErrors.length) {
150
- setFieldErrors(clientErrors);
970
+ event.preventDefault();
971
+ void submit();
972
+ });
973
+ if (typeof window !== "undefined") {
974
+ window.addEventListener("pageshow", (event) => {
975
+ if (event.persisted)
976
+ setIsSubmitting(false);
977
+ });
978
+ }
979
+ async function submit() {
980
+ if (isSubmitting())
981
+ return;
982
+ setStatusMessage("");
983
+ setSubmitFailure(SubmitFailure.NONE);
984
+ setErrorByTarget({});
985
+ if (honeypotValue.trim()) {
986
+ showSubmitted();
151
987
  return;
152
988
  }
153
- setIsSubmitting(true);
154
- try {
155
- await submitForm({
156
- formId: carryForward.formId || (typeof props.formId === "string" ? props.formId : ""),
157
- values
158
- });
159
- setStatusMessage("Form submitted successfully.");
160
- await clearFormValues();
161
- } catch (error) {
162
- if (error instanceof WixApiError) {
163
- const mapped = parseSubmissionFieldErrors(error.responseBody);
164
- const mappedErrors = Object.entries(mapped).map(([target, errorMessage]) => ({
165
- target,
166
- errorMessage
167
- }));
168
- if (mappedErrors.length) {
169
- setFieldErrors(mappedErrors);
170
- return;
171
- }
989
+ await seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
990
+ const submissionValues = readFormValues();
991
+ const clientErrors = validateVisibleFields(carryForward.fields, submissionValues);
992
+ if (Object.keys(clientErrors).length) {
993
+ setErrorByTarget(clientErrors);
994
+ setInvalidByTarget(Object.fromEntries(Object.keys(clientErrors).map((target) => [target, true])));
995
+ showFieldErrors(clientErrors);
996
+ setSubmitFailure(SubmitFailure.VALIDATION);
997
+ return;
998
+ }
999
+ await runFormSubmit({
1000
+ flight: submitFlight,
1001
+ isSubmitting,
1002
+ setIsSubmitting,
1003
+ ensureSessionFresh,
1004
+ submitForm,
1005
+ formId: carryForward.formId,
1006
+ submissionValues,
1007
+ presentSubmitResult,
1008
+ navigate: (path) => window.location.assign(path),
1009
+ onNetworkFailure: () => {
1010
+ setStatusMessage(SUBMIT_FAILED_MESSAGE);
1011
+ setSubmitFailure(SubmitFailure.NETWORK);
172
1012
  }
173
- const rawMessage = error instanceof Error ? error.message : "Something went wrong. Please try again.";
174
- const message = rawMessage.includes("403") ? "Form submission denied. Add Wix Forms permission to your API key in the Wix dashboard." : rawMessage;
175
- setStatusMessage(message);
176
- } finally {
177
- setIsSubmitting(false);
1013
+ });
1014
+ }
1015
+ function presentSubmitResult(result) {
1016
+ if (!result.success) {
1017
+ const rejection = presentSubmitRejection(result, carryForward.fields);
1018
+ setErrorByTarget(rejection.errorByTarget);
1019
+ setInvalidByTarget(rejection.invalidByTarget);
1020
+ setStatusMessage(rejection.statusMessage);
1021
+ setSubmitFailure(result.reason ?? SubmitFailure.UNKNOWN);
1022
+ showFieldErrors(rejection.errorByTarget);
1023
+ return void 0;
178
1024
  }
179
- });
1025
+ showSubmitted();
1026
+ const redirectTo = result.redirectTo;
1027
+ const redirectPath = toSitePath(redirectTo);
1028
+ if (redirectTo !== void 0 && !redirectPath) {
1029
+ console.error("[wix-forms] dropped an unsafe redirectTo", {
1030
+ formId: carryForward.formId
1031
+ });
1032
+ }
1033
+ return redirectPath;
1034
+ }
180
1035
  return {
181
- render: () => ({
182
- fields: toContractFields(carryForward.fields),
183
- options: carryForward.options,
184
- isLoading: carryForward.fields.length === 0 && !carryForward.loadError,
185
- loadError: carryForward.loadError ?? (carryForward.fields.length ? "" : "Could not load the form. Please try again later."),
1036
+ render: () => buildFormViewState(carryForward.fields, {
186
1037
  isSubmitting: isSubmitting(),
187
1038
  statusMessage: statusMessage(),
188
- fieldErrors: fieldErrors()
1039
+ loadError: carryForward.loadError ?? "",
1040
+ errorByTarget: errorByTarget(),
1041
+ invalidByTarget: invalidByTarget(),
1042
+ valueByTarget: values(),
1043
+ isSubmitted: isSubmitted(),
1044
+ submitFailure: submitFailure()
189
1045
  })
190
1046
  };
191
1047
  }
1048
+ function wireFieldEvents(refs, fields, handlers) {
1049
+ for (const field of fields) {
1050
+ const fieldRef = refs[contractTagName(field.target)];
1051
+ if (!fieldRef)
1052
+ continue;
1053
+ fieldRef.input?.oninput(({ event }) => handlers.onNativeInput(field, event));
1054
+ fieldRef.input?.onblur(() => handlers.onNativeBlur(field));
1055
+ fieldRef.control?.onclick(({ event }) => handlers.onControl(field, event));
1056
+ fieldRef.control?.oninput(({ event }) => handlers.onControl(field, event));
1057
+ }
1058
+ }
1059
+ function afterRemount(work) {
1060
+ queueMicrotask(work);
1061
+ }
1062
+ function focusFirstFieldInput(refs, fields, matches) {
1063
+ const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && refs[contractTagName(candidate.target)]?.input);
1064
+ if (!field)
1065
+ return;
1066
+ void refs[contractTagName(field.target)].input.exec$((element) => element.focus());
1067
+ }
1068
+ function owningSubmitForm(target) {
1069
+ const button = target?.closest?.("button");
1070
+ return button?.type === "submit" ? button.form ?? void 0 : void 0;
1071
+ }
1072
+ function wireNativeFormSubmit(refs, submit) {
1073
+ void refs.submitButton?.exec$((button) => guardNativeFormSubmit(button.form, submit));
1074
+ }
1075
+ function seedControlsIntoStore(refs, fields, dirtyTargets, setValues) {
1076
+ const seeds = [];
1077
+ const reads = fields.map((field) => {
1078
+ const control = refs[contractTagName(field.target)]?.control;
1079
+ if (!control?.exec$)
1080
+ return Promise.resolve();
1081
+ return control.exec$((element) => readControlValue(element)).then((value) => {
1082
+ seeds.push({
1083
+ target: field.target,
1084
+ value: value ?? "",
1085
+ dirty: dirtyTargets.has(field.target)
1086
+ });
1087
+ });
1088
+ });
1089
+ return Promise.all(reads).then(() => {
1090
+ setValues((current) => seedControlValues(current, seeds));
1091
+ });
1092
+ }
1093
+ function wireHoneypot(refs, record) {
1094
+ refs.honeypot?.oninput(({ event }) => {
1095
+ record(event.target.value ?? "");
1096
+ });
1097
+ }
1098
+ function readNativeValue(field, target) {
1099
+ if (field.inputType === "checkbox") {
1100
+ return target?.checked ?? false;
1101
+ }
1102
+ if (field.inputType === "multiselect") {
1103
+ const select = target;
1104
+ return select ? Array.from(select.selectedOptions).map((option) => option.value) : [];
1105
+ }
1106
+ const element = target;
1107
+ return element?.value ?? "";
1108
+ }
1109
+ function readControlValue(target) {
1110
+ const element = target;
1111
+ if (!element)
1112
+ return "";
1113
+ const dataValue = element.getAttribute?.("data-value");
1114
+ if (dataValue !== null && dataValue !== void 0) {
1115
+ return dataValue;
1116
+ }
1117
+ return element.value ?? "";
1118
+ }
192
1119
  makeJayStackComponent().withProps().withInteractive(WixFormInteractive);
1120
+ function describeBookingError(error) {
1121
+ const rawMessage = error instanceof Error ? error.message : "";
1122
+ if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
1123
+ return {
1124
+ failure: BookingFailure.CHECKOUT_PERMISSION,
1125
+ message: "Checkout API access denied. Add Wix eCommerce (carts/checkout) permission to your API key in the Wix dashboard."
1126
+ };
1127
+ }
1128
+ if (rawMessage.includes("redirect-session") && rawMessage.includes("400")) {
1129
+ return {
1130
+ failure: BookingFailure.CHECKOUT_REDIRECT_REJECTED,
1131
+ message: "Checkout redirect rejected. In Wix Dashboard → Headless Settings → your client → Allowed redirect domains, add localhost:3000 for local dev (or your deployed domain)."
1132
+ };
1133
+ }
1134
+ if (rawMessage.includes("get-checkout-url")) {
1135
+ return {
1136
+ failure: BookingFailure.SITE_NOT_PUBLISHED,
1137
+ message: "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site)."
1138
+ };
1139
+ }
1140
+ return {
1141
+ failure: BookingFailure.UNKNOWN,
1142
+ message: rawMessage || "Booking failed. Please try again."
1143
+ };
1144
+ }
1145
+ function bookingStateOf(state) {
1146
+ if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
1147
+ if (state.isBooking) return BookingState.BOOKING;
1148
+ if (state.isConfirmed) return BookingState.CONFIRMED;
1149
+ return BookingState.IDLE;
1150
+ }
193
1151
  const DEFAULT_PARTICIPANT_FIELDS = [
194
1152
  { target: "first_name", label: "First Name", type: "STRING", required: true },
195
1153
  { target: "last_name", label: "Last Name", type: "STRING", required: true },
@@ -216,6 +1174,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
216
1174
  const [showServices, setShowServices] = createSignal(true);
217
1175
  const showNoServices = _carryForward.services.length === 0 && !_carryForward.servicesError;
218
1176
  const servicesError = _carryForward.servicesError ?? "";
1177
+ const servicesFailure = _carryForward.servicesFailure ?? ServicesFailure.NONE;
219
1178
  const [hasSlots, setHasSlots] = createSignal(false);
220
1179
  const [showSlots, setShowSlots] = createSignal(false);
221
1180
  const [showForm, setShowForm] = createSignal(false);
@@ -225,14 +1184,23 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
225
1184
  const [slots, setSlots] = createSignal([]);
226
1185
  const [slotsLoading, setSlotsLoading] = createSignal(false);
227
1186
  const [slotsMessage, setSlotsMessage] = createSignal("");
1187
+ const [slotsFailure, setSlotsFailure] = createSignal(SlotsFailure.NONE);
228
1188
  const [formFields, setFormFields] = createSignal([]);
229
1189
  const [formLoading, setFormLoading] = createSignal(false);
230
1190
  const [isBooking, setIsBooking] = createSignal(false);
231
1191
  const [bookingStatus, setBookingStatus] = createSignal("");
232
1192
  const [bookingError, setBookingError] = createSignal("");
1193
+ const [bookingFailure, setBookingFailure] = createSignal(BookingFailure.NONE);
1194
+ const [isConfirmed, setIsConfirmed] = createSignal(false);
233
1195
  function resetBookingMessages() {
234
1196
  setBookingStatus("");
235
1197
  setBookingError("");
1198
+ setBookingFailure(BookingFailure.NONE);
1199
+ setIsConfirmed(false);
1200
+ }
1201
+ function failBooking(failure, message) {
1202
+ setBookingFailure(failure);
1203
+ setBookingError(message);
236
1204
  }
237
1205
  async function onSelectService(service) {
238
1206
  resetBookingMessages();
@@ -244,6 +1212,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
244
1212
  setShowForm(false);
245
1213
  setSlotsLoading(true);
246
1214
  setSlotsMessage("");
1215
+ setSlotsFailure(SlotsFailure.NONE);
247
1216
  setSlots([]);
248
1217
  setHasSlots(false);
249
1218
  try {
@@ -258,6 +1227,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
258
1227
  setSlots(result.slots);
259
1228
  setHasSlots(result.slots.length > 0);
260
1229
  } catch (error) {
1230
+ setSlotsFailure(SlotsFailure.UNKNOWN);
261
1231
  setSlotsMessage(error instanceof Error ? error.message : "Could not load availability.");
262
1232
  } finally {
263
1233
  setSlotsLoading(false);
@@ -287,7 +1257,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
287
1257
  })));
288
1258
  } catch (error) {
289
1259
  const message = error instanceof Error ? error.message : "Could not load participant form fields.";
290
- setBookingError(message);
1260
+ failBooking(BookingFailure.FORM_UNAVAILABLE, message);
291
1261
  setShowForm(false);
292
1262
  } finally {
293
1263
  setFormLoading(false);
@@ -311,14 +1281,13 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
311
1281
  if (!service || !slot) {
312
1282
  return;
313
1283
  }
314
- setBookingError("");
315
- setBookingStatus("");
1284
+ resetBookingMessages();
316
1285
  const formValues = await readFormValues();
317
1286
  const fields = formFields();
318
1287
  for (const field of fields) {
319
1288
  const validationError = validateFormSummaryField(field, formValues[field.target] ?? "");
320
1289
  if (validationError) {
321
- setBookingError(validationError);
1290
+ failBooking(BookingFailure.VALIDATION, validationError);
322
1291
  return;
323
1292
  }
324
1293
  }
@@ -342,19 +1311,12 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
342
1311
  return;
343
1312
  }
344
1313
  setBookingStatus("Booking confirmed!");
1314
+ setIsConfirmed(true);
345
1315
  setShowForm(false);
346
1316
  setSelectedSlot(null);
347
1317
  } catch (error) {
348
- const rawMessage = error instanceof Error ? error.message : "Booking failed. Please try again.";
349
- let message = rawMessage;
350
- if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
351
- message = "Checkout API access denied. Add Wix eCommerce (carts/checkout) permission to your API key in the Wix dashboard.";
352
- } else if (rawMessage.includes("redirect-session") && rawMessage.includes("400")) {
353
- message = "Checkout redirect rejected. In Wix Dashboard → Headless Settings → your client → Allowed redirect domains, add localhost:3000 for local dev (or your deployed domain).";
354
- } else if (rawMessage.includes("get-checkout-url")) {
355
- message = "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site).";
356
- }
357
- setBookingError(message);
1318
+ const { failure, message } = describeBookingError(error);
1319
+ failBooking(failure, message);
358
1320
  } finally {
359
1321
  setIsBooking(false);
360
1322
  }
@@ -369,6 +1331,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
369
1331
  setSelectedServiceName("");
370
1332
  setSlots([]);
371
1333
  setSlotsMessage("");
1334
+ setSlotsFailure(SlotsFailure.NONE);
372
1335
  setHasSlots(false);
373
1336
  setFormFields([]);
374
1337
  }
@@ -397,6 +1360,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
397
1360
  services: services(),
398
1361
  servicesLoading: false,
399
1362
  servicesError,
1363
+ servicesFailure,
400
1364
  showServices: showServices(),
401
1365
  showNoServices,
402
1366
  showSlots: showSlots(),
@@ -405,19 +1369,29 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
405
1369
  slots: slots().map(toContractSlot),
406
1370
  slotsLoading: slotsLoading(),
407
1371
  slotsMessage: slotsMessage(),
1372
+ slotsFailure: slotsFailure(),
408
1373
  hasSlots: hasSlots(),
409
1374
  formFields: formFields(),
410
1375
  formLoading: formLoading(),
411
1376
  isBooking: isBooking(),
412
1377
  bookingStatus: bookingStatus(),
413
- bookingError: bookingError()
1378
+ bookingError: bookingError(),
1379
+ bookingState: bookingStateOf({
1380
+ isBooking: isBooking(),
1381
+ isConfirmed: isConfirmed(),
1382
+ failure: bookingFailure()
1383
+ }),
1384
+ bookingFailure: bookingFailure()
414
1385
  })
415
1386
  };
416
1387
  }
417
1388
  const bookingFlow = makeJayStackComponent().withProps().withInteractive(BookingFlowInteractive);
418
1389
  export {
1390
+ WIX_BOOKINGS_CONTEXT,
419
1391
  bookingFlow,
1392
+ canBookOnline,
420
1393
  createBooking,
1394
+ createWixBookingsContext,
421
1395
  init,
422
1396
  listServices,
423
1397
  listSlots