@jay-framework/wix-bookings 0.26.4 → 0.26.5

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.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { W as WixBookingsConfig, a as WixBookingsService } from './index.client-oaMPI34g.js';
2
- export { m as BookingFeatures, g as BookingFormFieldView, B as BookingServiceView, f as BookingSlotView, n as BookingStep, C as CreateBookingOutcome, T as TimeSlot, o as TimeSlotsQuery, h as WIX_BOOKINGS_CONTEXT, e as WIX_BOOKINGS_SERVICE, p as WixBookingsContext, b as bookingFlow, j as canBookOnline, d as createBooking, k as createWixBookingsContext, i as init, l as listServices, c as listSlots } from './index.client-oaMPI34g.js';
1
+ import { W as WixBookingsConfig, a as WixBookingsService } from './index.client-BzhFjOWZ.js';
2
+ export { o as BookingFeatures, h as BookingFormFieldView, B as BookingServiceView, f as BookingSlotView, p as BookingStep, C as CreateBookingInput, j as CreateBookingOutcome, P as ParticipantFormValue, T as TimeSlot, q as TimeSlotsQuery, k as WIX_BOOKINGS_CONTEXT, e as WIX_BOOKINGS_SERVICE, r as WixBookingsContext, b as bookingFlow, m as canBookOnline, d as createBooking, n as createWixBookingsContext, g as getParticipantForm, i as init, l as listServices, c as listSlots } from './index.client-BzhFjOWZ.js';
3
3
  import { WixClient } from '@wix/sdk';
4
4
  import '@jay-framework/fullstack-component';
5
5
  import '@jay-framework/component';
6
6
  import '@jay-framework/runtime';
7
+ import '@jay-framework/wix-forms';
7
8
 
8
9
  declare function provideWixBookingsService(wixClient: WixClient, config: WixBookingsConfig): WixBookingsService;
9
10
 
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { createJayService, makeJayInit, makeJayStackComponent, phaseOutput, RenderPipeline, makeJayQuery, makeJayAction } from "@jay-framework/fullstack-component";
1
+ import { createJayService, makeJayInit, makeJayStackComponent, phaseOutput, RenderPipeline, makeJayQuery, ActionError, makeJayAction } from "@jay-framework/fullstack-component";
2
2
  import { registerService, getService } from "@jay-framework/stack-server-runtime";
