@gorgo/medusa-integration 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/.medusa/server/src/admin/index.js +2259 -0
  2. package/.medusa/server/src/admin/index.mjs +2257 -0
  3. package/.medusa/server/src/api/admin/integrations/[provider_id]/enable/route.d.ts +5 -0
  4. package/.medusa/server/src/api/admin/integrations/[provider_id]/enable/route.js +17 -0
  5. package/.medusa/server/src/api/admin/integrations/[provider_id]/route.d.ts +7 -0
  6. package/.medusa/server/src/api/admin/integrations/[provider_id]/route.js +46 -0
  7. package/.medusa/server/src/api/admin/integrations/[provider_id]/test-connection/route.d.ts +3 -0
  8. package/.medusa/server/src/api/admin/integrations/[provider_id]/test-connection/route.js +16 -0
  9. package/.medusa/server/src/api/admin/integrations/_helpers.d.ts +16 -0
  10. package/.medusa/server/src/api/admin/integrations/_helpers.js +52 -0
  11. package/.medusa/server/src/api/admin/integrations/middlewares.d.ts +2 -0
  12. package/.medusa/server/src/api/admin/integrations/middlewares.js +21 -0
  13. package/.medusa/server/src/api/admin/integrations/route.d.ts +3 -0
  14. package/.medusa/server/src/api/admin/integrations/route.js +11 -0
  15. package/.medusa/server/src/api/admin/integrations/validators.d.ts +11 -0
  16. package/.medusa/server/src/api/admin/integrations/validators.js +15 -0
  17. package/.medusa/server/src/api/middlewares.d.ts +2 -0
  18. package/.medusa/server/src/api/middlewares.js +10 -0
  19. package/.medusa/server/src/index.d.ts +10 -0
  20. package/.medusa/server/src/index.js +22 -0
  21. package/.medusa/server/src/jobs/test-integration-connections.d.ts +16 -0
  22. package/.medusa/server/src/jobs/test-integration-connections.js +53 -0
  23. package/.medusa/server/src/modules/integration/descriptor/__tests__/build-zod.unit.spec.d.ts +1 -0
  24. package/.medusa/server/src/modules/integration/descriptor/__tests__/build-zod.unit.spec.js +64 -0
  25. package/.medusa/server/src/modules/integration/descriptor/__tests__/define.unit.spec.d.ts +1 -0
  26. package/.medusa/server/src/modules/integration/descriptor/__tests__/define.unit.spec.js +41 -0
  27. package/.medusa/server/src/modules/integration/descriptor/__tests__/introspect.unit.spec.d.ts +1 -0
  28. package/.medusa/server/src/modules/integration/descriptor/__tests__/introspect.unit.spec.js +93 -0
  29. package/.medusa/server/src/modules/integration/descriptor/__tests__/validate.unit.spec.d.ts +1 -0
  30. package/.medusa/server/src/modules/integration/descriptor/__tests__/validate.unit.spec.js +64 -0
  31. package/.medusa/server/src/modules/integration/descriptor/build-zod.d.ts +8 -0
  32. package/.medusa/server/src/modules/integration/descriptor/build-zod.js +82 -0
  33. package/.medusa/server/src/modules/integration/descriptor/define.d.ts +74 -0
  34. package/.medusa/server/src/modules/integration/descriptor/define.js +31 -0
  35. package/.medusa/server/src/modules/integration/descriptor/index.d.ts +5 -0
  36. package/.medusa/server/src/modules/integration/descriptor/index.js +22 -0
  37. package/.medusa/server/src/modules/integration/descriptor/introspect.d.ts +5 -0
  38. package/.medusa/server/src/modules/integration/descriptor/introspect.js +67 -0
  39. package/.medusa/server/src/modules/integration/descriptor/meta.d.ts +7 -0
  40. package/.medusa/server/src/modules/integration/descriptor/meta.js +3 -0
  41. package/.medusa/server/src/modules/integration/descriptor/option.d.ts +104 -0
  42. package/.medusa/server/src/modules/integration/descriptor/option.js +3 -0
  43. package/.medusa/server/src/modules/integration/descriptor/validate.d.ts +29 -0
  44. package/.medusa/server/src/modules/integration/descriptor/validate.js +69 -0
  45. package/.medusa/server/src/modules/integration/index.d.ts +22 -0
  46. package/.medusa/server/src/modules/integration/index.js +15 -0
  47. package/.medusa/server/src/modules/integration/loaders/index.d.ts +1 -0
  48. package/.medusa/server/src/modules/integration/loaders/index.js +9 -0
  49. package/.medusa/server/src/modules/integration/loaders/load-providers.d.ts +5 -0
  50. package/.medusa/server/src/modules/integration/loaders/load-providers.js +35 -0
  51. package/.medusa/server/src/modules/integration/migrations/Migration20260610215533.d.ts +5 -0
  52. package/.medusa/server/src/modules/integration/migrations/Migration20260610215533.js +18 -0
  53. package/.medusa/server/src/modules/integration/migrations/Migration20260618154037.d.ts +5 -0
  54. package/.medusa/server/src/modules/integration/migrations/Migration20260618154037.js +27 -0
  55. package/.medusa/server/src/modules/integration/migrations/Migration20260622120502.d.ts +5 -0
  56. package/.medusa/server/src/modules/integration/migrations/Migration20260622120502.js +14 -0
  57. package/.medusa/server/src/modules/integration/migrations/Migration20260701095518.d.ts +5 -0
  58. package/.medusa/server/src/modules/integration/migrations/Migration20260701095518.js +14 -0
  59. package/.medusa/server/src/modules/integration/migrations/Migration20260708072033.d.ts +5 -0
  60. package/.medusa/server/src/modules/integration/migrations/Migration20260708072033.js +14 -0
  61. package/.medusa/server/src/modules/integration/models/integration.d.ts +13 -0
  62. package/.medusa/server/src/modules/integration/models/integration.js +27 -0
  63. package/.medusa/server/src/modules/integration/services/__tests__/crypto.unit.spec.d.ts +1 -0
  64. package/.medusa/server/src/modules/integration/services/__tests__/crypto.unit.spec.js +33 -0
  65. package/.medusa/server/src/modules/integration/services/__tests__/integration-provider.unit.spec.d.ts +1 -0
  66. package/.medusa/server/src/modules/integration/services/__tests__/integration-provider.unit.spec.js +77 -0
  67. package/.medusa/server/src/modules/integration/services/__tests__/secrets.unit.spec.d.ts +1 -0
  68. package/.medusa/server/src/modules/integration/services/__tests__/secrets.unit.spec.js +33 -0
  69. package/.medusa/server/src/modules/integration/services/crypto.d.ts +10 -0
  70. package/.medusa/server/src/modules/integration/services/crypto.js +41 -0
  71. package/.medusa/server/src/modules/integration/services/index.d.ts +3 -0
  72. package/.medusa/server/src/modules/integration/services/index.js +11 -0
  73. package/.medusa/server/src/modules/integration/services/integration-module.d.ts +113 -0
  74. package/.medusa/server/src/modules/integration/services/integration-module.js +219 -0
  75. package/.medusa/server/src/modules/integration/services/integration-provider.d.ts +49 -0
  76. package/.medusa/server/src/modules/integration/services/integration-provider.js +76 -0
  77. package/.medusa/server/src/modules/integration/services/secrets.d.ts +11 -0
  78. package/.medusa/server/src/modules/integration/services/secrets.js +31 -0
  79. package/.medusa/server/src/modules/integration/types/index.d.ts +13 -0
  80. package/.medusa/server/src/modules/integration/types/index.js +10 -0
  81. package/.medusa/server/src/modules/integration/utils/abstract-integration-provider.d.ts +39 -0
  82. package/.medusa/server/src/modules/integration/utils/abstract-integration-provider.js +42 -0
  83. package/.medusa/server/src/modules/integration/utils/index.d.ts +1 -0
  84. package/.medusa/server/src/modules/integration/utils/index.js +6 -0
  85. package/.medusa/server/src/subscribers/invalidate-options-cache.d.ts +5 -0
  86. package/.medusa/server/src/subscribers/invalidate-options-cache.js +13 -0
  87. package/.medusa/server/src/types/bundles.d.ts +1 -0
  88. package/.medusa/server/src/types/bundles.js +38 -0
  89. package/.medusa/server/src/types/http/index.d.ts +1 -0
  90. package/.medusa/server/src/types/http/index.js +18 -0
  91. package/.medusa/server/src/types/http/integration/admin/entities.d.ts +32 -0
  92. package/.medusa/server/src/types/http/integration/admin/entities.js +3 -0
  93. package/.medusa/server/src/types/http/integration/admin/index.d.ts +2 -0
  94. package/.medusa/server/src/types/http/integration/admin/index.js +19 -0
  95. package/.medusa/server/src/types/http/integration/admin/responses.d.ts +19 -0
  96. package/.medusa/server/src/types/http/integration/admin/responses.js +3 -0
  97. package/.medusa/server/src/types/http/integration/index.d.ts +1 -0
  98. package/.medusa/server/src/types/http/integration/index.js +18 -0
  99. package/.medusa/server/src/types/index.d.ts +3 -0
  100. package/.medusa/server/src/types/index.js +20 -0
  101. package/.medusa/server/src/types/integration/common.d.ts +70 -0
  102. package/.medusa/server/src/types/integration/common.js +3 -0
  103. package/.medusa/server/src/types/integration/index.d.ts +1 -0
  104. package/.medusa/server/src/types/integration/index.js +18 -0
  105. package/.medusa/server/src/workflows/integration/index.d.ts +2 -0
  106. package/.medusa/server/src/workflows/integration/index.js +19 -0
  107. package/.medusa/server/src/workflows/integration/steps/apply-integration-section.d.ts +22 -0
  108. package/.medusa/server/src/workflows/integration/steps/apply-integration-section.js +70 -0
  109. package/.medusa/server/src/workflows/integration/steps/delete-integration-record.d.ts +6 -0
  110. package/.medusa/server/src/workflows/integration/steps/delete-integration-record.js +16 -0
  111. package/.medusa/server/src/workflows/integration/steps/emit-integration-event.d.ts +5 -0
  112. package/.medusa/server/src/workflows/integration/steps/emit-integration-event.js +11 -0
  113. package/.medusa/server/src/workflows/integration/steps/index.d.ts +6 -0
  114. package/.medusa/server/src/workflows/integration/steps/index.js +16 -0
  115. package/.medusa/server/src/workflows/integration/steps/run-test-connection.d.ts +4 -0
  116. package/.medusa/server/src/workflows/integration/steps/run-test-connection.js +20 -0
  117. package/.medusa/server/src/workflows/integration/steps/set-integration-enabled.d.ts +19 -0
  118. package/.medusa/server/src/workflows/integration/steps/set-integration-enabled.js +27 -0
  119. package/.medusa/server/src/workflows/integration/steps/upsert-integration-record.d.ts +9 -0
  120. package/.medusa/server/src/workflows/integration/steps/upsert-integration-record.js +18 -0
  121. package/.medusa/server/src/workflows/integration/workflows/delete-integration.d.ts +7 -0
  122. package/.medusa/server/src/workflows/integration/workflows/delete-integration.js +18 -0
  123. package/.medusa/server/src/workflows/integration/workflows/index.d.ts +4 -0
  124. package/.medusa/server/src/workflows/integration/workflows/index.js +12 -0
  125. package/.medusa/server/src/workflows/integration/workflows/set-integration-enabled.d.ts +20 -0
  126. package/.medusa/server/src/workflows/integration/workflows/set-integration-enabled.js +20 -0
  127. package/.medusa/server/src/workflows/integration/workflows/test-integration-connection.d.ts +5 -0
  128. package/.medusa/server/src/workflows/integration/workflows/test-integration-connection.js +21 -0
  129. package/.medusa/server/src/workflows/integration/workflows/upsert-integration.d.ts +8 -0
  130. package/.medusa/server/src/workflows/integration/workflows/upsert-integration.js +30 -0
  131. package/LICENSE +21 -0
  132. package/README.md +46 -0
  133. package/package.json +79 -0
