@jay-framework/wix-bookings 0.25.5 → 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,7 +1,7 @@
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 } from "@jay-framework/wix-server-client/client";
4
- import { createSignal } from "@jay-framework/component";
3
+ import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT, ensureSessionFresh } from "@jay-framework/wix-server-client/client";
4
+ import { createSignal, createEffect } from "@jay-framework/component";
5
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
6
6
  const MAX_SLOTS_PER_QUERY = 200;
7
7
  const SERVICES_PAGE_SIZE = 100;
@@ -472,6 +472,34 @@ function provideWixBookingsContext(config) {
472
472
  const init = makeJayInit().withClient(async ({ config }) => {
473
473
  provideWixBookingsContext(config);
474
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 || {});
475
503
  const listServices = createActionCaller("wixBookings.listServices", "GET");
476
504
  const listSlots = createActionCaller("wixBookings.listSlots", "GET");
477
505
  const createBooking = createActionCaller("wixBookings.createBooking", "POST");
@@ -503,7 +531,14 @@ function validateFormSummaryField(field, value) {
503
531
  return "";
504
532
  }
505
533
  function validateFormField(field, value) {
506
- 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();
507
542
  if (field.required && !trimmed) {
508
543
  return `${field.label} is required.`;
509
544
  }
@@ -536,127 +571,583 @@ function validateFormField(field, value) {
536
571
  }
537
572
  return "";
538
573
  }
539
- function parseSubmissionFieldErrors(responseBody) {
540
- try {
541
- const parsed = JSON.parse(responseBody);
542
- const fieldErrors = {};
543
- const violations = parsed.details?.validationError?.fieldViolations ?? [];
544
- for (const violation of violations) {
545
- for (const fieldError of violation.data?.errors ?? []) {
546
- if (fieldError.errorPath && !fieldErrors[fieldError.errorPath]) {
547
- fieldErrors[fieldError.errorPath] = fieldError.errorMessage ?? "Invalid value";
548
- }
549
- }
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}`);
550
601
  }
551
- 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;
552
619
  } catch {
553
- 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;
663
+ }
664
+ return errors;
665
+ }
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 = {};
554
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;
555
757
  }
556
- function toContractFields(fields) {
557
- return fields.map((field) => ({
558
- target: field.target,
758
+ function fieldToViewState(field, state) {
759
+ const viewState = {
559
760
  label: field.label,
560
- inputType: field.inputType,
561
- isTextarea: field.inputType === "textarea",
562
761
  required: field.required,
563
- placeholder: field.placeholder,
564
- hasOptions: field.options.length > 0
565
- }));
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;
818
+ }
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
+ });
566
866
  }
567
- function WixFormInteractive(props, refs, viewStateSignals, carryForward) {
867
+ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
568
868
  const [isSubmitting, setIsSubmitting] = createSignal(false);
569
869
  const [statusMessage, setStatusMessage] = createSignal("");
570
- const [fieldErrors, setFieldErrors] = createSignal([]);
571
- async function readFormValues() {
572
- const values = {};
573
- const inputReads = refs.fields?.formInputs?.map((input, field) => input.exec$((element) => ({
574
- target: field.target,
575
- value: element.value
576
- }))) ?? [];
577
- const textareaReads = refs.fields?.formTextareas?.map((textarea, field) => textarea.exec$((element) => ({
578
- target: field.target,
579
- value: element.value
580
- }))) ?? [];
581
- const selectReads = refs.fields?.formSelects?.map((select, field) => select.exec$((element) => ({
582
- target: field.target,
583
- value: element.value
584
- }))) ?? [];
585
- const resolved = await Promise.all([...inputReads, ...textareaReads, ...selectReads]);
586
- for (const entry of resolved) {
587
- values[entry.target] = entry.value;
588
- }
589
- return values;
590
- }
591
- async function clearFormValues() {
592
- const clears = [
593
- ...refs.fields?.formInputs?.map((input) => input.exec$((element) => {
594
- element.value = "";
595
- })) ?? [],
596
- ...refs.fields?.formTextareas?.map((textarea) => textarea.exec$((element) => {
597
- element.value = "";
598
- })) ?? [],
599
- ...refs.fields?.formSelects?.map((select) => select.exec$((element) => {
600
- element.value = "";
601
- })) ?? []
602
- ];
603
- await Promise.all(clears);
604
- }
605
- 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({});
606
936
  setStatusMessage("");
607
- setFieldErrors([]);
608
- const values = await readFormValues();
609
- const clientErrors = [];
610
- for (const field of carryForward.fields) {
611
- const errorMessage = validateFormField(field, values[field.target] ?? "");
612
- if (errorMessage) {
613
- 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));
614
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;
969
+ }
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();
987
+ return;
615
988
  }
616
- if (clientErrors.length) {
617
- setFieldErrors(clientErrors);
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);
618
997
  return;
619
998
  }
620
- setIsSubmitting(true);
621
- try {
622
- await submitForm({
623
- formId: carryForward.formId || (typeof props.formId === "string" ? props.formId : ""),
624
- values
625
- });
626
- setStatusMessage("Form submitted successfully.");
627
- await clearFormValues();
628
- } catch (error) {
629
- if (error instanceof WixApiError) {
630
- const mapped = parseSubmissionFieldErrors(error.responseBody);
631
- const mappedErrors = Object.entries(mapped).map(([target, errorMessage]) => ({
632
- target,
633
- errorMessage
634
- }));
635
- if (mappedErrors.length) {
636
- setFieldErrors(mappedErrors);
637
- return;
638
- }
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);
639
1012
  }
640
- const rawMessage = error instanceof Error ? error.message : "Something went wrong. Please try again.";
641
- const message = rawMessage.includes("403") ? "Form submission denied. Add Wix Forms permission to your API key in the Wix dashboard." : rawMessage;
642
- setStatusMessage(message);
643
- } finally {
644
- 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;
645
1024
  }
646
- });
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
+ }
647
1035
  return {
648
- render: () => ({
649
- fields: toContractFields(carryForward.fields),
650
- options: carryForward.options,
651
- isLoading: carryForward.fields.length === 0 && !carryForward.loadError,
652
- loadError: carryForward.loadError ?? (carryForward.fields.length ? "" : "Could not load the form. Please try again later."),
1036
+ render: () => buildFormViewState(carryForward.fields, {
653
1037
  isSubmitting: isSubmitting(),
654
1038
  statusMessage: statusMessage(),
655
- fieldErrors: fieldErrors()
1039
+ loadError: carryForward.loadError ?? "",
1040
+ errorByTarget: errorByTarget(),
1041
+ invalidByTarget: invalidByTarget(),
1042
+ valueByTarget: values(),
1043
+ isSubmitted: isSubmitted(),
1044
+ submitFailure: submitFailure()
656
1045
  })
657
1046
  };
658
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
+ }
659
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
+ }
660
1151
  const DEFAULT_PARTICIPANT_FIELDS = [
661
1152
  { target: "first_name", label: "First Name", type: "STRING", required: true },
662
1153
  { target: "last_name", label: "Last Name", type: "STRING", required: true },
@@ -683,6 +1174,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
683
1174
  const [showServices, setShowServices] = createSignal(true);
684
1175
  const showNoServices = _carryForward.services.length === 0 && !_carryForward.servicesError;
685
1176
  const servicesError = _carryForward.servicesError ?? "";
1177
+ const servicesFailure = _carryForward.servicesFailure ?? ServicesFailure.NONE;
686
1178
  const [hasSlots, setHasSlots] = createSignal(false);
687
1179
  const [showSlots, setShowSlots] = createSignal(false);
688
1180
  const [showForm, setShowForm] = createSignal(false);
@@ -692,14 +1184,23 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
692
1184
  const [slots, setSlots] = createSignal([]);
693
1185
  const [slotsLoading, setSlotsLoading] = createSignal(false);
694
1186
  const [slotsMessage, setSlotsMessage] = createSignal("");
1187
+ const [slotsFailure, setSlotsFailure] = createSignal(SlotsFailure.NONE);
695
1188
  const [formFields, setFormFields] = createSignal([]);
696
1189
  const [formLoading, setFormLoading] = createSignal(false);
697
1190
  const [isBooking, setIsBooking] = createSignal(false);
698
1191
  const [bookingStatus, setBookingStatus] = createSignal("");
699
1192
  const [bookingError, setBookingError] = createSignal("");
1193
+ const [bookingFailure, setBookingFailure] = createSignal(BookingFailure.NONE);
1194
+ const [isConfirmed, setIsConfirmed] = createSignal(false);
700
1195
  function resetBookingMessages() {
701
1196
  setBookingStatus("");
702
1197
  setBookingError("");
1198
+ setBookingFailure(BookingFailure.NONE);
1199
+ setIsConfirmed(false);
1200
+ }
1201
+ function failBooking(failure, message) {
1202
+ setBookingFailure(failure);
1203
+ setBookingError(message);
703
1204
  }
704
1205
  async function onSelectService(service) {
705
1206
  resetBookingMessages();
@@ -711,6 +1212,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
711
1212
  setShowForm(false);
712
1213
  setSlotsLoading(true);
713
1214
  setSlotsMessage("");
1215
+ setSlotsFailure(SlotsFailure.NONE);
714
1216
  setSlots([]);
715
1217
  setHasSlots(false);
716
1218
  try {
@@ -725,6 +1227,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
725
1227
  setSlots(result.slots);
726
1228
  setHasSlots(result.slots.length > 0);
727
1229
  } catch (error) {
1230
+ setSlotsFailure(SlotsFailure.UNKNOWN);
728
1231
  setSlotsMessage(error instanceof Error ? error.message : "Could not load availability.");
729
1232
  } finally {
730
1233
  setSlotsLoading(false);
@@ -754,7 +1257,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
754
1257
  })));
755
1258
  } catch (error) {
756
1259
  const message = error instanceof Error ? error.message : "Could not load participant form fields.";
757
- setBookingError(message);
1260
+ failBooking(BookingFailure.FORM_UNAVAILABLE, message);
758
1261
  setShowForm(false);
759
1262
  } finally {
760
1263
  setFormLoading(false);
@@ -778,14 +1281,13 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
778
1281
  if (!service || !slot) {
779
1282
  return;
780
1283
  }
781
- setBookingError("");
782
- setBookingStatus("");
1284
+ resetBookingMessages();
783
1285
  const formValues = await readFormValues();
784
1286
  const fields = formFields();
785
1287
  for (const field of fields) {
786
1288
  const validationError = validateFormSummaryField(field, formValues[field.target] ?? "");
787
1289
  if (validationError) {
788
- setBookingError(validationError);
1290
+ failBooking(BookingFailure.VALIDATION, validationError);
789
1291
  return;
790
1292
  }
791
1293
  }
@@ -809,19 +1311,12 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
809
1311
  return;
810
1312
  }
811
1313
  setBookingStatus("Booking confirmed!");
1314
+ setIsConfirmed(true);
812
1315
  setShowForm(false);
813
1316
  setSelectedSlot(null);
814
1317
  } catch (error) {
815
- const rawMessage = error instanceof Error ? error.message : "Booking failed. Please try again.";
816
- let message = rawMessage;
817
- if (rawMessage.includes("/ecom/v2/carts") && rawMessage.includes("403")) {
818
- message = "Checkout API access denied. Add Wix eCommerce (carts/checkout) permission to your API key in the Wix dashboard.";
819
- } else if (rawMessage.includes("redirect-session") && rawMessage.includes("400")) {
820
- message = "Checkout redirect rejected. In Wix Dashboard → Headless Settings → your client → Allowed redirect domains, add localhost:3000 for local dev (or your deployed domain).";
821
- } else if (rawMessage.includes("get-checkout-url")) {
822
- message = "Could not open Wix checkout. Publish your Wix site (hosted checkout requires a published site).";
823
- }
824
- setBookingError(message);
1318
+ const { failure, message } = describeBookingError(error);
1319
+ failBooking(failure, message);
825
1320
  } finally {
826
1321
  setIsBooking(false);
827
1322
  }
@@ -836,6 +1331,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
836
1331
  setSelectedServiceName("");
837
1332
  setSlots([]);
838
1333
  setSlotsMessage("");
1334
+ setSlotsFailure(SlotsFailure.NONE);
839
1335
  setHasSlots(false);
840
1336
  setFormFields([]);
841
1337
  }
@@ -864,6 +1360,7 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
864
1360
  services: services(),
865
1361
  servicesLoading: false,
866
1362
  servicesError,
1363
+ servicesFailure,
867
1364
  showServices: showServices(),
868
1365
  showNoServices,
869
1366
  showSlots: showSlots(),
@@ -872,12 +1369,19 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
872
1369
  slots: slots().map(toContractSlot),
873
1370
  slotsLoading: slotsLoading(),
874
1371
  slotsMessage: slotsMessage(),
1372
+ slotsFailure: slotsFailure(),
875
1373
  hasSlots: hasSlots(),
876
1374
  formFields: formFields(),
877
1375
  formLoading: formLoading(),
878
1376
  isBooking: isBooking(),
879
1377
  bookingStatus: bookingStatus(),
880
- bookingError: bookingError()
1378
+ bookingError: bookingError(),
1379
+ bookingState: bookingStateOf({
1380
+ isBooking: isBooking(),
1381
+ isConfirmed: isConfirmed(),
1382
+ failure: bookingFailure()
1383
+ }),
1384
+ bookingFailure: bookingFailure()
881
1385
  })
882
1386
  };
883
1387
  }