3
3
  import { WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
4
- import { g as getBookingServiceById, p as paymentPreferenceFromService, l as localDateStrInTimeZone, m as mapAppointmentSlot, a as mapClassSlot, q as queryBookingServices, b as mapService, M as MAX_SLOTS_PER_QUERY, c as loadWixBookingsConfig } from "./query-services-B1MS77NZ.js";
4
+ import { p as participantFormId, g as getBookingServiceById, l as localDateStrInTimeZone, m as mapAppointmentSlot, a as mapClassSlot, q as queryBookingServices, b as mapService, c as paymentPreferenceFromService, M as MAX_SLOTS_PER_QUERY, d as loadWixBookingsConfig } from "./query-services-XDLgzwiL.js";
5
5
  import { wixFetch, WixApiError } from "@jay-framework/wix-server-client/client";
6
+ import { inLayoutOrder, readFieldKey, ignoreReasonOf, unsupportedFieldOf, classifyFormField, phoneRulesOf, readFieldView, fieldErrorsOf, readAddressValue, validateFormField, toPostedValues, projectAddressField, isBlankAddress, toWixAddress, canonicalFormId, hasAddressField, parseBookingFormViolations, mapAddressViolations, addressMessageFor, WIX_FORMS_SERVICE } from "@jay-framework/wix-forms";
6
7
  import { createJayContext } from "@jay-framework/runtime";
7
8
  const WIX_BOOKINGS_SERVICE = createJayService("WixBookingsService");
8
9
  async function createBookingRecord(client, body) {
@@ -110,6 +111,226 @@ async function listEventTimeSlots(client, input, options) {
110
111
  }
111
112
  return allSlots;
112
113
  }
114
+ const BOOKING_TYPE_BY_INPUT_TYPE = {
115
+ text: "STRING",
116
+ textarea: "STRING",
117
+ email: "EMAIL",
118
+ url: "URL",
119
+ tel: "PHONE",
120
+ checkbox: "BOOLEAN",
121
+ address: "ADDRESS"
122
+ };
123
+ function toBookingFieldType(key) {
124
+ if (key.componentType === "DATE_PICKER") return void 0;
125
+ const inputType = classifyFormField(key);
126
+ return inputType ? BOOKING_TYPE_BY_INPUT_TYPE[inputType] : void 0;
127
+ }
128
+ function toFormFieldView(view) {
129
+ const { type, longText, ...field } = view;
130
+ return { ...field, inputType: inputTypeOf(type, longText) };
131
+ }
132
+ function inputTypeOf(type, longText) {
133
+ switch (type) {
134
+ case "STRING":
135
+ return longText ? "textarea" : "text";
136
+ case "EMAIL":
137
+ return "email";
138
+ case "PHONE":
139
+ return "tel";
140
+ case "URL":
141
+ return "url";
142
+ case "BOOLEAN":
143
+ return "checkbox";
144
+ case "ADDRESS":
145
+ return "address";
146
+ }
147
+ }
148
+ function projectParticipantForm(rawForm, formId, warn, options = {}) {
149
+ const projected = { fields: [], unsupportedFields: [] };
150
+ for (const raw of inLayoutOrder(rawForm)) {
151
+ const key = readFieldKey(raw);
152
+ const ignored = ignoreReasonOf(key);
153
+ if (ignored === "display") continue;
154
+ if (ignored === "no-target") {
155
+ warn(
156
+ `[wix-bookings] Form ${formId}: field "${key.label}" has no target in Wix and is ignored.`
157
+ );
158
+ continue;
159
+ }
160
+ if (key.hidden) {
161
+ const kind = key.required ? "required hidden field" : "hidden field";
162
+ warn(
163
+ `[wix-bookings] Form ${formId}: ${kind} "${key.label}" is ignored; bookings cannot fill hidden fields.`
164
+ );
165
+ continue;
166
+ }
167
+ const type = toBookingFieldType(key);
168
+ if (!type) {
169
+ projected.unsupportedFields.push(unsupportedFieldOf(key));
170
+ continue;
171
+ }
172
+ if (type === "ADDRESS") {
173
+ const address = addressFieldOf(key, projected, { warn, ...options });
174
+ if (address) projected.fields.push(address);
175
+ else projected.unsupportedFields.push(unsupportedFieldOf(key));
176
+ continue;
177
+ }
178
+ const inputType = classifyFormField(key);
179
+ projected.fields.push({
180
+ target: key.target,
181
+ label: key.label,
182
+ type,
183
+ required: key.required,
184
+ longText: inputType === "textarea",
185
+ ...readFieldView(raw, key),
186
+ // The same phone rules as a wixForm page (DL #58 on the DL #51 path).
187
+ ...phoneRulesOf(raw, inputType, options)
188
+ });
189
+ }
190
+ return projected;
191
+ }
192
+ function addressFieldOf(key, projected, options) {
193
+ if (projected.fields.some((field) => field.type === "ADDRESS")) return void 0;
194
+ const view = projectAddressField(key, options);
195
+ if (!view?.address) return void 0;
196
+ return {
197
+ target: view.target,
198
+ label: view.label,
199
+ type: "ADDRESS",
200
+ required: view.required,
201
+ longText: false,
202
+ placeholder: "",
203
+ options: [],
204
+ address: view.address
205
+ };
206
+ }
207
+ function blockingFieldLabels(projected) {
208
+ return projected.unsupportedFields.filter((field) => field.required === true).map((field) => field.label);
209
+ }
210
+ function participantFieldErrors(fields, values) {
211
+ const fieldErrors = {};
212
+ for (const field of fields) {
213
+ const formField = toFormFieldView(field);
214
+ if (field.type === "ADDRESS") {
215
+ Object.assign(
216
+ fieldErrors,
217
+ fieldErrorsOf(formField, readAddressValue(values[field.target]))
218
+ );
219
+ continue;
220
+ }
221
+ const empty = formField.inputType === "checkbox" ? false : "";
222
+ const message = validateFormField(formField, values[field.target] ?? empty);
223
+ if (message) fieldErrors[field.target] = message;
224
+ }
225
+ return fieldErrors;
226
+ }
227
+ function supportedParticipantValues(fields, values) {
228
+ const kept = {};
229
+ for (const field of fields) {
230
+ if (!Object.hasOwn(values, field.target)) continue;
231
+ const value = values[field.target];
232
+ if (field.type !== "ADDRESS") {
233
+ kept[field.target] = value;
234
+ continue;
235
+ }
236
+ const address = normalisedAddress(field, value);
237
+ if (address) kept[field.target] = address;
238
+ }
239
+ return kept;
240
+ }
241
+ function postedParticipantValues(fields, values) {
242
+ return toPostedValues(fields.map(toFormFieldView), values);
243
+ }
244
+ function normalisedAddress(field, value) {
245
+ const address = readAddressValue(value);
246
+ if (!field.required && isBlankAddress(address)) return void 0;
247
+ return toWixAddress(field.address, address);
248
+ }
249
+ var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
250
+ ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
251
+ ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
252
+ ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
253
+ return ServicesFailure2;
254
+ })(ServicesFailure || {});
255
+ var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
256
+ SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
257
+ SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
258
+ return SlotsFailure2;
259
+ })(SlotsFailure || {});
260
+ var BookingState = /* @__PURE__ */ ((BookingState2) => {
261
+ BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
262
+ BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
263
+ BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
264
+ BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
265
+ return BookingState2;
266
+ })(BookingState || {});
267
+ var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
268
+ BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
269
+ BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
270
+ BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
271
+ BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
272
+ BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
273
+ BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
274
+ BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
275
+ BookingFailure2[BookingFailure2["FORM_UNSUPPORTED"] = 7] = "FORM_UNSUPPORTED";
276
+ return BookingFailure2;
277
+ })(BookingFailure || {});
278
+ function describeServicesError(error) {
279
+ const rawMessage = error instanceof Error ? error.message : "";
280
+ if (rawMessage.includes("403")) {
281
+ return {
282
+ failure: ServicesFailure.PERMISSION,
283
+ message: "Bookings API access denied. Add Wix Bookings permission to your API key in the Wix dashboard."
284
+ };
285
+ }
286
+ return {
287
+ failure: ServicesFailure.UNKNOWN,
288
+ message: rawMessage || "Could not load booking services."
289
+ };
290
+ }
291
+ const FORM_UNAVAILABLE_MESSAGE = "Could not load the participant form. Please try again later.";
292
+ function describeUnsupportedForm(labels) {
293
+ return `This booking form has a required field this site cannot show yet: ${labels.join(", ")}. Booking is disabled until the site is updated.`;
294
+ }
295
+ function bookingStateOf(state) {
296
+ if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
297
+ return BookingState.IDLE;
298
+ }
299
+ const SLOW_RENDER_TTL = 600;
300
+ const SLOW_RENDER_GRACE = 3600;
301
+ const SLOW_RENDER_ERROR_TTL = 30;
302
+ const RAW_FORM_TTL_MS = SLOW_RENDER_TTL * 1e3;
303
+ function createParticipantFormLoader() {
304
+ const cache = /* @__PURE__ */ new Map();
305
+ function cachedRawForm(formId, forms) {
306
+ const cached = cache.get(formId);
307
+ if (cached && cached.expiresAt > Date.now()) return cached.rawForm;
308
+ const rawForm = forms.getRawForm(formId);
309
+ cache.set(formId, { rawForm, expiresAt: Date.now() + RAW_FORM_TTL_MS });
310
+ rawForm.catch(() => {
311
+ if (cache.get(formId)?.rawForm === rawForm) cache.delete(formId);
312
+ });
313
+ return rawForm;
314
+ }
315
+ return async (service, forms) => {
316
+ if (!service) throw new Error("Booking service not found.");
317
+ const rawFormId = participantFormId(service.form);
318
+ if (!rawFormId) throw new Error("This booking service has no participant form.");
319
+ const formId = canonicalFormId(rawFormId);
320
+ if (!formId) throw new Error("Form ID is not a valid Wix form id.");
321
+ return { formId, rawForm: await cachedRawForm(formId, forms) };
322
+ };
323
+ }
324
+ async function projectionOptionsFor(rawForm, forms) {
325
+ const phoneOptions = { defaultPhoneCountry: forms.config.defaultPhoneCountry };
326
+ if (!hasAddressField(rawForm)) return phoneOptions;
327
+ return {
328
+ ...phoneOptions,
329
+ addressTemplates: await forms.addressTemplates(),
330
+ learnedFacts: forms.learnedAddressFacts().snapshot(),
331
+ addressConfig: forms.config.address
332
+ };
333
+ }
113
334
  async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