@@ -0,0 +1,2257 @@
1
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
+ import { defineRouteConfig } from "@medusajs/admin-sdk";
3
+ import { PuzzleSolid, CogSixTooth, Spinner, EllipsisHorizontal, Trash, PencilSquare } from "@medusajs/icons";
4
+ import { clx, Container, Heading, Text, Badge, StatusBadge, Label, Input, Select, Switch, Textarea, toast, Drawer, Button, usePrompt, DropdownMenu, IconButton } from "@medusajs/ui";
5
+ import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
6
+ import { useTranslation } from "react-i18next";
7
+ import { Link, useParams, useNavigate } from "react-router-dom";
8
+ import Medusa from "@medusajs/js-sdk";
9
+ import React, { useState } from "react";
10
+ import { LayoutComposer } from "@medusajs/dashboard/components";
11
+ const sdk = new Medusa({
12
+ baseUrl: "/",
13
+ debug: false,
14
+ auth: {
15
+ type: "session"
16
+ }
17
+ });
18
+ const IntegrationIcon = ({
19
+ src,
20
+ alt,
21
+ size = "base"
22
+ }) => {
23
+ const dim = size === "small" ? "h-6 w-6" : "h-8 w-8";
24
+ return /* @__PURE__ */ jsx(
25
+ "div",
26
+ {
27
+ className: clx(
28
+ "bg-ui-bg-component shadow-borders-base flex shrink-0 items-center justify-center overflow-hidden rounded-md",
29
+ dim
30
+ ),
31
+ children: src ? /* @__PURE__ */ jsx("img", { src, alt, className: "h-full w-full object-cover" }) : /* @__PURE__ */ jsx(PuzzleSolid, { className: "text-ui-fg-subtle" })
32
+ }
33
+ );
34
+ };
35
+ const IntegrationsPage = () => {
36
+ const { t } = useTranslation();
37
+ const { data, isLoading } = useQuery({
38
+ queryKey: ["integration-overview"],
39
+ queryFn: () => sdk.client.fetch("/admin/integrations")
40
+ });
41
+ const items = (data == null ? void 0 : data.integrations) ?? [];
42
+ const byModule = items.reduce((acc, i) => {
43
+ var _a;
44
+ (acc[_a = i.module] ?? (acc[_a] = [])).push(i);
45
+ return acc;
46
+ }, {});
47
+ return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
48
+ /* @__PURE__ */ jsx("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("integration.list.title") }) }),
49
+ isLoading ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center px-6 py-8", children: /* @__PURE__ */ jsx(Spinner, { className: "text-ui-fg-subtle animate-spin" }) }) : items.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("integration.list.empty") }) }) : Object.entries(byModule).map(([module, group]) => /* @__PURE__ */ jsxs("div", { className: "px-6 py-4", children: [
50
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: t(`integration.modules.${module}`) }),
51
+ /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-col gap-2", children: group.map((i) => {
52
+ const configured = i.is_configured && i.is_enabled;
53
+ return /* @__PURE__ */ jsxs(
54
+ Link,
55
+ {
56
+ to: `/settings/integrations/${i.provider_id}`,
57
+ className: "flex items-center justify-between rounded-md border px-3 py-2 hover:bg-ui-bg-base-hover",
58
+ children: [
59
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
60
+ /* @__PURE__ */ jsx(IntegrationIcon, { src: i.icon, alt: t(i.display_name), size: "small" }),
61
+ /* @__PURE__ */ jsx(Text, { size: "small", children: t(i.display_name) }),
62
+ i.instance_id && /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: i.instance_id })
63
+ ] }),
64
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
65
+ i.last_test_status === "ok" && /* @__PURE__ */ jsx(Badge, { color: "green", size: "2xsmall", children: t("integration.list.tested") }),
66
+ i.last_test_status === "fail" && /* @__PURE__ */ jsx(Badge, { color: "red", size: "2xsmall", children: t("integration.list.testFailed") }),
67
+ i.is_configured && !i.is_complete ? /* @__PURE__ */ jsx(StatusBadge, { color: "orange", children: t("integration.status.incomplete") }) : /* @__PURE__ */ jsx(StatusBadge, { color: configured ? "green" : "grey", children: !i.is_configured ? t("integration.status.notConfigured") : i.is_enabled ? t("integration.status.enabled") : t("integration.status.disabled") })
68
+ ] })
69
+ ]
70
+ },
71
+ i.provider_id
72
+ );
73
+ }) })
74
+ ] }, module))
75
+ ] });
76
+ };
77
+ const config = defineRouteConfig({
78
+ label: "integration.list.title",
79
+ translationNs: "translation",
80
+ icon: CogSixTooth
81
+ });
82
+ const IntegrationsBreadcrumb = () => {
83
+ const { t } = useTranslation();
84
+ return /* @__PURE__ */ jsx(Fragment, { children: t("integration.list.title") });
85
+ };
86
+ const handle$1 = {
87
+ breadcrumb: () => /* @__PURE__ */ jsx(IntegrationsBreadcrumb, {})
88
+ };
89
+ const Dash = () => /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "text-ui-fg-subtle", children: "-" });
90
+ const IntegrationFieldValue = ({
91
+ field,
92
+ value,
93
+ secretConfigured = false
94
+ }) => {
95
+ var _a;
96
+ const { t } = useTranslation();
97
+ if (field.readonly && (value == null || value === "")) value = field.readonlyValue;
98
+ if (field.secret || field.control === "secret") {
99
+ return secretConfigured ? /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: "••••••••" }) : /* @__PURE__ */ jsx(Dash, {});
100
+ }
101
+ if (field.control === "switch") {
102
+ if (value == null) return /* @__PURE__ */ jsx(Dash, {});
103
+ return /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: value ? "green" : "grey", children: value ? t("integration.status.enabled") : t("integration.status.disabled") });
104
+ }
105
+ if (field.control === "json") {
106
+ if (Array.isArray(value)) {
107
+ return value.length ? /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: t("integration.form.items", { count: value.length }) }) : /* @__PURE__ */ jsx(Dash, {});
108
+ }
109
+ if (value == null) return /* @__PURE__ */ jsx(Dash, {});
110
+ return /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: t("integration.status.configured") });
111
+ }
112
+ if (value == null || value === "") return /* @__PURE__ */ jsx(Dash, {});
113
+ if (field.control === "select") {
114
+ const labelKey = (_a = field.optionLabels) == null ? void 0 : _a[String(value)];
115
+ return /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: labelKey ? t(labelKey) : String(value) });
116
+ }
117
+ return /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: String(value) });
118
+ };
119
+ var isCheckBoxInput = (element) => element.type === "checkbox";
120
+ var isDateObject = (value) => value instanceof Date;
121
+ var isNullOrUndefined = (value) => value == null;
122
+ const isObjectType = (value) => typeof value === "object";
123
+ var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
124
+ var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
125
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
126
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
127
+ var isPlainObject = (tempObject) => {
128
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
129
+ return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
130
+ };
131
+ var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
132
+ function cloneObject(data) {
133
+ let copy;
134
+ const isArray = Array.isArray(data);
135
+ if (data instanceof Date) {
136
+ copy = new Date(data);
137
+ } else if (data instanceof Set) {
138
+ copy = new Set(data);
139
+ } else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) && (isArray || isObject(data))) {
140
+ copy = isArray ? [] : {};
141
+ if (!isArray && !isPlainObject(data)) {
142
+ copy = data;
143
+ } else {
144
+ for (const key in data) {
145
+ if (data.hasOwnProperty(key)) {
146
+ copy[key] = cloneObject(data[key]);
147
+ }
148
+ }
149
+ }
150
+ } else {
151
+ return data;
152
+ }
153
+ return copy;
154
+ }
155
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
156
+ var isUndefined = (val) => val === void 0;
157
+ var get = (object, path, defaultValue) => {
158
+ if (!path || !isObject(object)) {
159
+ return defaultValue;
160
+ }
161
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result2, key) => isNullOrUndefined(result2) ? result2 : result2[key], object);
162
+ return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
163
+ };
164
+ var isBoolean = (value) => typeof value === "boolean";
165
+ const EVENTS = {
166
+ BLUR: "blur",
167
+ FOCUS_OUT: "focusout",
168
+ CHANGE: "change"
169
+ };
170
+ const VALIDATION_MODE = {
171
+ onBlur: "onBlur",
172
+ onChange: "onChange",
173
+ onSubmit: "onSubmit",
174
+ onTouched: "onTouched",
175
+ all: "all"
176
+ };
177
+ const INPUT_VALIDATION_RULES = {
178
+ max: "max",
179
+ min: "min",
180
+ maxLength: "maxLength",
181
+ minLength: "minLength",
182
+ pattern: "pattern",
183
+ required: "required",
184
+ validate: "validate"
185
+ };
186
+ const HookFormContext = React.createContext(null);
187
+ const useFormContext = () => React.useContext(HookFormContext);
188
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
189
+ const result = {
190
+ defaultValues: control._defaultValues
191
+ };
192
+ for (const key in formState) {
193
+ Object.defineProperty(result, key, {
194
+ get: () => {
195
+ const _key = key;
196
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
197
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
198
+ }
199
+ localProxyFormState && (localProxyFormState[_key] = true);
200
+ return formState[_key];
201
+ }
202
+ });
203
+ }
204
+ return result;
205
+ };
206
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
207
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
208
+ updateFormState(formStateData);
209
+ const { name, ...formState } = formStateData;
210
+ return isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
211
+ };
212
+ var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
213
+ var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
214
+ function useSubscribe(props) {
215
+ const _props = React.useRef(props);
216
+ _props.current = props;
217
+ React.useEffect(() => {
218
+ const subscription = !props.disabled && _props.current.subject && _props.current.subject.subscribe({
219
+ next: _props.current.next
220
+ });
221
+ return () => {
222
+ subscription && subscription.unsubscribe();
223
+ };
224
+ }, [props.disabled]);
225
+ }
226
+ function useFormState(props) {
227
+ const methods = useFormContext();
228
+ const { control = methods.control, disabled, name, exact } = props || {};
229
+ const [formState, updateFormState] = React.useState(control._formState);
230
+ const _mounted = React.useRef(true);
231
+ const _localProxyFormState = React.useRef({
232
+ isDirty: false,
233
+ isLoading: false,
234
+ dirtyFields: false,
235
+ touchedFields: false,
236
+ isValidating: false,
237
+ isValid: false,
238
+ errors: false
239
+ });
240
+ const _name = React.useRef(name);
241
+ _name.current = name;
242
+ useSubscribe({
243
+ disabled,
244
+ next: (value) => _mounted.current && shouldSubscribeByName(_name.current, value.name, exact) && shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) && updateFormState({
245
+ ...control._formState,
246
+ ...value
247
+ }),
248
+ subject: control._subjects.state
249
+ });
250
+ React.useEffect(() => {
251
+ _mounted.current = true;
252
+ _localProxyFormState.current.isValid && control._updateValid(true);
253
+ return () => {
254
+ _mounted.current = false;
255
+ };
256
+ }, [control]);
257
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
258
+ }
259
+ var isString = (value) => typeof value === "string";
260
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
261
+ if (isString(names)) {
262
+ isGlobal && _names.watch.add(names);
263
+ return get(formValues, names, defaultValue);
264
+ }
265
+ if (Array.isArray(names)) {
266
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
267
+ }
268
+ isGlobal && (_names.watchAll = true);
269
+ return formValues;
270
+ };
271
+ function useWatch(props) {
272
+ const methods = useFormContext();
273
+ const { control = methods.control, name, defaultValue, disabled, exact } = props || {};
274
+ const _name = React.useRef(name);
275
+ _name.current = name;
276
+ useSubscribe({
277
+ disabled,
278
+ subject: control._subjects.values,
279
+ next: (formState) => {
280
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
281
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
282
+ }
283
+ }
284
+ });
285
+ const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
286
+ React.useEffect(() => control._removeUnmounted());
287
+ return value;
288
+ }
289
+ var isKey = (value) => /^\w*$/.test(value);
290
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
291
+ var set = (object, path, value) => {
292
+ let index = -1;
293
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
294
+ const length = tempPath.length;
295
+ const lastIndex = length - 1;
296
+ while (++index < length) {
297
+ const key = tempPath[index];
298
+ let newValue = value;
299
+ if (index !== lastIndex) {
300
+ const objValue = object[key];
301
+ newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
302
+ }
303
+ object[key] = newValue;
304
+ object = object[key];
305
+ }
306
+ return object;
307
+ };
308
+ function useController(props) {
309
+ const methods = useFormContext();
310
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
311
+ const isArrayField = isNameInFieldArray(control._names.array, name);
312
+ const value = useWatch({
313
+ control,
314
+ name,
315
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
316
+ exact: true
317
+ });
318
+ const formState = useFormState({
319
+ control,
320
+ name
321
+ });
322
+ const _registerProps = React.useRef(control.register(name, {
323
+ ...props.rules,
324
+ value,
325
+ ...isBoolean(props.disabled) ? { disabled: props.disabled } : {}
326
+ }));
327
+ React.useEffect(() => {
328
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
329
+ const updateMounted = (name2, value2) => {
330
+ const field = get(control._fields, name2);
331
+ if (field) {
332
+ field._f.mount = value2;
333
+ }
334
+ };
335
+ updateMounted(name, true);
336
+ if (_shouldUnregisterField) {
337
+ const value2 = cloneObject(get(control._options.defaultValues, name));
338
+ set(control._defaultValues, name, value2);
339
+ if (isUndefined(get(control._formValues, name))) {
340
+ set(control._formValues, name, value2);
341
+ }
342
+ }
343
+ return () => {
344
+ (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false);
345
+ };
346
+ }, [name, control, isArrayField, shouldUnregister]);
347
+ React.useEffect(() => {
348
+ if (get(control._fields, name)) {
349
+ control._updateDisabledField({
350
+ disabled,
351
+ fields: control._fields,
352
+ name,
353
+ value: get(control._fields, name)._f.value
354
+ });
355
+ }
356
+ }, [disabled, name, control]);
357
+ return {
358
+ field: {
359
+ name,
360
+ value,
361
+ ...isBoolean(disabled) || isBoolean(formState.disabled) ? { disabled: formState.disabled || disabled } : {},
362
+ onChange: React.useCallback((event) => _registerProps.current.onChange({
363
+ target: {
364
+ value: getEventValue(event),
365
+ name
366
+ },
367
+ type: EVENTS.CHANGE
368
+ }), [name]),
369
+ onBlur: React.useCallback(() => _registerProps.current.onBlur({
370
+ target: {
371
+ value: get(control._formValues, name),
372
+ name
373
+ },
374
+ type: EVENTS.BLUR
375
+ }), [name, control]),
376
+ ref: (elm) => {
377
+ const field = get(control._fields, name);
378
+ if (field && elm) {
379
+ field._f.ref = {
380
+ focus: () => elm.focus(),
381
+ select: () => elm.select(),
382
+ setCustomValidity: (message) => elm.setCustomValidity(message),
383
+ reportValidity: () => elm.reportValidity()
384
+ };
385
+ }
386
+ }
387
+ },
388
+ formState,
389
+ fieldState: Object.defineProperties({}, {
390
+ invalid: {
391
+ enumerable: true,
392
+ get: () => !!get(formState.errors, name)
393
+ },
394
+ isDirty: {
395
+ enumerable: true,
396
+ get: () => !!get(formState.dirtyFields, name)
397
+ },
398
+ isTouched: {
399
+ enumerable: true,
400
+ get: () => !!get(formState.touchedFields, name)
401
+ },
402
+ error: {
403
+ enumerable: true,
404
+ get: () => get(formState.errors, name)
405
+ }
406
+ })
407
+ };
408
+ }
409
+ const Controller = (props) => props.render(useController(props));
410
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
411
+ ...errors[name],
412
+ types: {
413
+ ...errors[name] && errors[name].types ? errors[name].types : {},
414
+ [type]: message || true
415
+ }
416
+ } : {};
417
+ var getValidationModes = (mode) => ({
418
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
419
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
420
+ isOnChange: mode === VALIDATION_MODE.onChange,
421
+ isOnAll: mode === VALIDATION_MODE.all,
422
+ isOnTouch: mode === VALIDATION_MODE.onTouched
423
+ });
424
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (_names.watchAll || _names.watch.has(name) || [..._names.watch].some((watchName) => name.startsWith(watchName) && /^\.\w+/.test(name.slice(watchName.length))));
425
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
426
+ for (const key of fieldsNames || Object.keys(fields)) {
427
+ const field = get(fields, key);
428
+ if (field) {
429
+ const { _f, ...currentField } = field;
430
+ if (_f) {
431
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
432
+ break;
433
+ } else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
434
+ break;
435
+ } else {
436
+ iterateFieldsByAction(currentField, action);
437
+ }
438
+ } else if (isObject(currentField)) {
439
+ iterateFieldsByAction(currentField, action);
440
+ }
441
+ }
442
+ }
443
+ };
444
+ var updateFieldArrayRootError = (errors, error, name) => {
445
+ const fieldArrayErrors = compact(get(errors, name));
446
+ set(fieldArrayErrors, "root", error[name]);
447
+ set(errors, name, fieldArrayErrors);
448
+ return errors;
449
+ };
450
+ var isFileInput = (element) => element.type === "file";
451
+ var isFunction = (value) => typeof value === "function";
452
+ var isHTMLElement = (value) => {
453
+ if (!isWeb) {
454
+ return false;
455
+ }
456
+ const owner = value ? value.ownerDocument : 0;
457
+ return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
458
+ };
459
+ var isMessage = (value) => isString(value);
460
+ var isRadioInput = (element) => element.type === "radio";
461
+ var isRegex = (value) => value instanceof RegExp;
462
+ const defaultResult = {
463
+ value: false,
464
+ isValid: false
465
+ };
466
+ const validResult = { value: true, isValid: true };
467
+ var getCheckboxValue = (options) => {
468
+ if (Array.isArray(options)) {
469
+ if (options.length > 1) {
470
+ const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
471
+ return { value: values, isValid: !!values.length };
472
+ }
473
+ return options[0].checked && !options[0].disabled ? (
474
+ // @ts-expect-error expected to work in the browser
475
+ options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : { value: options[0].value, isValid: true } : validResult
476
+ ) : defaultResult;
477
+ }
478
+ return defaultResult;
479
+ };
480
+ const defaultReturn = {
481
+ isValid: false,
482
+ value: null
483
+ };
484
+ var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
485
+ isValid: true,
486
+ value: option.value
487
+ } : previous, defaultReturn) : defaultReturn;
488
+ function getValidateError(result, ref, type = "validate") {
489
+ if (isMessage(result) || Array.isArray(result) && result.every(isMessage) || isBoolean(result) && !result) {
490
+ return {
491
+ type,
492
+ message: isMessage(result) ? result : "",
493
+ ref
494
+ };
495
+ }
496
+ }
497
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
498
+ value: validationData,
499
+ message: ""
500
+ };
501
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
502
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled } = field._f;
503
+ const inputValue = get(formValues, name);
504
+ if (!mount || disabled) {
505
+ return {};
506
+ }
507
+ const inputRef = refs ? refs[0] : ref;
508
+ const setCustomValidity = (message) => {
509
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
510
+ inputRef.setCustomValidity(isBoolean(message) ? "" : message || "");
511
+ inputRef.reportValidity();
512
+ }
513
+ };
514
+ const error = {};
515
+ const isRadio = isRadioInput(ref);
516
+ const isCheckBox = isCheckBoxInput(ref);
517
+ const isRadioOrCheckbox2 = isRadio || isCheckBox;
518
+ const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
519
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
520
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
521
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
522
+ error[name] = {
523
+ type: exceedMax ? maxType : minType,
524
+ message,
525
+ ref,
526
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message)
527
+ };
528
+ };
529
+ if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox2 && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
530
+ const { value, message } = isMessage(required) ? { value: !!required, message: required } : getValueAndMessage(required);
531
+ if (value) {
532
+ error[name] = {
533
+ type: INPUT_VALIDATION_RULES.required,
534
+ message,
535
+ ref: inputRef,
536
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
537
+ };
538
+ if (!validateAllFieldCriteria) {
539
+ setCustomValidity(message);
540
+ return error;
541
+ }
542
+ }
543
+ }
544
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
545
+ let exceedMax;
546
+ let exceedMin;
547
+ const maxOutput = getValueAndMessage(max);
548
+ const minOutput = getValueAndMessage(min);
549
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
550
+ const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
551
+ if (!isNullOrUndefined(maxOutput.value)) {
552
+ exceedMax = valueNumber > maxOutput.value;
553
+ }
554
+ if (!isNullOrUndefined(minOutput.value)) {
555
+ exceedMin = valueNumber < minOutput.value;
556
+ }
557
+ } else {
558
+ const valueDate = ref.valueAsDate || new Date(inputValue);
559
+ const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
560
+ const isTime = ref.type == "time";
561
+ const isWeek = ref.type == "week";
562
+ if (isString(maxOutput.value) && inputValue) {
563
+ exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
564
+ }
565
+ if (isString(minOutput.value) && inputValue) {
566
+ exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
567
+ }
568
+ }
569
+ if (exceedMax || exceedMin) {
570
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
571
+ if (!validateAllFieldCriteria) {
572
+ setCustomValidity(error[name].message);
573
+ return error;
574
+ }
575
+ }
576
+ }
577
+ if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
578
+ const maxLengthOutput = getValueAndMessage(maxLength);
579
+ const minLengthOutput = getValueAndMessage(minLength);
580
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
581
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
582
+ if (exceedMax || exceedMin) {
583
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
584
+ if (!validateAllFieldCriteria) {
585
+ setCustomValidity(error[name].message);
586
+ return error;
587
+ }
588
+ }
589
+ }
590
+ if (pattern && !isEmpty && isString(inputValue)) {
591
+ const { value: patternValue, message } = getValueAndMessage(pattern);
592
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
593
+ error[name] = {
594
+ type: INPUT_VALIDATION_RULES.pattern,
595
+ message,
596
+ ref,
597
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
598
+ };
599
+ if (!validateAllFieldCriteria) {
600
+ setCustomValidity(message);
601
+ return error;
602
+ }
603
+ }
604
+ }
605
+ if (validate) {
606
+ if (isFunction(validate)) {
607
+ const result = await validate(inputValue, formValues);
608
+ const validateError = getValidateError(result, inputRef);
609
+ if (validateError) {
610
+ error[name] = {
611
+ ...validateError,
612
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
613
+ };
614
+ if (!validateAllFieldCriteria) {
615
+ setCustomValidity(validateError.message);
616
+ return error;
617
+ }
618
+ }
619
+ } else if (isObject(validate)) {
620
+ let validationResult = {};
621
+ for (const key in validate) {
622
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
623
+ break;
624
+ }
625
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
626
+ if (validateError) {
627
+ validationResult = {
628
+ ...validateError,
629
+ ...appendErrorsCurry(key, validateError.message)
630
+ };
631
+ setCustomValidity(validateError.message);
632
+ if (validateAllFieldCriteria) {
633
+ error[name] = validationResult;
634
+ }
635
+ }
636
+ }
637
+ if (!isEmptyObject(validationResult)) {
638
+ error[name] = {
639
+ ref: inputRef,
640
+ ...validationResult
641
+ };
642
+ if (!validateAllFieldCriteria) {
643
+ return error;
644
+ }
645
+ }
646
+ }
647
+ }
648
+ setCustomValidity(true);
649
+ return error;
650
+ };
651
+ function baseGet(object, updatePath) {
652
+ const length = updatePath.slice(0, -1).length;
653
+ let index = 0;
654
+ while (index < length) {
655
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
656
+ }
657
+ return object;
658
+ }
659
+ function isEmptyArray(obj) {
660
+ for (const key in obj) {
661
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
662
+ return false;
663
+ }
664
+ }
665
+ return true;
666
+ }
667
+ function unset(object, path) {
668
+ const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
669
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
670
+ const index = paths.length - 1;
671
+ const key = paths[index];
672
+ if (childObject) {
673
+ delete childObject[key];
674
+ }
675
+ if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) {
676
+ unset(object, paths.slice(0, -1));
677
+ }
678
+ return object;
679
+ }
680
+ var createSubject = () => {
681
+ let _observers = [];
682
+ const next = (value) => {
683
+ for (const observer of _observers) {
684
+ observer.next && observer.next(value);
685
+ }
686
+ };
687
+ const subscribe = (observer) => {
688
+ _observers.push(observer);
689
+ return {
690
+ unsubscribe: () => {
691
+ _observers = _observers.filter((o) => o !== observer);
692
+ }
693
+ };
694
+ };
695
+ const unsubscribe = () => {
696
+ _observers = [];
697
+ };
698
+ return {
699
+ get observers() {
700
+ return _observers;
701
+ },
702
+ next,
703
+ subscribe,
704
+ unsubscribe
705
+ };
706
+ };
707
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
708
+ function deepEqual(object1, object2) {
709
+ if (isPrimitive(object1) || isPrimitive(object2)) {
710
+ return object1 === object2;
711
+ }
712
+ if (isDateObject(object1) && isDateObject(object2)) {
713
+ return object1.getTime() === object2.getTime();
714
+ }
715
+ const keys1 = Object.keys(object1);
716
+ const keys2 = Object.keys(object2);
717
+ if (keys1.length !== keys2.length) {
718
+ return false;
719
+ }
720
+ for (const key of keys1) {
721
+ const val1 = object1[key];
722
+ if (!keys2.includes(key)) {
723
+ return false;
724
+ }
725
+ if (key !== "ref") {
726
+ const val2 = object2[key];
727
+ if (isDateObject(val1) && isDateObject(val2) || isObject(val1) && isObject(val2) || Array.isArray(val1) && Array.isArray(val2) ? !deepEqual(val1, val2) : val1 !== val2) {
728
+ return false;
729
+ }
730
+ }
731
+ }
732
+ return true;
733
+ }
734
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
735
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
736
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
737
+ var objectHasFunction = (data) => {
738
+ for (const key in data) {
739
+ if (isFunction(data[key])) {
740
+ return true;
741
+ }
742
+ }
743
+ return false;
744
+ };
745
+ function markFieldsDirty(data, fields = {}) {
746
+ const isParentNodeArray = Array.isArray(data);
747
+ if (isObject(data) || isParentNodeArray) {
748
+ for (const key in data) {
749
+ if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
750
+ fields[key] = Array.isArray(data[key]) ? [] : {};
751
+ markFieldsDirty(data[key], fields[key]);
752
+ } else if (!isNullOrUndefined(data[key])) {
753
+ fields[key] = true;
754
+ }
755
+ }
756
+ }
757
+ return fields;
758
+ }
759
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
760
+ const isParentNodeArray = Array.isArray(data);
761
+ if (isObject(data) || isParentNodeArray) {
762
+ for (const key in data) {
763
+ if (Array.isArray(data[key]) || isObject(data[key]) && !objectHasFunction(data[key])) {
764
+ if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) {
765
+ dirtyFieldsFromValues[key] = Array.isArray(data[key]) ? markFieldsDirty(data[key], []) : { ...markFieldsDirty(data[key]) };
766
+ } else {
767
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
768
+ }
769
+ } else {
770
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
771
+ }
772
+ }
773
+ }
774
+ return dirtyFieldsFromValues;
775
+ }
776
+ var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
777
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ? value : valueAsNumber ? value === "" ? NaN : value ? +value : value : valueAsDate && isString(value) ? new Date(value) : setValueAs ? setValueAs(value) : value;
778
+ function getFieldValue(_f) {
779
+ const ref = _f.ref;
780
+ if (_f.refs ? _f.refs.every((ref2) => ref2.disabled) : ref.disabled) {
781
+ return;
782
+ }
783
+ if (isFileInput(ref)) {
784
+ return ref.files;
785
+ }
786
+ if (isRadioInput(ref)) {
787
+ return getRadioValue(_f.refs).value;
788
+ }
789
+ if (isMultipleSelect(ref)) {
790
+ return [...ref.selectedOptions].map(({ value }) => value);
791
+ }
792
+ if (isCheckBoxInput(ref)) {
793
+ return getCheckboxValue(_f.refs).value;
794
+ }
795
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
796
+ }
797
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
798
+ const fields = {};
799
+ for (const name of fieldsNames) {
800
+ const field = get(_fields, name);
801
+ field && set(fields, name, field._f);
802
+ }
803
+ return {
804
+ criteriaMode,
805
+ names: [...fieldsNames],
806
+ fields,
807
+ shouldUseNativeValidation
808
+ };
809
+ };
810
+ var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
811
+ var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
812
+ function schemaErrorLookup(errors, _fields, name) {
813
+ const error = get(errors, name);
814
+ if (error || isKey(name)) {
815
+ return {
816
+ error,
817
+ name
818
+ };
819
+ }
820
+ const names = name.split(".");
821
+ while (names.length) {
822
+ const fieldName = names.join(".");
823
+ const field = get(_fields, fieldName);
824
+ const foundError = get(errors, fieldName);
825
+ if (field && !Array.isArray(field) && name !== fieldName) {
826
+ return { name };
827
+ }
828
+ if (foundError && foundError.type) {
829
+ return {
830
+ name: fieldName,
831
+ error: foundError
832
+ };
833
+ }
834
+ names.pop();
835
+ }
836
+ return {
837
+ name
838
+ };
839
+ }
840
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
841
+ if (mode.isOnAll) {
842
+ return false;
843
+ } else if (!isSubmitted && mode.isOnTouch) {
844
+ return !(isTouched || isBlurEvent);
845
+ } else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
846
+ return !isBlurEvent;
847
+ } else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
848
+ return isBlurEvent;
849
+ }
850
+ return true;
851
+ };
852
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
853
+ const defaultOptions = {
854
+ mode: VALIDATION_MODE.onSubmit,
855
+ reValidateMode: VALIDATION_MODE.onChange,
856
+ shouldFocusError: true
857
+ };
858
+ function createFormControl(props = {}, flushRootRender) {
859
+ let _options = {
860
+ ...defaultOptions,
861
+ ...props
862
+ };
863
+ let _formState = {
864
+ submitCount: 0,
865
+ isDirty: false,
866
+ isLoading: isFunction(_options.defaultValues),
867
+ isValidating: false,
868
+ isSubmitted: false,
869
+ isSubmitting: false,
870
+ isSubmitSuccessful: false,
871
+ isValid: false,
872
+ touchedFields: {},
873
+ dirtyFields: {},
874
+ errors: _options.errors || {},
875
+ disabled: false
876
+ };
877
+ let _fields = {};
878
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
879
+ let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
880
+ let _state = {
881
+ action: false,
882
+ mount: false,
883
+ watch: false
884
+ };
885
+ let _names = {
886
+ mount: /* @__PURE__ */ new Set(),
887
+ unMount: /* @__PURE__ */ new Set(),
888
+ array: /* @__PURE__ */ new Set(),
889
+ watch: /* @__PURE__ */ new Set()
890
+ };
891
+ let delayErrorCallback;
892
+ let timer = 0;
893
+ const _proxyFormState = {
894
+ isDirty: false,
895
+ dirtyFields: false,
896
+ touchedFields: false,
897
+ isValidating: false,
898
+ isValid: false,
899
+ errors: false
900
+ };
901
+ const _subjects = {
902
+ values: createSubject(),
903
+ array: createSubject(),
904
+ state: createSubject()
905
+ };
906
+ const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
907
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
908
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
909
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
910
+ const debounce = (callback) => (wait) => {
911
+ clearTimeout(timer);
912
+ timer = setTimeout(callback, wait);
913
+ };
914
+ const _updateValid = async (shouldUpdateValid) => {
915
+ if (_proxyFormState.isValid || shouldUpdateValid) {
916
+ const isValid = _options.resolver ? isEmptyObject((await _executeSchema()).errors) : await executeBuiltInValidation(_fields, true);
917
+ if (isValid !== _formState.isValid) {
918
+ _subjects.state.next({
919
+ isValid
920
+ });
921
+ }
922
+ }
923
+ };
924
+ const _updateIsValidating = (value) => _proxyFormState.isValidating && _subjects.state.next({
925
+ isValidating: value
926
+ });
927
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
928
+ if (args && method) {
929
+ _state.action = true;
930
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
931
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
932
+ shouldSetValues && set(_fields, name, fieldValues);
933
+ }
934
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
935
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
936
+ shouldSetValues && set(_formState.errors, name, errors);
937
+ unsetEmptyArray(_formState.errors, name);
938
+ }
939
+ if (_proxyFormState.touchedFields && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
940
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
941
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
942
+ }
943
+ if (_proxyFormState.dirtyFields) {
944
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
945
+ }
946
+ _subjects.state.next({
947
+ name,
948
+ isDirty: _getDirty(name, values),
949
+ dirtyFields: _formState.dirtyFields,
950
+ errors: _formState.errors,
951
+ isValid: _formState.isValid
952
+ });
953
+ } else {
954
+ set(_formValues, name, values);
955
+ }
956
+ };
957
+ const updateErrors = (name, error) => {
958
+ set(_formState.errors, name, error);
959
+ _subjects.state.next({
960
+ errors: _formState.errors
961
+ });
962
+ };
963
+ const _setErrors = (errors) => {
964
+ _formState.errors = errors;
965
+ _subjects.state.next({
966
+ errors: _formState.errors,
967
+ isValid: false
968
+ });
969
+ };
970
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
971
+ const field = get(_fields, name);
972
+ if (field) {
973
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
974
+ isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
975
+ _state.mount && _updateValid();
976
+ }
977
+ };
978
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
979
+ let shouldUpdateField = false;
980
+ let isPreviousDirty = false;
981
+ const output = {
982
+ name
983
+ };
984
+ const disabledField = get(_fields, name) && get(_fields, name)._f.disabled;
985
+ if (!isBlurEvent || shouldDirty) {
986
+ if (_proxyFormState.isDirty) {
987
+ isPreviousDirty = _formState.isDirty;
988
+ _formState.isDirty = output.isDirty = _getDirty();
989
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
990
+ }
991
+ const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
992
+ isPreviousDirty = !disabledField && get(_formState.dirtyFields, name);
993
+ isCurrentFieldPristine || disabledField ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
994
+ output.dirtyFields = _formState.dirtyFields;
995
+ shouldUpdateField = shouldUpdateField || _proxyFormState.dirtyFields && isPreviousDirty !== !isCurrentFieldPristine;
996
+ }
997
+ if (isBlurEvent) {
998
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
999
+ if (!isPreviousFieldTouched) {
1000
+ set(_formState.touchedFields, name, isBlurEvent);
1001
+ output.touchedFields = _formState.touchedFields;
1002
+ shouldUpdateField = shouldUpdateField || _proxyFormState.touchedFields && isPreviousFieldTouched !== isBlurEvent;
1003
+ }
1004
+ }
1005
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1006
+ return shouldUpdateField ? output : {};
1007
+ };
1008
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1009
+ const previousFieldError = get(_formState.errors, name);
1010
+ const shouldUpdateValid = _proxyFormState.isValid && isBoolean(isValid) && _formState.isValid !== isValid;
1011
+ if (props.delayError && error) {
1012
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1013
+ delayErrorCallback(props.delayError);
1014
+ } else {
1015
+ clearTimeout(timer);
1016
+ delayErrorCallback = null;
1017
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1018
+ }
1019
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
1020
+ const updatedFormState = {
1021
+ ...fieldState,
1022
+ ...shouldUpdateValid && isBoolean(isValid) ? { isValid } : {},
1023
+ errors: _formState.errors,
1024
+ name
1025
+ };
1026
+ _formState = {
1027
+ ..._formState,
1028
+ ...updatedFormState
1029
+ };
1030
+ _subjects.state.next(updatedFormState);
1031
+ }
1032
+ _updateIsValidating(false);
1033
+ };
1034
+ const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1035
+ const executeSchemaAndUpdateState = async (names) => {
1036
+ const { errors } = await _executeSchema(names);
1037
+ if (names) {
1038
+ for (const name of names) {
1039
+ const error = get(errors, name);
1040
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1041
+ }
1042
+ } else {
1043
+ _formState.errors = errors;
1044
+ }
1045
+ return errors;
1046
+ };
1047
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1048
+ valid: true
1049
+ }) => {
1050
+ for (const name in fields) {
1051
+ const field = fields[name];
1052
+ if (field) {
1053
+ const { _f, ...fieldValue } = field;
1054
+ if (_f) {
1055
+ const isFieldArrayRoot = _names.array.has(_f.name);
1056
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1057
+ if (fieldError[_f.name]) {
1058
+ context.valid = false;
1059
+ if (shouldOnlyCheckValid) {
1060
+ break;
1061
+ }
1062
+ }
1063
+ !shouldOnlyCheckValid && (get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name));
1064
+ }
1065
+ fieldValue && await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context);
1066
+ }
1067
+ }
1068
+ return context.valid;
1069
+ };
1070
+ const _removeUnmounted = () => {
1071
+ for (const name of _names.unMount) {
1072
+ const field = get(_fields, name);
1073
+ field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
1074
+ }
1075
+ _names.unMount = /* @__PURE__ */ new Set();
1076
+ };
1077
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data), !deepEqual(getValues(), _defaultValues));
1078
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1079
+ ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue
1080
+ }, isGlobal, defaultValue);
1081
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
1082
+ const setFieldValue = (name, value, options = {}) => {
1083
+ const field = get(_fields, name);
1084
+ let fieldValue = value;
1085
+ if (field) {
1086
+ const fieldReference = field._f;
1087
+ if (fieldReference) {
1088
+ !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
1089
+ fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
1090
+ if (isMultipleSelect(fieldReference.ref)) {
1091
+ [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
1092
+ } else if (fieldReference.refs) {
1093
+ if (isCheckBoxInput(fieldReference.ref)) {
1094
+ fieldReference.refs.length > 1 ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) && (checkboxRef.checked = Array.isArray(fieldValue) ? !!fieldValue.find((data) => data === checkboxRef.value) : fieldValue === checkboxRef.value)) : fieldReference.refs[0] && (fieldReference.refs[0].checked = !!fieldValue);
1095
+ } else {
1096
+ fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
1097
+ }
1098
+ } else if (isFileInput(fieldReference.ref)) {
1099
+ fieldReference.ref.value = "";
1100
+ } else {
1101
+ fieldReference.ref.value = fieldValue;
1102
+ if (!fieldReference.ref.type) {
1103
+ _subjects.values.next({
1104
+ name,
1105
+ values: { ..._formValues }
1106
+ });
1107
+ }
1108
+ }
1109
+ }
1110
+ }
1111
+ (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1112
+ options.shouldValidate && trigger(name);
1113
+ };
1114
+ const setValues = (name, value, options) => {
1115
+ for (const fieldKey in value) {
1116
+ const fieldValue = value[fieldKey];
1117
+ const fieldName = `${name}.${fieldKey}`;
1118
+ const field = get(_fields, fieldName);
1119
+ (_names.array.has(name) || !isPrimitive(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options);
1120
+ }
1121
+ };
1122
+ const setValue = (name, value, options = {}) => {
1123
+ const field = get(_fields, name);
1124
+ const isFieldArray = _names.array.has(name);
1125
+ const cloneValue = cloneObject(value);
1126
+ set(_formValues, name, cloneValue);
1127
+ if (isFieldArray) {
1128
+ _subjects.array.next({
1129
+ name,
1130
+ values: { ..._formValues }
1131
+ });
1132
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) && options.shouldDirty) {
1133
+ _subjects.state.next({
1134
+ name,
1135
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
1136
+ isDirty: _getDirty(name, cloneValue)
1137
+ });
1138
+ }
1139
+ } else {
1140
+ field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options);
1141
+ }
1142
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
1143
+ _subjects.values.next({
1144
+ name,
1145
+ values: { ..._formValues }
1146
+ });
1147
+ !_state.mount && flushRootRender();
1148
+ };
1149
+ const onChange = async (event) => {
1150
+ const target = event.target;
1151
+ let name = target.name;
1152
+ let isFieldValueUpdated = true;
1153
+ const field = get(_fields, name);
1154
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1155
+ const _updateIsFieldValueUpdated = (fieldValue) => {
1156
+ isFieldValueUpdated = Number.isNaN(fieldValue) || fieldValue === get(_formValues, name, fieldValue);
1157
+ };
1158
+ if (field) {
1159
+ let error;
1160
+ let isValid;
1161
+ const fieldValue = getCurrentFieldValue();
1162
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1163
+ const shouldSkipValidation = !hasValidation(field._f) && !_options.resolver && !get(_formState.errors, name) && !field._f.deps || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1164
+ const watched = isWatched(name, _names, isBlurEvent);
1165
+ set(_formValues, name, fieldValue);
1166
+ if (isBlurEvent) {
1167
+ field._f.onBlur && field._f.onBlur(event);
1168
+ delayErrorCallback && delayErrorCallback(0);
1169
+ } else if (field._f.onChange) {
1170
+ field._f.onChange(event);
1171
+ }
1172
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1173
+ const shouldRender = !isEmptyObject(fieldState) || watched;
1174
+ !isBlurEvent && _subjects.values.next({
1175
+ name,
1176
+ type: event.type,
1177
+ values: { ..._formValues }
1178
+ });
1179
+ if (shouldSkipValidation) {
1180
+ _proxyFormState.isValid && _updateValid();
1181
+ return shouldRender && _subjects.state.next({ name, ...watched ? {} : fieldState });
1182
+ }
1183
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1184
+ _updateIsValidating(true);
1185
+ if (_options.resolver) {
1186
+ const { errors } = await _executeSchema([name]);
1187
+ _updateIsFieldValueUpdated(fieldValue);
1188
+ if (isFieldValueUpdated) {
1189
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1190
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1191
+ error = errorLookupResult.error;
1192
+ name = errorLookupResult.name;
1193
+ isValid = isEmptyObject(errors);
1194
+ }
1195
+ } else {
1196
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1197
+ _updateIsFieldValueUpdated(fieldValue);
1198
+ if (isFieldValueUpdated) {
1199
+ if (error) {
1200
+ isValid = false;
1201
+ } else if (_proxyFormState.isValid) {
1202
+ isValid = await executeBuiltInValidation(_fields, true);
1203
+ }
1204
+ }
1205
+ }
1206
+ if (isFieldValueUpdated) {
1207
+ field._f.deps && trigger(field._f.deps);
1208
+ shouldRenderByError(name, isValid, error, fieldState);
1209
+ }
1210
+ }
1211
+ };
1212
+ const _focusInput = (ref, key) => {
1213
+ if (get(_formState.errors, key) && ref.focus) {
1214
+ ref.focus();
1215
+ return 1;
1216
+ }
1217
+ return;
1218
+ };
1219
+ const trigger = async (name, options = {}) => {
1220
+ let isValid;
1221
+ let validationResult;
1222
+ const fieldNames = convertToArrayPayload(name);
1223
+ _updateIsValidating(true);
1224
+ if (_options.resolver) {
1225
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1226
+ isValid = isEmptyObject(errors);
1227
+ validationResult = name ? !fieldNames.some((name2) => get(errors, name2)) : isValid;
1228
+ } else if (name) {
1229
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1230
+ const field = get(_fields, fieldName);
1231
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1232
+ }))).every(Boolean);
1233
+ !(!validationResult && !_formState.isValid) && _updateValid();
1234
+ } else {
1235
+ validationResult = isValid = await executeBuiltInValidation(_fields);
1236
+ }
1237
+ _subjects.state.next({
1238
+ ...!isString(name) || _proxyFormState.isValid && isValid !== _formState.isValid ? {} : { name },
1239
+ ..._options.resolver || !name ? { isValid } : {},
1240
+ errors: _formState.errors,
1241
+ isValidating: false
1242
+ });
1243
+ options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
1244
+ return validationResult;
1245
+ };
1246
+ const getValues = (fieldNames) => {
1247
+ const values = {
1248
+ ..._defaultValues,
1249
+ ..._state.mount ? _formValues : {}
1250
+ };
1251
+ return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
1252
+ };
1253
+ const getFieldState = (name, formState) => ({
1254
+ invalid: !!get((formState || _formState).errors, name),
1255
+ isDirty: !!get((formState || _formState).dirtyFields, name),
1256
+ isTouched: !!get((formState || _formState).touchedFields, name),
1257
+ error: get((formState || _formState).errors, name)
1258
+ });
1259
+ const clearErrors = (name) => {
1260
+ name && convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1261
+ _subjects.state.next({
1262
+ errors: name ? _formState.errors : {}
1263
+ });
1264
+ };
1265
+ const setError = (name, error, options) => {
1266
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1267
+ set(_formState.errors, name, {
1268
+ ...error,
1269
+ ref
1270
+ });
1271
+ _subjects.state.next({
1272
+ name,
1273
+ errors: _formState.errors,
1274
+ isValid: false
1275
+ });
1276
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
1277
+ };
1278
+ const watch = (name, defaultValue) => isFunction(name) ? _subjects.values.subscribe({
1279
+ next: (payload) => name(_getWatch(void 0, defaultValue), payload)
1280
+ }) : _getWatch(name, defaultValue, true);
1281
+ const unregister = (name, options = {}) => {
1282
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1283
+ _names.mount.delete(fieldName);
1284
+ _names.array.delete(fieldName);
1285
+ if (!options.keepValue) {
1286
+ unset(_fields, fieldName);
1287
+ unset(_formValues, fieldName);
1288
+ }
1289
+ !options.keepError && unset(_formState.errors, fieldName);
1290
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1291
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
1292
+ !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
1293
+ }
1294
+ _subjects.values.next({
1295
+ values: { ..._formValues }
1296
+ });
1297
+ _subjects.state.next({
1298
+ ..._formState,
1299
+ ...!options.keepDirty ? {} : { isDirty: _getDirty() }
1300
+ });
1301
+ !options.keepIsValid && _updateValid();
1302
+ };
1303
+ const _updateDisabledField = ({ disabled, name, field, fields, value }) => {
1304
+ if (isBoolean(disabled)) {
1305
+ const inputValue = disabled ? void 0 : isUndefined(value) ? getFieldValue(field ? field._f : get(fields, name)._f) : value;
1306
+ set(_formValues, name, inputValue);
1307
+ updateTouchAndDirty(name, inputValue, false, false, true);
1308
+ }
1309
+ };
1310
+ const register = (name, options = {}) => {
1311
+ let field = get(_fields, name);
1312
+ const disabledIsDefined = isBoolean(options.disabled);
1313
+ set(_fields, name, {
1314
+ ...field || {},
1315
+ _f: {
1316
+ ...field && field._f ? field._f : { ref: { name } },
1317
+ name,
1318
+ mount: true,
1319
+ ...options
1320
+ }
1321
+ });
1322
+ _names.mount.add(name);
1323
+ if (field) {
1324
+ _updateDisabledField({
1325
+ field,
1326
+ disabled: options.disabled,
1327
+ name
1328
+ });
1329
+ } else {
1330
+ updateValidAndValue(name, true, options.value);
1331
+ }
1332
+ return {
1333
+ ...disabledIsDefined ? { disabled: options.disabled } : {},
1334
+ ..._options.progressive ? {
1335
+ required: !!options.required,
1336
+ min: getRuleValue(options.min),
1337
+ max: getRuleValue(options.max),
1338
+ minLength: getRuleValue(options.minLength),
1339
+ maxLength: getRuleValue(options.maxLength),
1340
+ pattern: getRuleValue(options.pattern)
1341
+ } : {},
1342
+ name,
1343
+ onChange,
1344
+ onBlur: onChange,
1345
+ ref: (ref) => {
1346
+ if (ref) {
1347
+ register(name, options);
1348
+ field = get(_fields, name);
1349
+ const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
1350
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1351
+ const refs = field._f.refs || [];
1352
+ if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) {
1353
+ return;
1354
+ }
1355
+ set(_fields, name, {
1356
+ _f: {
1357
+ ...field._f,
1358
+ ...radioOrCheckbox ? {
1359
+ refs: [
1360
+ ...refs.filter(live),
1361
+ fieldRef,
1362
+ ...Array.isArray(get(_defaultValues, name)) ? [{}] : []
1363
+ ],
1364
+ ref: { type: fieldRef.type, name }
1365
+ } : { ref: fieldRef }
1366
+ }
1367
+ });
1368
+ updateValidAndValue(name, false, void 0, fieldRef);
1369
+ } else {
1370
+ field = get(_fields, name, {});
1371
+ if (field._f) {
1372
+ field._f.mount = false;
1373
+ }
1374
+ (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
1375
+ }
1376
+ }
1377
+ };
1378
+ };
1379
+ const _focusError = () => _options.shouldFocusError && iterateFieldsByAction(_fields, _focusInput, _names.mount);
1380
+ const _disableForm = (disabled) => {
1381
+ if (isBoolean(disabled)) {
1382
+ _subjects.state.next({ disabled });
1383
+ iterateFieldsByAction(_fields, (ref, name) => {
1384
+ let requiredDisabledState = disabled;
1385
+ const currentField = get(_fields, name);
1386
+ if (currentField && isBoolean(currentField._f.disabled)) {
1387
+ requiredDisabledState || (requiredDisabledState = currentField._f.disabled);
1388
+ }
1389
+ ref.disabled = requiredDisabledState;
1390
+ }, 0, false);
1391
+ }
1392
+ };
1393
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
1394
+ if (e) {
1395
+ e.preventDefault && e.preventDefault();
1396
+ e.persist && e.persist();
1397
+ }
1398
+ let fieldValues = cloneObject(_formValues);
1399
+ _subjects.state.next({
1400
+ isSubmitting: true
1401
+ });
1402
+ if (_options.resolver) {
1403
+ const { errors, values } = await _executeSchema();
1404
+ _formState.errors = errors;
1405
+ fieldValues = values;
1406
+ } else {
1407
+ await executeBuiltInValidation(_fields);
1408
+ }
1409
+ unset(_formState.errors, "root");
1410
+ if (isEmptyObject(_formState.errors)) {
1411
+ _subjects.state.next({
1412
+ errors: {}
1413
+ });
1414
+ await onValid(fieldValues, e);
1415
+ } else {
1416
+ if (onInvalid) {
1417
+ await onInvalid({ ..._formState.errors }, e);
1418
+ }
1419
+ _focusError();
1420
+ setTimeout(_focusError);
1421
+ }
1422
+ _subjects.state.next({
1423
+ isSubmitted: true,
1424
+ isSubmitting: false,
1425
+ isSubmitSuccessful: isEmptyObject(_formState.errors),
1426
+ submitCount: _formState.submitCount + 1,
1427
+ errors: _formState.errors
1428
+ });
1429
+ };
1430
+ const resetField = (name, options = {}) => {
1431
+ if (get(_fields, name)) {
1432
+ if (isUndefined(options.defaultValue)) {
1433
+ setValue(name, get(_defaultValues, name));
1434
+ } else {
1435
+ setValue(name, options.defaultValue);
1436
+ set(_defaultValues, name, options.defaultValue);
1437
+ }
1438
+ if (!options.keepTouched) {
1439
+ unset(_formState.touchedFields, name);
1440
+ }
1441
+ if (!options.keepDirty) {
1442
+ unset(_formState.dirtyFields, name);
1443
+ _formState.isDirty = options.defaultValue ? _getDirty(name, get(_defaultValues, name)) : _getDirty();
1444
+ }
1445
+ if (!options.keepError) {
1446
+ unset(_formState.errors, name);
1447
+ _proxyFormState.isValid && _updateValid();
1448
+ }
1449
+ _subjects.state.next({ ..._formState });
1450
+ }
1451
+ };
1452
+ const _reset = (formValues, keepStateOptions = {}) => {
1453
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1454
+ const cloneUpdatedValues = cloneObject(updatedValues);
1455
+ const values = formValues && !isEmptyObject(formValues) ? cloneUpdatedValues : _defaultValues;
1456
+ if (!keepStateOptions.keepDefaultValues) {
1457
+ _defaultValues = updatedValues;
1458
+ }
1459
+ if (!keepStateOptions.keepValues) {
1460
+ if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
1461
+ for (const fieldName of _names.mount) {
1462
+ get(_formState.dirtyFields, fieldName) ? set(values, fieldName, get(_formValues, fieldName)) : setValue(fieldName, get(values, fieldName));
1463
+ }
1464
+ } else {
1465
+ if (isWeb && isUndefined(formValues)) {
1466
+ for (const name of _names.mount) {
1467
+ const field = get(_fields, name);
1468
+ if (field && field._f) {
1469
+ const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
1470
+ if (isHTMLElement(fieldReference)) {
1471
+ const form = fieldReference.closest("form");
1472
+ if (form) {
1473
+ form.reset();
1474
+ break;
1475
+ }
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+ _fields = {};
1481
+ }
1482
+ _formValues = props.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneObject(values);
1483
+ _subjects.array.next({
1484
+ values: { ...values }
1485
+ });
1486
+ _subjects.values.next({
1487
+ values: { ...values }
1488
+ });
1489
+ }
1490
+ _names = {
1491
+ mount: /* @__PURE__ */ new Set(),
1492
+ unMount: /* @__PURE__ */ new Set(),
1493
+ array: /* @__PURE__ */ new Set(),
1494
+ watch: /* @__PURE__ */ new Set(),
1495
+ watchAll: false,
1496
+ focus: ""
1497
+ };
1498
+ !_state.mount && flushRootRender();
1499
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
1500
+ _state.watch = !!props.shouldUnregister;
1501
+ _subjects.state.next({
1502
+ submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
1503
+ isDirty: keepStateOptions.keepDirty ? _formState.isDirty : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
1504
+ isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
1505
+ dirtyFields: keepStateOptions.keepDirtyValues ? _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : {},
1506
+ touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
1507
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
1508
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
1509
+ isSubmitting: false
1510
+ });
1511
+ };
1512
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, keepStateOptions);
1513
+ const setFocus = (name, options = {}) => {
1514
+ const field = get(_fields, name);
1515
+ const fieldReference = field && field._f;
1516
+ if (fieldReference) {
1517
+ const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
1518
+ if (fieldRef.focus) {
1519
+ fieldRef.focus();
1520
+ options.shouldSelect && fieldRef.select();
1521
+ }
1522
+ }
1523
+ };
1524
+ const _updateFormState = (updatedFormState) => {
1525
+ _formState = {
1526
+ ..._formState,
1527
+ ...updatedFormState
1528
+ };
1529
+ };
1530
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
1531
+ reset(values, _options.resetOptions);
1532
+ _subjects.state.next({
1533
+ isLoading: false
1534
+ });
1535
+ });
1536
+ return {
1537
+ control: {
1538
+ register,
1539
+ unregister,
1540
+ getFieldState,
1541
+ handleSubmit,
1542
+ setError,
1543
+ _executeSchema,
1544
+ _getWatch,
1545
+ _getDirty,
1546
+ _updateValid,
1547
+ _removeUnmounted,
1548
+ _updateFieldArray,
1549
+ _updateDisabledField,
1550
+ _getFieldArray,
1551
+ _reset,
1552
+ _resetDefaultValues,
1553
+ _updateFormState,
1554
+ _disableForm,
1555
+ _subjects,
1556
+ _proxyFormState,
1557
+ _setErrors,
1558
+ get _fields() {
1559
+ return _fields;
1560
+ },
1561
+ get _formValues() {
1562
+ return _formValues;
1563
+ },
1564
+ get _state() {
1565
+ return _state;
1566
+ },
1567
+ set _state(value) {
1568
+ _state = value;
1569
+ },
1570
+ get _defaultValues() {
1571
+ return _defaultValues;
1572
+ },
1573
+ get _names() {
1574
+ return _names;
1575
+ },
1576
+ set _names(value) {
1577
+ _names = value;
1578
+ },
1579
+ get _formState() {
1580
+ return _formState;
1581
+ },
1582
+ set _formState(value) {
1583
+ _formState = value;
1584
+ },
1585
+ get _options() {
1586
+ return _options;
1587
+ },
1588
+ set _options(value) {
1589
+ _options = {
1590
+ ..._options,
1591
+ ...value
1592
+ };
1593
+ }
1594
+ },
1595
+ trigger,
1596
+ register,
1597
+ handleSubmit,
1598
+ watch,
1599
+ setValue,
1600
+ getValues,
1601
+ reset,
1602
+ resetField,
1603
+ clearErrors,
1604
+ unregister,
1605
+ setError,
1606
+ setFocus,
1607
+ getFieldState
1608
+ };
1609
+ }
1610
+ function useForm(props = {}) {
1611
+ const _formControl = React.useRef();
1612
+ const _values = React.useRef();
1613
+ const [formState, updateFormState] = React.useState({
1614
+ isDirty: false,
1615
+ isValidating: false,
1616
+ isLoading: isFunction(props.defaultValues),
1617
+ isSubmitted: false,
1618
+ isSubmitting: false,
1619
+ isSubmitSuccessful: false,
1620
+ isValid: false,
1621
+ submitCount: 0,
1622
+ dirtyFields: {},
1623
+ touchedFields: {},
1624
+ errors: props.errors || {},
1625
+ disabled: false,
1626
+ defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
1627
+ });
1628
+ if (!_formControl.current) {
1629
+ _formControl.current = {
1630
+ ...createFormControl(props, () => updateFormState((formState2) => ({ ...formState2 }))),
1631
+ formState
1632
+ };
1633
+ }
1634
+ const control = _formControl.current.control;
1635
+ control._options = props;
1636
+ useSubscribe({
1637
+ subject: control._subjects.state,
1638
+ next: (value) => {
1639
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
1640
+ updateFormState({ ...control._formState });
1641
+ }
1642
+ }
1643
+ });
1644
+ React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
1645
+ React.useEffect(() => {
1646
+ if (control._proxyFormState.isDirty) {
1647
+ const isDirty = control._getDirty();
1648
+ if (isDirty !== formState.isDirty) {
1649
+ control._subjects.state.next({
1650
+ isDirty
1651
+ });
1652
+ }
1653
+ }
1654
+ }, [control, formState.isDirty]);
1655
+ React.useEffect(() => {
1656
+ if (props.values && !deepEqual(props.values, _values.current)) {
1657
+ control._reset(props.values, control._options.resetOptions);
1658
+ _values.current = props.values;
1659
+ updateFormState((state) => ({ ...state }));
1660
+ } else {
1661
+ control._resetDefaultValues();
1662
+ }
1663
+ }, [props.values, control]);
1664
+ React.useEffect(() => {
1665
+ if (props.errors) {
1666
+ control._setErrors(props.errors);
1667
+ }
1668
+ }, [props.errors, control]);
1669
+ React.useEffect(() => {
1670
+ if (!control._state.mount) {
1671
+ control._updateValid();
1672
+ control._state.mount = true;
1673
+ }
1674
+ if (control._state.watch) {
1675
+ control._state.watch = false;
1676
+ control._subjects.state.next({ ...control._formState });
1677
+ }
1678
+ control._removeUnmounted();
1679
+ });
1680
+ _formControl.current.formState = getProxyFormState(formState, control);
1681
+ return _formControl.current;
1682
+ }
1683
+ const jsonToText = (v) => v === void 0 || v === "" ? "" : JSON.stringify(v, null, 2);
1684
+ const JsonField = ({ field, f }) => {
1685
+ const { t } = useTranslation();
1686
+ const [raw, setRaw] = useState(() => jsonToText(f.value));
1687
+ const [error, setError] = useState(null);
1688
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1689
+ /* @__PURE__ */ jsx(
1690
+ Textarea,
1691
+ {
1692
+ rows: 6,
1693
+ className: "font-mono",
1694
+ placeholder: field.placeholder ? t(field.placeholder) : "[]",
1695
+ value: raw,
1696
+ disabled: field.readonly === true,
1697
+ onBlur: f.onBlur,
1698
+ onChange: (e) => {
1699
+ const text = e.target.value;
1700
+ setRaw(text);
1701
+ if (text.trim() === "") {
1702
+ setError(null);
1703
+ f.onChange(void 0);
1704
+ return;
1705
+ }
1706
+ try {
1707
+ f.onChange(JSON.parse(text));
1708
+ setError(null);
1709
+ } catch {
1710
+ setError(t("integration.form.invalidJson"));
1711
+ }
1712
+ }
1713
+ }
1714
+ ),
1715
+ error && /* @__PURE__ */ jsx(Text, { size: "xsmall", className: "text-ui-fg-error", children: error })
1716
+ ] });
1717
+ };
1718
+ const IntegrationField = ({
1719
+ field,
1720
+ control,
1721
+ secretConfigured = false
1722
+ }) => {
1723
+ const { t } = useTranslation();
1724
+ const enforceRequired = field.required && field.control !== "switch" && !(field.control === "secret" && secretConfigured);
1725
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
1726
+ /* @__PURE__ */ jsxs(Label, { size: "small", weight: "plus", children: [
1727
+ t(field.label),
1728
+ field.required ? " *" : ""
1729
+ ] }),
1730
+ /* @__PURE__ */ jsx(
1731
+ Controller,
1732
+ {
1733
+ name: field.name,
1734
+ control,
1735
+ rules: {
1736
+ required: enforceRequired ? t("integration.form.required", { field: t(field.label) }) : false
1737
+ },
1738
+ render: ({ field: f, fieldState }) => {
1739
+ var _a;
1740
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1741
+ renderControl(field, f, secretConfigured, t),
1742
+ ((_a = fieldState.error) == null ? void 0 : _a.message) && /* @__PURE__ */ jsx(Text, { size: "xsmall", className: "text-ui-fg-error", children: fieldState.error.message })
1743
+ ] });
1744
+ }
1745
+ }
1746
+ ),
1747
+ field.hint && /* @__PURE__ */ jsx(Text, { size: "xsmall", className: "text-ui-fg-subtle", children: t(field.hint) })
1748
+ ] });
1749
+ };
1750
+ function renderControl(field, f, secretConfigured, t) {
1751
+ const placeholder = field.placeholder ? t(field.placeholder) : void 0;
1752
+ const disabled = field.readonly === true;
1753
+ switch (field.control) {
1754
+ case "switch":
1755
+ return /* @__PURE__ */ jsx(Switch, { checked: !!f.value, onCheckedChange: f.onChange, disabled });
1756
+ case "select":
1757
+ return /* @__PURE__ */ jsxs(Select, { value: f.value ?? "", onValueChange: f.onChange, disabled, children: [
1758
+ /* @__PURE__ */ jsx(Select.Trigger, { children: /* @__PURE__ */ jsx(Select.Value, { placeholder }) }),
1759
+ /* @__PURE__ */ jsx(Select.Content, { children: (field.options ?? []).map((o) => {
1760
+ var _a;
1761
+ const labelKey = (_a = field.optionLabels) == null ? void 0 : _a[o];
1762
+ return /* @__PURE__ */ jsx(Select.Item, { value: o, children: labelKey ? t(labelKey) : o }, o);
1763
+ }) })
1764
+ ] });
1765
+ case "number":
1766
+ return /* @__PURE__ */ jsx(
1767
+ Input,
1768
+ {
1769
+ type: "number",
1770
+ placeholder,
1771
+ value: f.value ?? "",
1772
+ disabled,
1773
+ onChange: (e) => f.onChange(e.target.value === "" ? void 0 : e.target.valueAsNumber)
1774
+ }
1775
+ );
1776
+ case "secret":
1777
+ return /* @__PURE__ */ jsx(
1778
+ Input,
1779
+ {
1780
+ type: "password",
1781
+ placeholder: secretConfigured ? t("integration.form.keepSecret") : placeholder ?? "",
1782
+ value: f.value ?? "",
1783
+ disabled,
1784
+ onChange: f.onChange
1785
+ }
1786
+ );
1787
+ case "json":
1788
+ return /* @__PURE__ */ jsx(JsonField, { field, f });
1789
+ default:
1790
+ return /* @__PURE__ */ jsx(
1791
+ Input,
1792
+ {
1793
+ placeholder,
1794
+ value: f.value ?? "",
1795
+ disabled,
1796
+ onChange: f.onChange
1797
+ }
1798
+ );
1799
+ }
1800
+ }
1801
+ function isFieldVisible(field, values) {
1802
+ const rule = field.visibleWhen;
1803
+ if (!rule) return true;
1804
+ return values[rule.field] === rule.equals;
1805
+ }
1806
+ function sectionDefaults(section, values) {
1807
+ const out = {};
1808
+ for (const f of section.fields) {
1809
+ if (f.readonly) out[f.name] = f.readonlyValue;
1810
+ else if (f.secret || f.control === "secret") out[f.name] = "";
1811
+ else if (f.control === "switch") out[f.name] = (values == null ? void 0 : values[f.name]) ?? false;
1812
+ else if (f.control === "json") out[f.name] = values == null ? void 0 : values[f.name];
1813
+ else out[f.name] = (values == null ? void 0 : values[f.name]) ?? "";
1814
+ }
1815
+ return out;
1816
+ }
1817
+ const EditSectionDrawer = ({
1818
+ open,
1819
+ onOpenChange,
1820
+ providerId,
1821
+ section,
1822
+ values,
1823
+ hasSecrets = false
1824
+ }) => {
1825
+ const { t } = useTranslation();
1826
+ const qc = useQueryClient();
1827
+ const [defaults] = useState(() => sectionDefaults(section, values));
1828
+ const form = useForm({ values: defaults });
1829
+ const current = form.watch();
1830
+ const visibilityValues = { ...values, ...current };
1831
+ const save = useMutation({
1832
+ mutationFn: (sectionValues) => sdk.client.fetch(`/admin/integrations/${providerId}`, {
1833
+ method: "POST",
1834
+ // Only this section's values + its id — the server validates just this section and
1835
+ // merges over the rest of the stored config (keeping blank/untouched secrets).
1836
+ body: { section_id: section.id, values: sectionValues }
1837
+ }),
1838
+ onSuccess: () => {
1839
+ toast.success(t("integration.toast.saved"));
1840
+ qc.invalidateQueries({ queryKey: ["integration", providerId] });
1841
+ qc.invalidateQueries({ queryKey: ["integration-overview"] });
1842
+ onOpenChange(false);
1843
+ },
1844
+ onError: (e) => toast.error((e == null ? void 0 : e.message) ?? t("integration.toast.saveFailed"))
1845
+ });
1846
+ return /* @__PURE__ */ jsx(Drawer, { open, onOpenChange, children: /* @__PURE__ */ jsxs(Drawer.Content, { children: [
1847
+ /* @__PURE__ */ jsx(Drawer.Header, { children: /* @__PURE__ */ jsx(Drawer.Title, { children: t(section.title) }) }),
1848
+ /* @__PURE__ */ jsx(Drawer.Body, { className: "flex flex-1 flex-col gap-y-4 overflow-auto", children: section.fields.filter((f) => isFieldVisible(f, visibilityValues)).map((f) => /* @__PURE__ */ jsx(
1849
+ IntegrationField,
1850
+ {
1851
+ field: f,
1852
+ control: form.control,
1853
+ secretConfigured: hasSecrets
1854
+ },
1855
+ f.name
1856
+ )) }),
1857
+ /* @__PURE__ */ jsxs(Drawer.Footer, { children: [
1858
+ /* @__PURE__ */ jsx(Drawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", disabled: save.isPending, children: t("integration.actions.cancel") }) }),
1859
+ /* @__PURE__ */ jsx(
1860
+ Button,
1861
+ {
1862
+ size: "small",
1863
+ isLoading: save.isPending,
1864
+ onClick: form.handleSubmit((v) => save.mutate(v)),
1865
+ children: t("integration.actions.save")
1866
+ }
1867
+ )
1868
+ ] })
1869
+ ] }) });
1870
+ };
1871
+ const testColor = (s) => s === "ok" ? "green" : s === "fail" ? "red" : "grey";
1872
+ const Row = ({ label, children }) => /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 px-6 py-4", children: [
1873
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: label }),
1874
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-x-2", children })
1875
+ ] });
1876
+ const EditPage = () => {
1877
+ const { t } = useTranslation();
1878
+ const { provider_id } = useParams();
1879
+ const qc = useQueryClient();
1880
+ const navigate = useNavigate();
1881
+ const prompt = usePrompt();
1882
+ const [editingSection, setEditingSection] = useState(null);
1883
+ const { data, isLoading } = useQuery({
1884
+ queryKey: ["integration", provider_id],
1885
+ queryFn: () => sdk.client.fetch(`/admin/integrations/${provider_id}`)
1886
+ });
1887
+ const descriptor = data == null ? void 0 : data.descriptor;
1888
+ const record = data == null ? void 0 : data.integration;
1889
+ const isConfigured = !!record;
1890
+ const isComplete = (data == null ? void 0 : data.is_complete) ?? false;
1891
+ const invalidate = () => {
1892
+ qc.invalidateQueries({ queryKey: ["integration", provider_id] });
1893
+ qc.invalidateQueries({ queryKey: ["integration-overview"] });
1894
+ };
1895
+ const test = useMutation({
1896
+ mutationFn: () => sdk.client.fetch(
1897
+ `/admin/integrations/${provider_id}/test-connection`,
1898
+ { method: "POST" }
1899
+ ),
1900
+ onSuccess: (r) => {
1901
+ r.status === "ok" ? toast.success(t("integration.toast.connectionOk")) : toast.warning(r.message ?? r.status);
1902
+ invalidate();
1903
+ },
1904
+ onError: (e) => toast.error((e == null ? void 0 : e.message) ?? t("integration.toast.testFailed"))
1905
+ });
1906
+ const toggleEnabled = useMutation({
1907
+ mutationFn: (next) => sdk.client.fetch(`/admin/integrations/${provider_id}/enable`, {
1908
+ method: "POST",
1909
+ body: { is_enabled: next }
1910
+ }),
1911
+ onSuccess: (_d, next) => {
1912
+ toast.success(next ? t("integration.toast.enabled") : t("integration.toast.disabled"));
1913
+ invalidate();
1914
+ },
1915
+ onError: (e) => toast.error((e == null ? void 0 : e.message) ?? t("integration.toast.updateFailed"))
1916
+ });
1917
+ const remove = useMutation({
1918
+ mutationFn: () => sdk.client.fetch(`/admin/integrations/${provider_id}`, { method: "DELETE" }),
1919
+ onSuccess: () => {
1920
+ toast.success(t("integration.toast.deleted"));
1921
+ invalidate();
1922
+ navigate("/settings/integrations");
1923
+ },
1924
+ onError: (e) => toast.error((e == null ? void 0 : e.message) ?? t("integration.toast.deleteFailed"))
1925
+ });
1926
+ const onDelete = async () => {
1927
+ const confirmed = await prompt({
1928
+ title: t("integration.delete.title"),
1929
+ description: t("integration.delete.description", {
1930
+ name: descriptor ? t(descriptor.displayName) : ""
1931
+ }),
1932
+ confirmText: t("integration.actions.delete"),
1933
+ cancelText: t("integration.actions.cancel")
1934
+ });
1935
+ if (confirmed) remove.mutate();
1936
+ };
1937
+ if (isLoading) {
1938
+ return /* @__PURE__ */ jsx(Container, { className: "flex items-center justify-center p-8", children: /* @__PURE__ */ jsx(Spinner, { className: "text-ui-fg-subtle animate-spin" }) });
1939
+ }
1940
+ if (!descriptor) {
1941
+ return /* @__PURE__ */ jsxs(Container, { className: "p-6", children: [
1942
+ /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("integration.unknown", { id: provider_id }) }),
1943
+ /* @__PURE__ */ jsx(Link, { to: "/settings/integrations", className: "text-ui-fg-interactive", children: t("integration.back") })
1944
+ ] });
1945
+ }
1946
+ const editing = descriptor.sections.find((s) => s.id === editingSection) ?? null;
1947
+ const sectionData = {
1948
+ providerId: provider_id,
1949
+ pluginId: descriptor.pluginId,
1950
+ values: (record == null ? void 0 : record.values) ?? {},
1951
+ isComplete
1952
+ };
1953
+ const renderSection = (section) => /* @__PURE__ */ jsx(LayoutComposer.Entry, { id: section.id, children: /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
1954
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
1955
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: t(section.title) }),
1956
+ /* @__PURE__ */ jsxs(DropdownMenu, { children: [
1957
+ /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(IconButton, { size: "small", variant: "transparent", children: /* @__PURE__ */ jsx(EllipsisHorizontal, {}) }) }),
1958
+ /* @__PURE__ */ jsx(DropdownMenu.Content, { children: /* @__PURE__ */ jsxs(DropdownMenu.Item, { className: "gap-x-2", onClick: () => setEditingSection(section.id), children: [
1959
+ /* @__PURE__ */ jsx(PencilSquare, { className: "text-ui-fg-subtle" }),
1960
+ t("integration.actions.edit")
1961
+ ] }) })
1962
+ ] })
1963
+ ] }),
1964
+ section.fields.filter((f) => isFieldVisible(f, (record == null ? void 0 : record.values) ?? {})).map((f) => {
1965
+ var _a;
1966
+ return /* @__PURE__ */ jsx(Row, { label: t(f.label), children: /* @__PURE__ */ jsx(
1967
+ IntegrationFieldValue,
1968
+ {
1969
+ field: f,
1970
+ value: (_a = record == null ? void 0 : record.values) == null ? void 0 : _a[f.name],
1971
+ secretConfigured: !!(record == null ? void 0 : record.has_secrets)
1972
+ }
1973
+ ) }, f.name);
1974
+ })
1975
+ ] }, section.id) });
1976
+ const mainSections = descriptor.sections.filter((s) => s.column !== "side");
1977
+ const sideSections = descriptor.sections.filter((s) => s.column === "side");
1978
+ const main = /* @__PURE__ */ jsxs(Fragment, { children: [
1979
+ /* @__PURE__ */ jsx(LayoutComposer.Entry, { id: "main", children: /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
1980
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
1981
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
1982
+ /* @__PURE__ */ jsx(IntegrationIcon, { src: descriptor.icon, alt: t(descriptor.displayName) }),
1983
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
1984
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1985
+ /* @__PURE__ */ jsx(Heading, { children: t(descriptor.displayName) }),
1986
+ descriptor.instanceId && /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: descriptor.instanceId })
1987
+ ] }),
1988
+ descriptor.description && /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t(descriptor.description) })
1989
+ ] })
1990
+ ] }),
1991
+ isConfigured && /* @__PURE__ */ jsxs(DropdownMenu, { children: [
1992
+ /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(IconButton, { size: "small", variant: "transparent", children: /* @__PURE__ */ jsx(EllipsisHorizontal, {}) }) }),
1993
+ /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
1994
+ descriptor.hasTestConnection && record.is_enabled && isComplete && /* @__PURE__ */ jsx(DropdownMenu.Item, { disabled: test.isPending, onClick: () => test.mutate(), children: t("integration.actions.test") }),
1995
+ isConfigured && /* @__PURE__ */ jsx(
1996
+ DropdownMenu.Item,
1997
+ {
1998
+ disabled: toggleEnabled.isPending,
1999
+ onClick: () => toggleEnabled.mutate(!record.is_enabled),
2000
+ children: record.is_enabled ? t("integration.actions.disable") : t("integration.actions.enable")
2001
+ }
2002
+ ),
2003
+ isConfigured && /* @__PURE__ */ jsx(DropdownMenu.Separator, {}),
2004
+ isConfigured && /* @__PURE__ */ jsxs(DropdownMenu.Item, { className: "gap-x-2", onClick: onDelete, children: [
2005
+ /* @__PURE__ */ jsx(Trash, { className: "text-ui-fg-subtle" }),
2006
+ t("integration.actions.delete")
2007
+ ] })
2008
+ ] })
2009
+ ] })
2010
+ ] }),
2011
+ /* @__PURE__ */ jsx(Row, { label: t("integration.labels.status"), children: !isConfigured ? /* @__PURE__ */ jsx(StatusBadge, { color: "grey", children: t("integration.status.notConfigured") }) : !isComplete ? /* @__PURE__ */ jsx(StatusBadge, { color: "orange", children: t("integration.status.incomplete") }) : /* @__PURE__ */ jsx(StatusBadge, { color: record.is_enabled ? "green" : "grey", children: record.is_enabled ? t("integration.status.enabled") : t("integration.status.disabled") }) }),
2012
+ /* @__PURE__ */ jsx(Row, { label: t("integration.labels.module"), children: /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: t(`integration.modules.${descriptor.module}`) }) }),
2013
+ /* @__PURE__ */ jsx(Row, { label: t("integration.labels.lastTest"), children: (record == null ? void 0 : record.last_test_status) ? /* @__PURE__ */ jsxs(Fragment, { children: [
2014
+ /* @__PURE__ */ jsx(StatusBadge, { color: testColor(record.last_test_status), children: t(`integration.testStatus.${record.last_test_status}`) }),
2015
+ /* @__PURE__ */ jsxs(Text, { size: "small", leading: "compact", className: "text-ui-fg-subtle", children: [
2016
+ record.last_test_at && new Date(record.last_test_at).toLocaleString(),
2017
+ record.last_test_message ? ` · ${record.last_test_message}` : ""
2018
+ ] })
2019
+ ] }) : /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "text-ui-fg-subtle", children: t("integration.labels.neverTested") }) })
2020
+ ] }) }),
2021
+ mainSections.map(renderSection),
2022
+ editing && /* @__PURE__ */ jsx(
2023
+ EditSectionDrawer,
2024
+ {
2025
+ open: true,
2026
+ onOpenChange: (open) => !open && setEditingSection(null),
2027
+ providerId: provider_id,
2028
+ section: editing,
2029
+ values: (record == null ? void 0 : record.values) ?? {},
2030
+ hasSecrets: !!(record == null ? void 0 : record.has_secrets)
2031
+ },
2032
+ editing.id
2033
+ )
2034
+ ] });
2035
+ const side = /* @__PURE__ */ jsx(Fragment, { children: sideSections.map(renderSection) });
2036
+ return /* @__PURE__ */ jsx(
2037
+ LayoutComposer,
2038
+ {
2039
+ widgetsZonePrefix: `gorgo.integration.${descriptor.pluginId}`,
2040
+ preferredLayoutId: descriptor.preferredLayoutId,
2041
+ sections: { main, side },
2042
+ data: sectionData,
2043
+ hasOutlet: false
2044
+ }
2045
+ );
2046
+ };
2047
+ const IntegrationBreadcrumb = ({ params }) => {
2048
+ const { t } = useTranslation();
2049
+ const providerId = params.provider_id;
2050
+ const { data } = useQuery({
2051
+ queryKey: ["integration", providerId],
2052
+ queryFn: () => sdk.client.fetch(`/admin/integrations/${providerId}`),
2053
+ enabled: !!providerId
2054
+ });
2055
+ const descriptor = data == null ? void 0 : data.descriptor;
2056
+ if (!descriptor) return /* @__PURE__ */ jsx(Fragment, { children: providerId });
2057
+ const name = t(descriptor.displayName);
2058
+ return /* @__PURE__ */ jsx(Fragment, { children: descriptor.instanceId ? `${name} · ${descriptor.instanceId}` : name });
2059
+ };
2060
+ const handle = {
2061
+ breadcrumb: ({ params }) => /* @__PURE__ */ jsx(IntegrationBreadcrumb, { params })
2062
+ };
2063
+ const integration$1 = {
2064
+ list: {
2065
+ title: "Integrations",
2066
+ empty: "No integrations registered. Declare providers under the integration plugin's options.providers in medusa-config.",
2067
+ tested: "tested",
2068
+ testFailed: "test failed"
2069
+ },
2070
+ status: {
2071
+ notConfigured: "Not configured",
2072
+ incomplete: "Incomplete",
2073
+ enabled: "Enabled",
2074
+ disabled: "Disabled",
2075
+ configured: "Configured"
2076
+ },
2077
+ labels: {
2078
+ status: "Status",
2079
+ module: "Module",
2080
+ lastTest: "Last test",
2081
+ neverTested: "Never tested"
2082
+ },
2083
+ modules: {
2084
+ payment: "Payment",
2085
+ fulfillment: "Fulfillment",
2086
+ marketplace: "Marketplace",
2087
+ crm: "CRM",
2088
+ erp: "ERP",
2089
+ pim: "PIM",
2090
+ notification: "Notification",
2091
+ feed: "Feed",
2092
+ tax: "Tax",
2093
+ other: "Other"
2094
+ },
2095
+ testStatus: {
2096
+ ok: "OK",
2097
+ fail: "Failed",
2098
+ skipped: "Skipped"
2099
+ },
2100
+ actions: {
2101
+ test: "Test connection",
2102
+ enable: "Enable",
2103
+ disable: "Disable",
2104
+ "delete": "Delete",
2105
+ edit: "Edit",
2106
+ save: "Save",
2107
+ cancel: "Cancel"
2108
+ },
2109
+ "delete": {
2110
+ title: "Delete configuration",
2111
+ description: "Remove the stored configuration for {{name}}? This can't be undone."
2112
+ },
2113
+ form: {
2114
+ required: "{{field}} is required",
2115
+ invalidJson: "Invalid JSON",
2116
+ keepSecret: "•••••• — leave blank to keep",
2117
+ items: "{{count}} items"
2118
+ },
2119
+ toast: {
2120
+ saved: "Saved",
2121
+ saveFailed: "Save failed",
2122
+ connectionOk: "Connection OK",
2123
+ testFailed: "Test failed",
2124
+ enabled: "Enabled",
2125
+ disabled: "Disabled",
2126
+ deleted: "Configuration deleted",
2127
+ deleteFailed: "Delete failed",
2128
+ updateFailed: "Update failed"
2129
+ },
2130
+ unknown: 'Unknown integration "{{id}}".',
2131
+ back: "Back to integrations"
2132
+ };
2133
+ const en = {
2134
+ integration: integration$1
2135
+ };
2136
+ const integration = {
2137
+ list: {
2138
+ title: "Интеграции",
2139
+ empty: "Нет зарегистрированных интеграций. Объявите провайдеров в options.providers плагина интеграций в medusa-config.",
2140
+ tested: "проверено",
2141
+ testFailed: "ошибка проверки"
2142
+ },
2143
+ status: {
2144
+ notConfigured: "Не настроено",
2145
+ incomplete: "Не завершено",
2146
+ enabled: "Включено",
2147
+ disabled: "Выключено",
2148
+ configured: "Настроено"
2149
+ },
2150
+ labels: {
2151
+ status: "Статус",
2152
+ module: "Модуль",
2153
+ lastTest: "Последняя проверка",
2154
+ neverTested: "Не проверялось"
2155
+ },
2156
+ modules: {
2157
+ payment: "Платежи",
2158
+ fulfillment: "Доставка",
2159
+ marketplace: "Маркетплейс",
2160
+ crm: "CRM",
2161
+ erp: "ERP",
2162
+ pim: "PIM",
2163
+ notification: "Уведомления",
2164
+ feed: "Фиды",
2165
+ tax: "Налоги",
2166
+ other: "Прочее"
2167
+ },
2168
+ testStatus: {
2169
+ ok: "OK",
2170
+ fail: "Ошибка",
2171
+ skipped: "Пропущено"
2172
+ },
2173
+ actions: {
2174
+ test: "Проверить соединение",
2175
+ enable: "Включить",
2176
+ disable: "Выключить",
2177
+ "delete": "Удалить",
2178
+ edit: "Редактировать",
2179
+ save: "Сохранить",
2180
+ cancel: "Отмена"
2181
+ },
2182
+ "delete": {
2183
+ title: "Удалить конфигурацию",
2184
+ description: "Удалить сохранённую конфигурацию «{{name}}»? Это действие необратимо."
2185
+ },
2186
+ form: {
2187
+ required: "Поле «{{field}}» обязательно",
2188
+ invalidJson: "Некорректный JSON",
2189
+ keepSecret: "•••••• — оставьте пустым, чтобы не менять",
2190
+ items: "{{count}} шт."
2191
+ },
2192
+ toast: {
2193
+ saved: "Сохранено",
2194
+ saveFailed: "Не удалось сохранить",
2195
+ connectionOk: "Соединение установлено",
2196
+ testFailed: "Проверка не удалась",
2197
+ enabled: "Включено",
2198
+ disabled: "Выключено",
2199
+ deleted: "Конфигурация удалена",
2200
+ deleteFailed: "Не удалось удалить",
2201
+ updateFailed: "Не удалось обновить"
2202
+ },
2203
+ unknown: "Неизвестная интеграция «{{id}}».",
2204
+ back: "К интеграциям"
2205
+ };
2206
+ const ru = {
2207
+ integration
2208
+ };
2209
+ const i18nTranslations0 = {
2210
+ en: { translation: en },
2211
+ ru: { translation: ru }
2212
+ };
2213
+ const widgetModule = { widgets: [] };
2214
+ const routeModule = {
2215
+ routes: [
2216
+ {
2217
+ Component: IntegrationsPage,
2218
+ path: "/settings/integrations",
2219
+ handle: handle$1
2220
+ },
2221
+ {
2222
+ Component: EditPage,
2223
+ path: "/settings/integrations/:provider_id",
2224
+ handle
2225
+ }
2226
+ ]
2227
+ };
2228
+ const menuItemModule = {
2229
+ menuItems: [
2230
+ {
2231
+ label: config.label,
2232
+ icon: config.icon,
2233
+ path: "/settings/integrations",
2234
+ nested: void 0,
2235
+ rank: void 0,
2236
+ translationNs: config.translationNs
2237
+ }
2238
+ ]
2239
+ };
2240
+ const formModule = { customFields: {} };
2241
+ const displayModule = {
2242
+ displays: {}
2243
+ };
2244
+ const i18nModule = { resources: i18nTranslations0 };
2245
+ const layoutModule = { layouts: [] };
2246
+ const plugin = {
2247
+ widgetModule,
2248
+ routeModule,
2249
+ menuItemModule,
2250
+ formModule,
2251
+ displayModule,
2252
+ i18nModule,
2253
+ layoutModule
2254
+ };
2255
+ export {
2256
+ plugin as default
2257
+ };