114
335
  try {
115
336
  const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
@@ -132,6 +353,47 @@ async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
132
353
  return checkoutUrl;
133
354
  }
134
355
  function createWixBookingsService(wixClient, config) {
356
+ const loadParticipantForm = createParticipantFormLoader();
357
+ const warnOnce = createWarnOnce();
358
+ async function checkParticipantForm(input, forms) {
359
+ let service;
360
+ let participantForm;
361
+ try {
362
+ service = await getBookingServiceById(wixClient, input.serviceId);
363
+ const { formId, rawForm } = await loadParticipantForm(service, forms);
364
+ const options = await projectionOptionsFor(rawForm, forms);
365
+ participantForm = projectParticipantForm(rawForm, formId, warnOnce, options);
366
+ } catch (error) {
367
+ console.error("[wix-bookings] could not load the participant form", {
368
+ serviceId: input.serviceId,
369
+ error: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
370
+ });
371
+ return {
372
+ outcome: "formUnavailable",
373
+ failure: "FORM_UNAVAILABLE",
374
+ message: FORM_UNAVAILABLE_MESSAGE
375
+ };
376
+ }
377
+ const blocking = blockingFieldLabels(participantForm);
378
+ if (blocking.length) {
379
+ return {
380
+ outcome: "formUnavailable",
381
+ failure: "FORM_UNSUPPORTED",
382
+ message: describeUnsupportedForm(blocking)
383
+ };
384
+ }
385
+ const fieldErrors = participantFieldErrors(participantForm.fields, input.formValues);
386
+ if (Object.keys(fieldErrors).length) return { outcome: "invalid", fieldErrors };
387
+ return {
388
+ service,
389
+ formValues: postedParticipantValues(
390
+ participantForm.fields,
391
+ supportedParticipantValues(participantForm.fields, input.formValues)
392
+ ),
393
+ fields: participantForm.fields,
394
+ forms
395
+ };
396
+ }
135
397
  return {
136
398
  async listServices() {
137
399
  const items = await queryBookingServices(wixClient, config.bookingAppId);
@@ -170,60 +432,121 @@ function createWixBookingsService(wixClient, config) {
170
432
  );
171
433
  return timeSlots.map((slot) => mapClassSlot(slot)).filter((slot) => slot !== null);
172
434
  },
173
- async createBooking(input) {
174
- const rawService = await getBookingServiceById(wixClient, input.serviceId);
175
- const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
176
- rawService
177
- ) : "ONLINE");
178
- const slotData = {
179
- serviceId: input.serviceId,
180
- startDate: input.slot.localStartDate,
181
- endDate: input.slot.localEndDate,
182
- timezone: input.timezone,
183
- location: { locationType: "OWNER_BUSINESS" },
184
- // Any staff member of the configured staff resource type; without one, the slot's own (a class
185
- // session names its staff; Wix rejects an empty resource type id).
186
- ...config.staffResourceTypeId ? {
187
- resourceSelections: [
188
- {
189
- resourceTypeId: config.staffResourceTypeId,
190
- selectionMethod: "ANY_RESOURCE"
191
- }
192
- ]
193
- } : {}
194
- };
195
- if (input.serviceType === "APPOINTMENT") {
196
- slotData.scheduleId = input.slot.scheduleId;
197
- } else {
198
- slotData.eventId = input.slot.eventId;
199
- }
200
- const bookingData = await createBookingRecord(wixClient, {
201
- booking: {
202
- bookedEntity: { slot: slotData },
203
- selectedPaymentOption: paymentPreference,
204
- totalParticipants: 1
205
- },
206
- formSubmission: input.formValues
207
- });
208
- const bookingId = bookingData.booking.id;
209
- const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
210
- const cartId = cartData.cart.id;
211
- const calcData = await calculateBookingCart(wixClient, cartId);
212
- const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
213
- if (total > 0) {
214
- const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
215
- const redirectUrl = await resolvePaidCheckoutRedirectUrl(
216
- wixClient,
217
- cartId,
218
- postFlowUrl
219
- );
220
- return { outcome: "redirect", redirectUrl };
435
+ async getParticipantForm(serviceId, forms) {
436
+ if (typeof serviceId !== "string" || !serviceId) {
437
+ throw new Error("Service ID is missing.");
221
438
  }
222
- const { orderId } = await placeBookingOrder(wixClient, cartId);
223
- return { outcome: "confirmed", ...orderId ? { orderId } : {} };
439
+ const service = await getBookingServiceById(wixClient, serviceId);
440
+ const { formId, rawForm } = await loadParticipantForm(service, forms);
441
+ const options = await projectionOptionsFor(rawForm, forms);
442
+ return projectParticipantForm(rawForm, formId, warnOnce, options);
443
+ },
444
+ async createBooking(input, forms) {
445
+ const checked = await checkParticipantForm(input, forms);
446
+ if ("outcome" in checked) return checked;
447
+ return bookAndCheckout(
448
+ wixClient,
449
+ config,
450
+ checked.service,
451
+ { ...input, formValues: checked.formValues },
452
+ checked
453
+ );
224
454
  }
225
455
  };
226
456
  }
457
+ function createUncheckedBooking(wixClient, config) {
458
+ return async (input) => {
459
+ const service = await getBookingServiceById(wixClient, input.serviceId);
460
+ return bookAndCheckout(wixClient, config, service, input);
461
+ };
462
+ }
463
+ async function bookAndCheckout(wixClient, config, rawService, input, checked) {
464
+ const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
465
+ rawService
466
+ ) : "ONLINE");
467
+ const slotData = {
468
+ serviceId: input.serviceId,
469
+ startDate: input.slot.localStartDate,
470
+ endDate: input.slot.localEndDate,
471
+ timezone: input.timezone,
472
+ location: { locationType: "OWNER_BUSINESS" },
473
+ // Any staff member of the configured staff resource type; without one, the slot's own (a class
474
+ // session names its staff; Wix rejects an empty resource type id).
475
+ ...config.staffResourceTypeId ? {
476
+ resourceSelections: [
477
+ {
478
+ resourceTypeId: config.staffResourceTypeId,
479
+ selectionMethod: "ANY_RESOURCE"
480
+ }
481
+ ]
482
+ } : {}
483
+ };
484
+ if (input.serviceType === "APPOINTMENT") {
485
+ slotData.scheduleId = input.slot.scheduleId;
486
+ } else {
487
+ slotData.eventId = input.slot.eventId;
488
+ }
489
+ let bookingData;
490
+ try {
491
+ bookingData = await createBookingRecord(wixClient, {
492
+ booking: {
493
+ bookedEntity: { slot: slotData },
494
+ selectedPaymentOption: paymentPreference,
495
+ totalParticipants: 1
496
+ },
497
+ formSubmission: input.formValues
498
+ });
499
+ } catch (error) {
500
+ const invalid = checked ? invalidFromFormViolations(error, input, checked) : void 0;
501
+ if (invalid) return invalid;
502
+ throw error;
503
+ }
504
+ const bookingId = bookingData.booking.id;
505
+ const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
506
+ const cartId = cartData.cart.id;
507
+ const calcData = await calculateBookingCart(wixClient, cartId);
508
+ const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
509
+ if (total > 0) {
510
+ const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
511
+ const redirectUrl = await resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl);
512
+ return { outcome: "redirect", redirectUrl };
513
+ }
514
+ const { orderId } = await placeBookingOrder(wixClient, cartId);
515
+ return { outcome: "confirmed", ...orderId ? { orderId } : {} };
516
+ }
517
+ function invalidFromFormViolations(error, input, checked) {
518
+ var _a;
519
+ if (!(error instanceof WixApiError) || error.status !== 400) return void 0;
520
+ const violations = parseBookingFormViolations(error.responseBody);
521
+ if (!violations.length) return void 0;
522
+ const views = checked.fields.map(toFormFieldView);
523
+ const mapped = mapAddressViolations({
524
+ violations,
525
+ fields: views.filter((field) => field.inputType === "address"),
526
+ values: input.formValues,
527
+ facts: checked.forms.learnedAddressFacts()
528
+ });
529
+ const fieldErrors = { ...mapped.fieldErrors };
530
+ for (const violation of mapped.unhandled) {
531
+ const field = views.find((candidate) => candidate.target === violation.key);
532
+ fieldErrors[_a = violation.key] ?? (fieldErrors[_a] = field ? addressMessageFor(field, readAddressValue(void 0), violation) : violation.wixMessage ?? "Please check this value.");
533
+ }
534
+ return {
535
+ outcome: "invalid",
536
+ fieldErrors,
537
+ ...Object.keys(mapped.fieldOptions).length ? { fieldOptions: mapped.fieldOptions } : {},
538
+ ...Object.keys(mapped.revealedParts).length ? { revealedParts: mapped.revealedParts } : {},
539
+ ...Object.keys(mapped.factsCountry).length ? { factsCountry: mapped.factsCountry } : {}
540
+ };
541
+ }
542
+ function createWarnOnce() {
543
+ const warned = /* @__PURE__ */ new Set();
544
+ return (message) => {
545
+ if (warned.has(message)) return;
546
+ warned.add(message);
547
+ console.warn(message);
548
+ };
549
+ }
227
550
  function provideWixBookingsService(wixClient, config) {
228
551
  const service = createWixBookingsService(wixClient, config);
229
552
  registerService(WIX_BOOKINGS_SERVICE, service);
@@ -238,54 +561,32 @@ const init = makeJayInit().withServer(async () => {
238
561
  console.log("[wix-bookings] Server initialization complete");
239
562
  return { config };
240
563
  });
241
- var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
242
- ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
243
- ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
244
- ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
245
- return ServicesFailure2;
246
- })(ServicesFailure || {});
247
- var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
248
- SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
249
- SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
250
- return SlotsFailure2;
251
- })(SlotsFailure || {});
252
- var BookingState = /* @__PURE__ */ ((BookingState2) => {
253
- BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
254
- BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
255
- BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
256
- BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
257
- return BookingState2;
258
- })(BookingState || {});
259
- var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
260
- BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
261
- BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
262
- BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
263
- BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
264
- BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
265
- BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
266
- BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
267
- return BookingFailure2;
268
- })(BookingFailure || {});
269
- const SLOW_RENDER_TTL = 600;
270
- const SLOW_RENDER_GRACE = 3600;
271
- const SLOW_RENDER_ERROR_TTL = 30;
272
- function describeServicesError(error) {
273
- const rawMessage = error instanceof Error ? error.message : "";
274
- if (rawMessage.includes("403")) {
275
- return {
276
- failure: ServicesFailure.PERMISSION,
277
- message: "Bookings API access denied. Add Wix Bookings permission to your API key in the Wix dashboard."
278
- };
279
- }
564
+ function absentAddressViewState() {
565
+ const part = {
566
+ shown: false,
567
+ required: false,
568
+ order: 0,
569
+ label: "",
570
+ value: "",
571
+ error: "",
572
+ invalid: false
573
+ };
280
574
  return {
281
- failure: ServicesFailure.UNKNOWN,
282
- message: rawMessage || "Could not load booking services."
575
+ present: false,
576
+ label: "",
577
+ required: false,
578
+ error: "",
579
+ invalid: false,
580
+ country: { label: "", value: "", error: "", invalid: false, options: [] },
581
+ addressLine: { ...part, maxLength: 0 },
582
+ addressLine2: { ...part, maxLength: 0 },
583
+ streetName: { ...part, maxLength: 0 },
584
+ streetNumber: { ...part, maxLength: 0 },
585
+ city: { ...part, maxLength: 0 },
586
+ subdivision: { ...part, listed: false, options: [] },
587
+ postalCode: { ...part, maxLength: 0 }
283
588
  };
284
589
  }
285
- function bookingStateOf(state) {
286
- if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
287
- return BookingState.IDLE;
288
- }
289
590
  async function renderSlowlyChanging(_props, bookings) {
290
591
  try {
291
592
  const services = await bookings.listServices();
@@ -315,6 +616,7 @@ async function renderFastChanging(_props, carryForward) {
315
616
  slotsMessage: "",
316
617
  slotsFailure: SlotsFailure.NONE,
317
618
  formFields: [],
619
+ address: absentAddressViewState(),
318
620
  formLoading: false,
319
621
  isBooking: false,
320
622
  bookingStatus: "",
@@ -338,8 +640,14 @@ const listSlots = makeJayQuery("wixBookings.listSlots").withServices(WIX_BOOKING
338
640
  return { slots };
339
641
  }
340
642
  );
341
- const createBooking = makeJayAction("wixBookings.createBooking").withServices(WIX_BOOKINGS_SERVICE).withHandler(
342
- async (input, bookings) => bookings.createBooking(input)
643
+ const getParticipantForm = makeJayQuery("wixBookings.getParticipantForm").withServices(WIX_BOOKINGS_SERVICE, WIX_FORMS_SERVICE).withHandler(async ({ serviceId }, bookings, forms) => {
644
+ if (typeof serviceId !== "string" || !serviceId) {
645
+ throw new ActionError("INVALID_INPUT", "Service ID is missing.");
646
+ }
647
+ return bookings.getParticipantForm(serviceId, forms);
648
+ });
649
+ const createBooking = makeJayAction("wixBookings.createBooking").withServices(WIX_BOOKINGS_SERVICE, WIX_FORMS_SERVICE).withHandler(
650
+ async (input, bookings, forms) => bookings.createBooking(input, forms)
343
651
  );
344
652
  function canBookOnline(features, type, step) {
345
653
  if (type === "COURSE") return step !== "form" || features.courses;
@@ -360,7 +668,7 @@ function createWixBookingsContext(wixClient, config) {
360
668
  }
361
669
  return settings;
362
670
  };
363
- const service = createWixBookingsService(wixClient, config);
671
+ const createBooking2 = createUncheckedBooking(wixClient, config);
364
672
  const ownBookings = async (filter) => {
365
673
  const res = await wixFetch(wixClient, "/_api/bookings-reader/v2/extended-bookings/query", {
366
674
  method: "POST",
@@ -423,7 +731,7 @@ function createWixBookingsContext(wixClient, config) {
423
731
  );
424
732
  return res.timeSlots ?? [];
425
733
  },
426
- createBooking: service.createBooking,
734
+ createBooking: createBooking2,
427
735
  async serviceBookings(serviceId) {
428
736
  return (await ownBookings({
429
737
  "bookedEntity.slot.serviceId": serviceId,
@@ -454,6 +762,7 @@ export {
454
762
  canBookOnline,
455
763
  createBooking,
456
764
  createWixBookingsContext,
765
+ getParticipantForm,
457
766
  init,
458
767
  listServices,
459
768
  listSlots,
@@ -25,10 +25,8 @@ function loadWixBookingsConfig(projectRoot) {
25
25
  }
26
26
  const MAX_SLOTS_PER_QUERY = 200;
27
27
  const SERVICES_PAGE_SIZE = 100;
28
- const DEFAULT_FORM_ID = "00000000-0000-0000-0000-000000000000";
29
28
  function participantFormId(form) {
30
- const id = form?.id ?? form?._id ?? "";
31
- return id === DEFAULT_FORM_ID ? "" : id;
29
+ return form?.id ?? form?._id ?? "";
32
30
  }
33
31
  function formatPrice(service) {
34
32
  const price = service.payment?.fixed?.price;
@@ -166,11 +164,11 @@ export {
166
164
  MAX_SLOTS_PER_QUERY as M,
167
165
  mapClassSlot as a,
168
166
  mapService as b,
169
- loadWixBookingsConfig as c,
170
- participantFormId as d,
167
+ paymentPreferenceFromService as c,
168
+ loadWixBookingsConfig as d,
171
169
  getBookingServiceById as g,
172
170
  localDateStrInTimeZone as l,
173
171
  mapAppointmentSlot as m,
174
- paymentPreferenceFromService as p,
172
+ participantFormId as p,
175
173
  queryBookingServices as q
176
174
  };
package/dist/tools.d.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  import { PluginAgentKitContext, PluginAgentKitResult, PluginSetupContext, PluginSetupResult } from '@jay-framework/stack-server-runtime';
2
+ import { JayHtmlValidatorFn } from '@jay-framework/compiler-shared';
2
3
 
3
4
  declare function generateWixBookingsAgentKit(ctx: PluginAgentKitContext): Promise<PluginAgentKitResult>;
4
5
 
5
6
  declare function setupWixBookings(ctx: PluginSetupContext): Promise<PluginSetupResult>;
6
7
  declare const setup: typeof setupWixBookings;
7
8
 
8
- export { generateWixBookingsAgentKit, setup, setupWixBookings };
9
+ /**
10
+ * wix-bookings plugin validator (DL #52 §6): the participant address on `booking-flow` pages.
11
+ *
12
+ * - A page that binds address refs must bind every part's input(s), and no unknown part or
13
+ * child (the wix-forms rule 6 core, `checkAddressBindings`): core grafts unknown `ref=`
14
+ * sub-tags silently, so this is the only build-time guard.
15
+ * - A page that binds no address ref (`BOOKINGS-ADDRESS-UNBOUND`): an error when a site service's
16
+ * participant form has an address (agent-kit `services.yaml`), nothing when none has one, a
17
+ * warning when it cannot be known. A page silences only this finding with
18
+ * `wix-bookings: { allow-unbound-address: true }` in its jay-validations block.
19
+ */
20
+
21
+ declare const validateBookingFlowBindings: JayHtmlValidatorFn;
22
+
23
+ export { generateWixBookingsAgentKit, setup, setupWixBookings, validateBookingFlowBindings };