@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.7 → 6.2.3-dev.71

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 (114) hide show
  1. package/dist/browser/document-models/index.js +2 -1
  2. package/dist/browser/documents-BLZ-QW5b.js +16 -0
  3. package/dist/browser/documents-BLZ-QW5b.js.map +1 -0
  4. package/dist/browser/{editor-DHysndk4.js → editor-Dmpkd8pQ.js} +4 -5
  5. package/dist/browser/{editor-DHysndk4.js.map → editor-Dmpkd8pQ.js.map} +1 -1
  6. package/dist/browser/{editor-6T4WF2og.js → editor-x1UIfSot.js} +740 -272
  7. package/dist/browser/editor-x1UIfSot.js.map +1 -0
  8. package/dist/browser/editors/document-model-editor/module.js +1 -1
  9. package/dist/browser/editors/document-model-editor/module.js.map +1 -1
  10. package/dist/browser/editors/generic-drive-explorer/index.js +4 -324
  11. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  12. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  13. package/dist/browser/editors/generic-drive-explorer/module.js.map +1 -1
  14. package/dist/browser/{folder-view-DTewe8q8.js → folder-view-CwIU4XEe.js} +17 -12
  15. package/dist/browser/folder-view-CwIU4XEe.js.map +1 -0
  16. package/dist/browser/graphql-editor-CpcGaYmP.js +103 -0
  17. package/dist/browser/graphql-editor-CpcGaYmP.js.map +1 -0
  18. package/dist/browser/hooks-BmHa-lY2.js +126 -0
  19. package/dist/browser/hooks-BmHa-lY2.js.map +1 -0
  20. package/dist/browser/index.js +6 -703
  21. package/dist/browser/index.js.map +1 -1
  22. package/dist/browser/json-editor-CB1XmZgN.js +55 -0
  23. package/dist/browser/json-editor-CB1XmZgN.js.map +1 -0
  24. package/dist/browser/{schema-context-ZyeclQwy.js → schema-context-5evhtuMb.js} +6 -5
  25. package/dist/browser/{schema-context-ZyeclQwy.js.map → schema-context-5evhtuMb.js.map} +1 -1
  26. package/dist/browser/{state-schemas-CpcWN_Qo.js → state-schemas-DHLAg1w0.js} +20 -18
  27. package/dist/browser/state-schemas-DHLAg1w0.js.map +1 -0
  28. package/dist/{browser/dist-BAJ5nRDl.js → node/bundle-mjs-Cuu3DEfT.mjs} +1251 -822
  29. package/dist/node/bundle-mjs-Cuu3DEfT.mjs.map +1 -0
  30. package/dist/node/document-models/index.mjs +2 -1
  31. package/dist/node/{graphql-BfAoPeWM.mjs → documents-CFiuC6XV.mjs} +64 -50
  32. package/dist/node/documents-CFiuC6XV.mjs.map +1 -0
  33. package/dist/node/editor-7g9ujMII.mjs +4747 -0
  34. package/dist/node/editor-7g9ujMII.mjs.map +1 -0
  35. package/dist/node/{editor-DPv5LEug.mjs → editor-NwTlNx8z.mjs} +4 -5
  36. package/dist/node/{editor-DPv5LEug.mjs.map → editor-NwTlNx8z.mjs.map} +1 -1
  37. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  38. package/dist/node/editors/document-model-editor/module.mjs.map +1 -1
  39. package/dist/node/editors/generic-drive-explorer/index.mjs +26 -21
  40. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  41. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  42. package/dist/node/editors/generic-drive-explorer/module.mjs.map +1 -1
  43. package/dist/node/folder-view-CkCNU8A_.mjs +966 -0
  44. package/dist/node/folder-view-CkCNU8A_.mjs.map +1 -0
  45. package/dist/node/{graphql-editor-D0CHQeCL.mjs → graphql-editor-v1OXETjM.mjs} +5130 -63
  46. package/dist/node/graphql-editor-v1OXETjM.mjs.map +1 -0
  47. package/dist/node/{hooks-D0DcS3MV.mjs → hooks-gEAaW5rF.mjs} +824 -444
  48. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-gEAaW5rF.mjs.map} +1 -1
  49. package/dist/node/index.mjs +38 -90
  50. package/dist/node/index.mjs.map +1 -1
  51. package/dist/{browser/json-editor-xI_oaxyT.js → node/json-editor-8dfjgcaX.mjs} +8 -9
  52. package/dist/node/{json-editor-Ckaem6ky.mjs.map → json-editor-8dfjgcaX.mjs.map} +1 -1
  53. package/dist/node/rolldown-runtime-Bl3dcgcQ.mjs +16 -0
  54. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-DgUu7l_Q.mjs} +5 -5
  55. package/dist/node/schema-context-DgUu7l_Q.mjs.map +1 -0
  56. package/dist/node/state-schemas-DXWpf1zO.mjs +1064 -0
  57. package/dist/node/state-schemas-DXWpf1zO.mjs.map +1 -0
  58. package/package.json +25 -23
  59. package/style.css +2 -0
  60. package/dist/browser/assets/entry-DSBtQnit.js +0 -314
  61. package/dist/browser/assets/projection-entry-Bem3exmO.js +0 -404
  62. package/dist/browser/button-CuO8Gh3v.js +0 -696
  63. package/dist/browser/button-CuO8Gh3v.js.map +0 -1
  64. package/dist/browser/connect-5NZDVmbb.js +0 -14328
  65. package/dist/browser/connect-5NZDVmbb.js.map +0 -1
  66. package/dist/browser/dist-1yB-AuT-.js +0 -4641
  67. package/dist/browser/dist-1yB-AuT-.js.map +0 -1
  68. package/dist/browser/dist-B4FWbuEM.js +0 -4148
  69. package/dist/browser/dist-B4FWbuEM.js.map +0 -1
  70. package/dist/browser/dist-BAJ5nRDl.js.map +0 -1
  71. package/dist/browser/document-drive-CrvzV1D4.js +0 -8319
  72. package/dist/browser/document-drive-CrvzV1D4.js.map +0 -1
  73. package/dist/browser/documents-J_l59mSV.js +0 -6188
  74. package/dist/browser/documents-J_l59mSV.js.map +0 -1
  75. package/dist/browser/editor-6T4WF2og.js.map +0 -1
  76. package/dist/browser/folder-view-DTewe8q8.js.map +0 -1
  77. package/dist/browser/graphql-editor-C2EtXqb9.js +0 -11698
  78. package/dist/browser/graphql-editor-C2EtXqb9.js.map +0 -1
  79. package/dist/browser/hooks-KKcNp2X0.js +0 -24213
  80. package/dist/browser/hooks-KKcNp2X0.js.map +0 -1
  81. package/dist/browser/json-editor-xI_oaxyT.js.map +0 -1
  82. package/dist/browser/lib-CPkPeg_u.js +0 -209
  83. package/dist/browser/lib-CPkPeg_u.js.map +0 -1
  84. package/dist/browser/parser-CkF6Qt8V.js +0 -2553
  85. package/dist/browser/parser-CkF6Qt8V.js.map +0 -1
  86. package/dist/browser/printer-CEYr4JOg.js +0 -604
  87. package/dist/browser/printer-CEYr4JOg.js.map +0 -1
  88. package/dist/browser/state-schemas-CpcWN_Qo.js.map +0 -1
  89. package/dist/node/button-Da7CxMn7.mjs +0 -678
  90. package/dist/node/button-Da7CxMn7.mjs.map +0 -1
  91. package/dist/node/connect-cjzsd2cR.mjs +0 -15022
  92. package/dist/node/connect-cjzsd2cR.mjs.map +0 -1
  93. package/dist/node/dist-C30J_pcg.mjs +0 -4649
  94. package/dist/node/dist-C30J_pcg.mjs.map +0 -1
  95. package/dist/node/dist-CzYOpeXN.mjs +0 -2711
  96. package/dist/node/dist-CzYOpeXN.mjs.map +0 -1
  97. package/dist/node/dist-DT7jI9ol.mjs +0 -4148
  98. package/dist/node/dist-DT7jI9ol.mjs.map +0 -1
  99. package/dist/node/document-drive-BByBwg-I.mjs +0 -8336
  100. package/dist/node/document-drive-BByBwg-I.mjs.map +0 -1
  101. package/dist/node/documents-DCf53bzO.mjs +0 -747
  102. package/dist/node/documents-DCf53bzO.mjs.map +0 -1
  103. package/dist/node/editor-B4vhYrmV.mjs +0 -1809
  104. package/dist/node/editor-B4vhYrmV.mjs.map +0 -1
  105. package/dist/node/folder-view-BhackcXO.mjs +0 -232
  106. package/dist/node/folder-view-BhackcXO.mjs.map +0 -1
  107. package/dist/node/graphql-BfAoPeWM.mjs.map +0 -1
  108. package/dist/node/graphql-editor-D0CHQeCL.mjs.map +0 -1
  109. package/dist/node/json-editor-Ckaem6ky.mjs +0 -154
  110. package/dist/node/main-BhH_ajBM.mjs +0 -745
  111. package/dist/node/main-BhH_ajBM.mjs.map +0 -1
  112. package/dist/node/schema-context-DL8jhi_d.mjs.map +0 -1
  113. package/dist/node/state-schemas-B1SNl8Ob.mjs +0 -299
  114. package/dist/node/state-schemas-B1SNl8Ob.mjs.map +0 -1
@@ -0,0 +1,4747 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-Bl3dcgcQ.mjs";
2
+ import { t as twMerge } from "./bundle-mjs-Cuu3DEfT.mjs";
3
+ import { a as require_graphql } from "./documents-CFiuC6XV.mjs";
4
+ import { n as safeParseSdl, t as SchemaContextProvider } from "./schema-context-DgUu7l_Q.mjs";
5
+ import { addModule, addOperation, addOperationError, deleteModule, deleteOperation, deleteOperationError, generateId, releaseNewVersion, setAuthorName, setAuthorWebsite, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleName, setOperationDescription, setOperationErrorName, setOperationName, setOperationSchema, setStateSchema } from "@powerhousedao/shared/document-model";
6
+ import { z } from "zod";
7
+ import * as React$1 from "react";
8
+ import React, { Suspense, forwardRef, lazy, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from "react";
9
+ import { ConnectSelect, DocumentToolbar, Modal, ModalButton } from "@powerhousedao/design-system/connect";
10
+ import { usePHToast, useSetPHDocumentEditorConfig } from "@powerhousedao/reactor-browser";
11
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
+ import "react-dom";
13
+ import { getPHCustomScalarByTypeName } from "@powerhousedao/document-engineering/graphql";
14
+ import * as n from "zod/v4/core";
15
+ //#region ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js
16
+ const SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu;
17
+ const SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
18
+ const SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u;
19
+ const DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu;
20
+ const SPLIT_REPLACE_VALUE = "$1\0$2";
21
+ const DEFAULT_PREFIX_SUFFIX_CHARACTERS = "";
22
+ /**
23
+ * Split any cased input strings into an array of words.
24
+ */
25
+ function split(value) {
26
+ let result = value.trim();
27
+ result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);
28
+ result = result.replace(DEFAULT_STRIP_REGEXP, "\0");
29
+ let start = 0;
30
+ let end = result.length;
31
+ while (result.charAt(start) === "\0") start++;
32
+ if (start === end) return [];
33
+ while (result.charAt(end - 1) === "\0") end--;
34
+ return result.slice(start, end).split(/\0/g);
35
+ }
36
+ /**
37
+ * Split the input string into an array of words, separating numbers.
38
+ */
39
+ function splitSeparateNumbers(value) {
40
+ const words = split(value);
41
+ for (let i = 0; i < words.length; i++) {
42
+ const word = words[i];
43
+ const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);
44
+ if (match) {
45
+ const offset = match.index + (match[1] ?? match[2]).length;
46
+ words.splice(i, 1, word.slice(0, offset), word.slice(offset));
47
+ }
48
+ }
49
+ return words;
50
+ }
51
+ /**
52
+ * Convert a string to space separated lower case (`foo bar`).
53
+ */
54
+ function noCase(input, options) {
55
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
56
+ return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix;
57
+ }
58
+ /**
59
+ * Convert a string to pascal case (`FooBar`).
60
+ */
61
+ function pascalCase(input, options) {
62
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
63
+ const lower = lowerFactory(options?.locale);
64
+ const upper = upperFactory(options?.locale);
65
+ const transform = options?.mergeAmbiguousCharacters ? capitalCaseTransformFactory(lower, upper) : pascalCaseTransformFactory(lower, upper);
66
+ return prefix + words.map(transform).join(options?.delimiter ?? "") + suffix;
67
+ }
68
+ /**
69
+ * Convert a string to constant case (`FOO_BAR`).
70
+ */
71
+ function constantCase(input, options) {
72
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
73
+ return prefix + words.map(upperFactory(options?.locale)).join(options?.delimiter ?? "_") + suffix;
74
+ }
75
+ /**
76
+ * Convert a string to path case (`Foo bar`).
77
+ */
78
+ function sentenceCase(input, options) {
79
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
80
+ const lower = lowerFactory(options?.locale);
81
+ const transform = capitalCaseTransformFactory(lower, upperFactory(options?.locale));
82
+ return prefix + words.map((word, index) => {
83
+ if (index === 0) return transform(word);
84
+ return lower(word);
85
+ }).join(options?.delimiter ?? " ") + suffix;
86
+ }
87
+ /**
88
+ * Convert a string to snake case (`foo_bar`).
89
+ */
90
+ function snakeCase(input, options) {
91
+ return noCase(input, {
92
+ delimiter: "_",
93
+ ...options
94
+ });
95
+ }
96
+ function lowerFactory(locale) {
97
+ return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale);
98
+ }
99
+ function upperFactory(locale) {
100
+ return locale === false ? (input) => input.toUpperCase() : (input) => input.toLocaleUpperCase(locale);
101
+ }
102
+ function capitalCaseTransformFactory(lower, upper) {
103
+ return (word) => `${upper(word[0])}${lower(word.slice(1))}`;
104
+ }
105
+ function pascalCaseTransformFactory(lower, upper) {
106
+ return (word, index) => {
107
+ const char0 = word[0];
108
+ return (index > 0 && char0 >= "0" && char0 <= "9" ? "_" + char0 : upper(char0)) + lower(word.slice(1));
109
+ };
110
+ }
111
+ function splitPrefixSuffix(input, options = {}) {
112
+ const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);
113
+ const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
114
+ const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
115
+ let prefixIndex = 0;
116
+ let suffixIndex = input.length;
117
+ while (prefixIndex < input.length) {
118
+ const char = input.charAt(prefixIndex);
119
+ if (!prefixCharacters.includes(char)) break;
120
+ prefixIndex++;
121
+ }
122
+ while (suffixIndex > prefixIndex) {
123
+ const index = suffixIndex - 1;
124
+ const char = input.charAt(index);
125
+ if (!suffixCharacters.includes(char)) break;
126
+ suffixIndex = index;
127
+ }
128
+ return [
129
+ input.slice(0, prefixIndex),
130
+ splitFn(input.slice(prefixIndex, suffixIndex)),
131
+ input.slice(suffixIndex)
132
+ ];
133
+ }
134
+ //#endregion
135
+ //#region editors/document-model-editor/constants/graphql-kinds.ts
136
+ var import_graphql = require_graphql();
137
+ const STRING_GQL_PRIMITIVE_NAME = "String";
138
+ const BOOLEAN_GQL_PRIMITIVE_NAME = "Boolean";
139
+ const FLOAT_GQL_PRIMITIVE_NAME = "Float";
140
+ const gqlPrimitiveNodeNamesList = [
141
+ STRING_GQL_PRIMITIVE_NAME,
142
+ BOOLEAN_GQL_PRIMITIVE_NAME,
143
+ "Int",
144
+ FLOAT_GQL_PRIMITIVE_NAME,
145
+ "ID"
146
+ ];
147
+ //#endregion
148
+ //#region editors/document-model-editor/utils/helpers.ts
149
+ function makeStateSchemaNameForScope(modelName, scope) {
150
+ const modelNamePascalCase = pascalCase(modelName);
151
+ const scopePascalCase = pascalCase(scope);
152
+ return scopePascalCase === "Global" ? `${modelNamePascalCase}State` : `${modelNamePascalCase}${scopePascalCase}State`;
153
+ }
154
+ function makeInitialSchemaDoc(modelName, scope) {
155
+ return `type ${makeStateSchemaNameForScope(modelName, scope)} {
156
+ "Add your ${scope} state fields here"
157
+ _placeholder: String
158
+ }`;
159
+ }
160
+ function makeOperationInitialDoc(name) {
161
+ return `input ${pascalCase(name)}Input {
162
+ "Add your inputs here"
163
+ _placeholder: String
164
+ }`;
165
+ }
166
+ function makeEmptyOperationSchema(operationName) {
167
+ return `input ${pascalCase(operationName)}Input {\n _empty: Boolean\n}`;
168
+ }
169
+ function isEmptyOperationSchema(schema) {
170
+ if (!schema) return false;
171
+ return /_empty:\s*Boolean/.test(schema) && !schema.replace(/_empty:\s*Boolean/, "").match(/\w+:\s*\w+/);
172
+ }
173
+ function safeParseJsonRecord(json) {
174
+ try {
175
+ return JSON.parse(json);
176
+ } catch (_error) {
177
+ return null;
178
+ }
179
+ }
180
+ function makeMinimalObjectForStateType(args) {
181
+ const { sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue } = args;
182
+ const existingValueObject = safeParseJsonRecord(existingValue);
183
+ if (!existingValueObject) return existingValue;
184
+ const stateTypeDefinitionFields = stateTypeDefinitionNode.fields;
185
+ if (!stateTypeDefinitionFields?.length) return existingValue;
186
+ const minimalObject = makeMinimalValuesForObjectFields({
187
+ schemaDocumentNode: sharedSchemaDocumentNode,
188
+ fieldDefinitionNodes: stateTypeDefinitionFields,
189
+ existingValueObject,
190
+ visitedTypes: /* @__PURE__ */ new Set([stateTypeDefinitionNode.name.value])
191
+ });
192
+ return JSON.stringify(minimalObject, null, 2);
193
+ }
194
+ function makeMinimalValuesForObjectFields(args) {
195
+ const { schemaDocumentNode, existingValueObject, fieldDefinitionNodes, visitedTypes } = args;
196
+ const newJson = {};
197
+ for (const astNode of fieldDefinitionNodes) {
198
+ const fieldName = getASTNodeName(astNode);
199
+ if (!fieldName) continue;
200
+ const minimalValue = makeMinimalValueForASTNode({
201
+ fieldName,
202
+ astNode,
203
+ schemaDocumentNode,
204
+ existingValueObject,
205
+ visitedTypes
206
+ });
207
+ newJson[astNode.name.value] = minimalValue;
208
+ }
209
+ return newJson;
210
+ }
211
+ function makeMinimalValueForASTNode(args) {
212
+ const { fieldName, astNode, schemaDocumentNode, existingValueObject, visitedTypes } = args;
213
+ const existingFieldValue = existingValueObject?.[fieldName];
214
+ let node = astNode;
215
+ if (isFieldDefinitionNode(astNode)) node = getASTNodeTypeNode(node);
216
+ const isNonNull = isNonNullNode(node);
217
+ if (isNonNull) node = getASTNodeTypeNode(node);
218
+ if (isListTypeNode(node)) return makeMinimalValueForGqlListNode(node, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes);
219
+ if (isGqlPrimitiveNode(node)) return makeMinimalValueForGQLPrimitiveNode(node, existingFieldValue, isNonNull);
220
+ const namedTypeDefinitionNode = getNamedTypeDefinitionNode(node, schemaDocumentNode);
221
+ if (isEnumTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull);
222
+ if (isScalarTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlScalar(namedTypeDefinitionNode, existingFieldValue, isNonNull);
223
+ if (isUnionTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes);
224
+ if (isObjectTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlObject(namedTypeDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
225
+ return existingFieldValue;
226
+ }
227
+ function isFieldDefinitionNode(astNodeTypeNode) {
228
+ if (!astNodeTypeNode) return false;
229
+ return astNodeTypeNode.kind === import_graphql.Kind.FIELD_DEFINITION;
230
+ }
231
+ function isNonNullNode(astNode) {
232
+ if (!astNode) return false;
233
+ return astNode.kind === import_graphql.Kind.NON_NULL_TYPE;
234
+ }
235
+ function isGqlPrimitiveNode(astNodeTypeNode) {
236
+ if (!astNodeTypeNode) return false;
237
+ const name = getASTNodeName(astNodeTypeNode);
238
+ return gqlPrimitiveNodeNamesList.includes(name);
239
+ }
240
+ function isListTypeNode(astNodeTypeNode) {
241
+ if (!astNodeTypeNode) return false;
242
+ return astNodeTypeNode.kind === import_graphql.Kind.LIST_TYPE;
243
+ }
244
+ function isEnumTypeDefinitionNode(definitionNode) {
245
+ if (!definitionNode) return false;
246
+ return definitionNode.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION;
247
+ }
248
+ function isScalarTypeDefinitionNode(definitionNode) {
249
+ if (!definitionNode) return false;
250
+ return definitionNode.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION;
251
+ }
252
+ function isUnionTypeDefinitionNode(definitionNode) {
253
+ if (!definitionNode) return false;
254
+ return definitionNode.kind === import_graphql.Kind.UNION_TYPE_DEFINITION;
255
+ }
256
+ function isObjectTypeDefinitionNode(definitionNode) {
257
+ if (!definitionNode) return false;
258
+ return definitionNode.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION;
259
+ }
260
+ function getASTNodeName(astNode) {
261
+ if (!astNode) return null;
262
+ if (!("name" in astNode)) return null;
263
+ if (!astNode.name) return null;
264
+ if (!("value" in astNode.name)) return null;
265
+ return astNode.name.value;
266
+ }
267
+ function getASTNodeTypeNode(astNode) {
268
+ if (!astNode) return null;
269
+ if (!("type" in astNode)) return null;
270
+ return astNode.type;
271
+ }
272
+ function makeMinimalValueForGQLPrimitiveNode(primitiveTypeNode, existingFieldValue, isNonNull) {
273
+ const name = getASTNodeName(primitiveTypeNode);
274
+ if (!name) return null;
275
+ switch (name) {
276
+ case "ID":
277
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
278
+ return isNonNull ? "placeholder-id" : null;
279
+ case BOOLEAN_GQL_PRIMITIVE_NAME:
280
+ if (z.boolean().safeParse(existingFieldValue).success) return existingFieldValue;
281
+ return isNonNull ? false : null;
282
+ case "Int":
283
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
284
+ return isNonNull ? 0 : null;
285
+ case FLOAT_GQL_PRIMITIVE_NAME:
286
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
287
+ return isNonNull ? 0 : null;
288
+ case STRING_GQL_PRIMITIVE_NAME:
289
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
290
+ return isNonNull ? "" : null;
291
+ }
292
+ return isNonNull ? existingFieldValue : null;
293
+ }
294
+ function makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull) {
295
+ const enumValues = namedTypeDefinitionNode.values?.map((value) => value.name.value) ?? [];
296
+ if (typeof existingFieldValue === "string" && enumValues.includes(existingFieldValue)) return existingFieldValue;
297
+ if (isNonNull) return enumValues[0];
298
+ return null;
299
+ }
300
+ function makeMinimalValueForGqlScalar(scalarTypeDefinitionNode, existingFieldValue, isNonNull) {
301
+ if (!isNonNull && !existingFieldValue) return null;
302
+ const name = getASTNodeName(scalarTypeDefinitionNode);
303
+ if (!name) {
304
+ console.error("No name for scalar type definition node", scalarTypeDefinitionNode);
305
+ return null;
306
+ }
307
+ const scalar = getPHCustomScalarByTypeName(name);
308
+ if (!scalar) return null;
309
+ if (scalar.schema.safeParse(existingFieldValue).success) return existingFieldValue;
310
+ if (!isNonNull) return null;
311
+ const minimalValue = scalar.getDefaultValue?.();
312
+ if (minimalValue) return minimalValue;
313
+ return existingFieldValue;
314
+ }
315
+ function makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes) {
316
+ if (!isNonNull && !existingFieldValue) return null;
317
+ if (!namedTypeDefinitionNode.types?.length) return null;
318
+ const firstNamedTypeDefinitionNode = namedTypeDefinitionNode.types?.at(0);
319
+ if (!firstNamedTypeDefinitionNode) return null;
320
+ const firstNamedTypeObjectDefinitionNode = getNamedTypeDefinitionNode(firstNamedTypeDefinitionNode, schemaDocumentNode);
321
+ if (!isObjectTypeDefinitionNode(firstNamedTypeObjectDefinitionNode)) return null;
322
+ return makeMinimalValueForGqlObject(firstNamedTypeObjectDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
323
+ }
324
+ function makeMinimalValueForGqlListNode(listTypeNode, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes) {
325
+ if (!isNonNull && !Array.isArray(existingFieldValue)) return null;
326
+ if (isNonNull && !Array.isArray(existingFieldValue)) return [];
327
+ return existingFieldValue.map((item, index) => makeMinimalValueForASTNode({
328
+ fieldName: String(index),
329
+ astNode: listTypeNode.type,
330
+ schemaDocumentNode,
331
+ existingValueObject: { [index]: item },
332
+ visitedTypes
333
+ }));
334
+ }
335
+ function makeMinimalValueForGqlObject(objectTypeDefinitionNode, schemaDocumentNode, _existingValueObject, existingFieldValue, isNonNull, visitedTypes) {
336
+ const typeName = objectTypeDefinitionNode.name.value;
337
+ if (visitedTypes?.has(typeName)) return null;
338
+ if (!isNonNull && !existingFieldValue) return null;
339
+ const fields = objectTypeDefinitionNode.fields;
340
+ if (!fields?.length) return {};
341
+ const newVisitedTypes = new Set(visitedTypes);
342
+ newVisitedTypes.add(typeName);
343
+ return makeMinimalValuesForObjectFields({
344
+ schemaDocumentNode,
345
+ existingValueObject: existingFieldValue && typeof existingFieldValue === "object" && !Array.isArray(existingFieldValue) ? existingFieldValue : null,
346
+ fieldDefinitionNodes: fields,
347
+ visitedTypes: newVisitedTypes
348
+ });
349
+ }
350
+ function getNamedTypeDefinitionNode(astNodeTypeNode, schemaDocumentNode) {
351
+ if (!astNodeTypeNode) return null;
352
+ const name = getASTNodeName(astNodeTypeNode);
353
+ if (!name) return null;
354
+ const definitionNode = schemaDocumentNode.definitions.find((def) => "kind" in def && "name" in def && def.name?.value === name);
355
+ if (!definitionNode) return null;
356
+ return definitionNode;
357
+ }
358
+ function removeWhitespace(str) {
359
+ return str.replace(/\s+|\\n|\\t/g, "").toLowerCase();
360
+ }
361
+ function compareStringsWithoutWhitespace(str1, str2) {
362
+ if (str1 === null || str2 === null || str1 === void 0 || str2 === void 0) return false;
363
+ return removeWhitespace(str1) === removeWhitespace(str2);
364
+ }
365
+ function renameSchemaType(sdl, oldName, newName, scope) {
366
+ const typeSuffix = scope === "global" ? "State" : "LocalState";
367
+ const oldTypeName = `${pascalCase(oldName)}${typeSuffix}`;
368
+ const newTypeName = `${pascalCase(newName)}${typeSuffix}`;
369
+ const ast = safeParseSdl(sdl);
370
+ if (!ast) return sdl;
371
+ const updatedAst = (0, import_graphql.visit)(ast, { ObjectTypeDefinition: (node) => {
372
+ if (node.name.value === oldTypeName) return {
373
+ ...node,
374
+ name: {
375
+ ...node.name,
376
+ value: newTypeName
377
+ }
378
+ };
379
+ } });
380
+ return (0, import_graphql.print)(updatedAst);
381
+ }
382
+ function initializeModelSchema(modelName) {
383
+ return makeInitialSchemaDoc(modelName, "global");
384
+ }
385
+ function updateModelSchemaNames(params) {
386
+ const { oldName, newName, globalStateSchema, localStateSchema, setStateSchema } = params;
387
+ setStateSchema(renameSchemaType(globalStateSchema, oldName, newName, "global"), "global");
388
+ if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, oldName, newName, "local"), "local");
389
+ }
390
+ function handleModelNameChange(params) {
391
+ const { newName, globalStateSchema, setStateSchema } = params;
392
+ if (!!!globalStateSchema) {
393
+ setStateSchema(initializeModelSchema(newName), "global");
394
+ return;
395
+ }
396
+ updateModelSchemaNames(params);
397
+ }
398
+ function validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateValue) {
399
+ let stateObjectJson;
400
+ try {
401
+ stateObjectJson = JSON.parse(stateValue);
402
+ } catch (error) {
403
+ return [new Error("Invalid JSON object", { cause: error })];
404
+ }
405
+ const typeDefByName = indexTypeDefinitions(sharedSchemaDocumentNode);
406
+ const stateTypeName = stateTypeDefinitionNode.name.value;
407
+ if (!typeDefByName.has(stateTypeName)) return [/* @__PURE__ */ new Error(`State type "${stateTypeName}" was not found in sharedSchemaDocumentNode`)];
408
+ const inputSuffix = "Input";
409
+ const generatedInputDefs = generateInputTypesForObjectTree(stateTypeName, typeDefByName, inputSuffix);
410
+ const augmentedDoc = {
411
+ ...sharedSchemaDocumentNode,
412
+ definitions: [...sharedSchemaDocumentNode.definitions, ...generatedInputDefs]
413
+ };
414
+ let schema;
415
+ try {
416
+ schema = (0, import_graphql.buildASTSchema)(augmentedDoc, { assumeValidSDL: false });
417
+ } catch (e) {
418
+ return [new Error("Failed to build schema from SDL", { cause: e })];
419
+ }
420
+ const inputTypeName = `${stateTypeName}${inputSuffix}`;
421
+ const opDoc = (0, import_graphql.parse)(`query($v: ${inputTypeName}!) { __typename }`);
422
+ const op = (0, import_graphql.getOperationAST)(opDoc);
423
+ if (!op) return [/* @__PURE__ */ new Error("Failed to create validation operation AST")];
424
+ const { errors } = (0, import_graphql.getVariableValues)(schema, op.variableDefinitions ?? [], { v: stateObjectJson });
425
+ const recursiveTypeErrors = detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName);
426
+ const recursiveFieldNames = new Set(recursiveTypeErrors.map((e) => e.field));
427
+ const validationErrors = errors ? graphQLErrorsToStateValidationErrors(errors).filter((e) => {
428
+ if (e instanceof StateValidationError && e.kind === "NON_NULL") {
429
+ const rootField = e.path[0];
430
+ if (typeof rootField === "string" && recursiveFieldNames.has(rootField)) return false;
431
+ }
432
+ return true;
433
+ }) : [];
434
+ validationErrors.unshift(...recursiveTypeErrors);
435
+ const missingOptionalErrors = detectMissingOptionalFields(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateObjectJson);
436
+ validationErrors.push(...missingOptionalErrors);
437
+ return validationErrors;
438
+ }
439
+ /**
440
+ * Indexes object/input/enum/scalar/interface/union type definition nodes by name.
441
+ * Note: only AST definitions that have a "name" field are indexed.
442
+ */
443
+ function indexTypeDefinitions(doc) {
444
+ const map = /* @__PURE__ */ new Map();
445
+ for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION || def.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.ENUM_TYPE_EXTENSION || def.kind === import_graphql.Kind.INTERFACE_TYPE_EXTENSION || def.kind === import_graphql.Kind.UNION_TYPE_EXTENSION) {
446
+ const name = def.name.value;
447
+ if (!map.has(name)) map.set(name, def);
448
+ }
449
+ return map;
450
+ }
451
+ /**
452
+ * Generates InputObjectTypeDefinitionNode(s) for a root object type and any nested
453
+ * object types reachable via fields, converting object references to their *Input equivalents*.
454
+ */
455
+ function generateInputTypesForObjectTree(rootObjectTypeName, typeDefByName, inputSuffix) {
456
+ const generated = /* @__PURE__ */ new Map();
457
+ const visiting = /* @__PURE__ */ new Set();
458
+ const ensureInputForObject = (objectTypeName) => {
459
+ const inputName = `${objectTypeName}${inputSuffix}`;
460
+ if (generated.has(inputName)) return;
461
+ if (visiting.has(objectTypeName)) return;
462
+ visiting.add(objectTypeName);
463
+ const def = typeDefByName.get(objectTypeName);
464
+ if (!def) throw new import_graphql.GraphQLError(`Unknown referenced type "${objectTypeName}"`);
465
+ if (def.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION && def.kind !== import_graphql.Kind.OBJECT_TYPE_EXTENSION) throw new import_graphql.GraphQLError(`Type "${objectTypeName}" is not an object type; cannot generate input from kind "${def.kind}"`);
466
+ const objDef = def;
467
+ const inputFields = objDef.fields?.map((f) => {
468
+ return {
469
+ kind: import_graphql.Kind.INPUT_VALUE_DEFINITION,
470
+ name: f.name,
471
+ description: f.description,
472
+ directives: [],
473
+ type: convertOutputTypeNodeToInputTypeNode(f.type, typeDefByName, inputSuffix, ensureInputForObject),
474
+ defaultValue: void 0
475
+ };
476
+ }) ?? [];
477
+ const inputDef = {
478
+ kind: import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
479
+ name: {
480
+ kind: import_graphql.Kind.NAME,
481
+ value: inputName
482
+ },
483
+ description: objDef.description,
484
+ directives: [],
485
+ fields: inputFields
486
+ };
487
+ generated.set(inputName, inputDef);
488
+ visiting.delete(objectTypeName);
489
+ };
490
+ ensureInputForObject(rootObjectTypeName);
491
+ return Array.from(generated.values());
492
+ }
493
+ function convertOutputTypeNodeToInputTypeNode(typeNode, typeDefByName, inputSuffix, ensureInputForObject) {
494
+ switch (typeNode.kind) {
495
+ case import_graphql.Kind.NON_NULL_TYPE: return {
496
+ kind: import_graphql.Kind.NON_NULL_TYPE,
497
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
498
+ };
499
+ case import_graphql.Kind.LIST_TYPE: return {
500
+ kind: import_graphql.Kind.LIST_TYPE,
501
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
502
+ };
503
+ case import_graphql.Kind.NAMED_TYPE: {
504
+ const named = typeNode;
505
+ const name = named.name.value;
506
+ const def = typeDefByName.get(name);
507
+ if (def?.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def?.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION) {
508
+ ensureInputForObject(name);
509
+ return {
510
+ kind: import_graphql.Kind.NAMED_TYPE,
511
+ name: {
512
+ kind: import_graphql.Kind.NAME,
513
+ value: `${name}${inputSuffix}`
514
+ }
515
+ };
516
+ }
517
+ if (!def || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) return named;
518
+ if (def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION) throw new import_graphql.GraphQLError(`Type "${name}" (${def.kind}) cannot be used in an input type`);
519
+ throw new import_graphql.GraphQLError(`Unsupported named type "${name}" of kind "${def.kind}"`);
520
+ }
521
+ default: throw new import_graphql.GraphQLError(`Unsupported TypeNode kind: ${JSON.stringify(typeNode)}`);
522
+ }
523
+ }
524
+ var StateValidationError = class extends Error {
525
+ payload;
526
+ originalMessage;
527
+ constructor(payload, originalMessage) {
528
+ super(payload.kind);
529
+ this.name = "StateValidationError";
530
+ this.payload = payload;
531
+ this.originalMessage = originalMessage;
532
+ Object.setPrototypeOf(this, new.target.prototype);
533
+ }
534
+ get kind() {
535
+ return this.payload.kind;
536
+ }
537
+ get path() {
538
+ return this.payload.path;
539
+ }
540
+ get field() {
541
+ return this.payload.field;
542
+ }
543
+ };
544
+ function extractInputPath(message) {
545
+ const match = message.match(/at\s+"([^"]+)"/);
546
+ if (!match) return [];
547
+ const parts = match[1].split(".").filter(Boolean);
548
+ return (parts[0] === "v" ? parts.slice(1) : parts).map((p) => /^\d+$/.test(p) ? Number(p) : p);
549
+ }
550
+ const RE_MISSING_REQUIRED_FIELD = /Field "([^"]+)" of required type "([^"]+)" was not provided\./;
551
+ const RE_UNKNOWN_FIELD = /Field "([^"]+)" is not defined by type "([^"]+)"\.(?: Did you mean "([^"]+)"\?)?/;
552
+ function extractMissingRequiredField(message) {
553
+ const m = message.match(RE_MISSING_REQUIRED_FIELD);
554
+ if (!m) return null;
555
+ return {
556
+ field: m[1],
557
+ expectedType: m[2]
558
+ };
559
+ }
560
+ function extractUnknownField(message) {
561
+ const m = message.match(RE_UNKNOWN_FIELD);
562
+ if (!m) return null;
563
+ return {
564
+ field: m[1],
565
+ typeName: m[2],
566
+ didYouMean: m[3]
567
+ };
568
+ }
569
+ function lastFieldFromPath(path) {
570
+ for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "string") return path[i];
571
+ }
572
+ function extractExpectedType(message) {
573
+ let m = message.match(/Expected non-nullable type "([^"]+)"/);
574
+ if (m?.[1]) return m[1];
575
+ m = message.match(/Expected type "([^"]+)"/);
576
+ if (m?.[1]) return m[1];
577
+ m = message.match(/;\s*([_A-Za-z][_0-9A-Za-z]*)\s+cannot represent/i);
578
+ if (m?.[1]) return m[1];
579
+ }
580
+ function graphQLErrorsToStateValidationErrors(errors) {
581
+ const out = [];
582
+ for (const e of errors) {
583
+ const originalMessage = e.message;
584
+ const missing = extractMissingRequiredField(originalMessage);
585
+ if (missing) {
586
+ out.push(new StateValidationError({
587
+ kind: "MISSING",
588
+ path: [missing.field],
589
+ field: missing.field,
590
+ expectedType: missing.expectedType
591
+ }, originalMessage));
592
+ continue;
593
+ }
594
+ const unknown = extractUnknownField(originalMessage);
595
+ if (unknown) {
596
+ out.push(new StateValidationError({
597
+ kind: "UNKNOWN_FIELD",
598
+ path: [unknown.field],
599
+ field: unknown.field,
600
+ didYouMean: unknown.didYouMean
601
+ }, originalMessage));
602
+ continue;
603
+ }
604
+ const path = extractInputPath(originalMessage);
605
+ const field = lastFieldFromPath(path) ?? "value";
606
+ const expectedType = extractExpectedType(originalMessage);
607
+ if (originalMessage.includes("Expected non-nullable type") && originalMessage.includes("not to be null")) {
608
+ out.push(new StateValidationError({
609
+ kind: "NON_NULL",
610
+ path,
611
+ field,
612
+ expectedType
613
+ }, originalMessage));
614
+ continue;
615
+ }
616
+ if (originalMessage.includes("cannot represent") || originalMessage.includes("Expected type")) {
617
+ out.push(new StateValidationError({
618
+ kind: "TYPE",
619
+ path,
620
+ field,
621
+ expectedType,
622
+ details: originalMessage
623
+ }, originalMessage));
624
+ continue;
625
+ }
626
+ out.push(new StateValidationError({
627
+ kind: "TYPE",
628
+ path,
629
+ field,
630
+ details: originalMessage
631
+ }, originalMessage));
632
+ }
633
+ return out;
634
+ }
635
+ /**
636
+ * Finds all fields defined in the schema that are missing from the state object.
637
+ * Returns information about each missing field including whether it's required.
638
+ */
639
+ function findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value, basePath = []) {
640
+ let stateObjectJson;
641
+ try {
642
+ stateObjectJson = typeof value === "string" ? JSON.parse(value) : value;
643
+ } catch {
644
+ return [];
645
+ }
646
+ const typeByName = indexObjectTypes(sharedSchemaDocumentNode);
647
+ const missingFields = [];
648
+ for (const field of rootTypeNode.fields ?? []) {
649
+ const fieldName = field.name.value;
650
+ const fieldPath = [...basePath, fieldName];
651
+ const isRequired = field.type.kind === import_graphql.Kind.NON_NULL_TYPE;
652
+ const underlyingType = isRequired ? field.type.type : field.type;
653
+ if (!(fieldName in stateObjectJson)) {
654
+ missingFields.push({
655
+ fieldName,
656
+ path: fieldPath,
657
+ isRequired,
658
+ type: underlyingType
659
+ });
660
+ continue;
661
+ }
662
+ const namedType = unwrapNamedType(field.type);
663
+ const childType = namedType ? typeByName.get(namedType) : void 0;
664
+ if (childType && typeof stateObjectJson[fieldName] === "object" && stateObjectJson[fieldName] !== null && !Array.isArray(stateObjectJson[fieldName])) {
665
+ const nestedMissing = findMissingFields(sharedSchemaDocumentNode, childType, stateObjectJson[fieldName], fieldPath);
666
+ missingFields.push(...nestedMissing);
667
+ }
668
+ }
669
+ return missingFields;
670
+ }
671
+ /**
672
+ * Detects optional fields defined in the schema that are missing from the state object.
673
+ * Returns StateValidationError[] for each missing optional field.
674
+ */
675
+ function detectMissingOptionalFields(sharedSchemaDocumentNode, rootTypeNode, value) {
676
+ return findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value).filter((field) => !field.isRequired).map((field) => new StateValidationError({
677
+ kind: "MISSING_OPTIONAL",
678
+ path: field.path,
679
+ field: field.fieldName,
680
+ expectedType: typeNodeToString(field.type)
681
+ }));
682
+ }
683
+ /**
684
+ * Detects fields that have recursive types (types that reference themselves directly or indirectly).
685
+ * Returns a RECURSIVE_TYPE error for each field that contains a recursive type.
686
+ */
687
+ function detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName) {
688
+ const errors = [];
689
+ for (const field of stateTypeDefinitionNode.fields ?? []) {
690
+ const fieldName = field.name.value;
691
+ const namedTypeName = getNamedTypeName(field.type);
692
+ if (!namedTypeName) continue;
693
+ if (isRecursiveType(namedTypeName, typeDefByName, /* @__PURE__ */ new Set())) errors.push(new StateValidationError({
694
+ kind: "RECURSIVE_TYPE",
695
+ path: [fieldName],
696
+ field: fieldName,
697
+ typeName: namedTypeName
698
+ }));
699
+ }
700
+ return errors;
701
+ }
702
+ /**
703
+ * Gets the named type name from a TypeNode, unwrapping NonNull and List types.
704
+ */
705
+ function getNamedTypeName(typeNode) {
706
+ if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
707
+ if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE || typeNode.kind === import_graphql.Kind.LIST_TYPE) return getNamedTypeName(typeNode.type);
708
+ return null;
709
+ }
710
+ /**
711
+ * Checks if a type is recursive (references itself directly or indirectly through required fields).
712
+ */
713
+ function isRecursiveType(typeName, typeDefByName, visitedTypes) {
714
+ if (visitedTypes.has(typeName)) return true;
715
+ const typeDef = typeDefByName.get(typeName);
716
+ if (!typeDef || typeDef.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION) return false;
717
+ visitedTypes.add(typeName);
718
+ for (const field of typeDef.fields ?? []) {
719
+ if (field.type.kind !== import_graphql.Kind.NON_NULL_TYPE) continue;
720
+ const innerType = field.type.type;
721
+ let fieldTypeName = null;
722
+ if (innerType.kind === import_graphql.Kind.NAMED_TYPE) fieldTypeName = innerType.name.value;
723
+ else if (innerType.kind === import_graphql.Kind.LIST_TYPE) fieldTypeName = getNamedTypeName(innerType);
724
+ if (fieldTypeName && isRecursiveType(fieldTypeName, typeDefByName, visitedTypes)) return true;
725
+ }
726
+ visitedTypes.delete(typeName);
727
+ return false;
728
+ }
729
+ /**
730
+ * Converts a TypeNode to its string representation (e.g., "String", "Int!", "[String]!")
731
+ */
732
+ function typeNodeToString(typeNode) {
733
+ switch (typeNode.kind) {
734
+ case import_graphql.Kind.NAMED_TYPE: return typeNode.name.value;
735
+ case import_graphql.Kind.NON_NULL_TYPE: return `${typeNodeToString(typeNode.type)}!`;
736
+ case import_graphql.Kind.LIST_TYPE: return `[${typeNodeToString(typeNode.type)}]`;
737
+ }
738
+ }
739
+ function indexObjectTypes(doc) {
740
+ const map = /* @__PURE__ */ new Map();
741
+ for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION) map.set(def.name.value, def);
742
+ return map;
743
+ }
744
+ function unwrapNamedType(typeNode) {
745
+ if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
746
+ if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE) return unwrapNamedType(typeNode.type);
747
+ if (typeNode.kind === import_graphql.Kind.LIST_TYPE) return unwrapNamedType(typeNode.type);
748
+ }
749
+ //#endregion
750
+ //#region editors/document-model-editor/utils/linting.ts
751
+ function ensureDocumentContainsNodeWithNameAndType(doc, nodeName, nodeType) {
752
+ const parsedDoc = safeParseSdl(doc);
753
+ if (!parsedDoc) return true;
754
+ return parsedDoc.definitions.some((def) => {
755
+ return def.kind === import_graphql.Kind[nodeType] && "name" in def && def.name?.value === nodeName;
756
+ });
757
+ }
758
+ function createNodeTypeAndNameDiagnostic(doc, errorMessage) {
759
+ const parsedDoc = safeParseSdl(doc);
760
+ if (!parsedDoc) return void 0;
761
+ const firstNode = parsedDoc.definitions[0];
762
+ const nameNode = "name" in firstNode ? firstNode.name : null;
763
+ return {
764
+ from: nameNode?.loc?.start ?? firstNode.loc?.start ?? 0,
765
+ to: nameNode?.loc?.end ?? firstNode.loc?.end ?? 0,
766
+ severity: "error",
767
+ message: errorMessage
768
+ };
769
+ }
770
+ function ensureValidStateSchemaName(doc, modelName, scope) {
771
+ if (!safeParseSdl(doc)) return [];
772
+ const requiredTypeName = makeStateSchemaNameForScope(modelName, scope);
773
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `${sentenceCase(scope)} state schema must be named ${requiredTypeName}`)].filter((d) => d !== void 0);
774
+ return [];
775
+ }
776
+ function ensureValidOperationSchemaInputName(doc, operationName) {
777
+ if (!doc || !safeParseSdl(doc)) return [];
778
+ const requiredTypeName = `${pascalCase(operationName)}Input`;
779
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "INPUT_OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `Operation schema must contain an input type named ${requiredTypeName}`)].filter((d) => d !== void 0);
780
+ return [];
781
+ }
782
+ //#endregion
783
+ //#region editors/document-model-editor/components/button.tsx
784
+ const Button = forwardRef((props, ref) => {
785
+ const { className, ...rest } = props;
786
+ return /* @__PURE__ */ jsx("button", {
787
+ ref,
788
+ ...rest,
789
+ className: twMerge("h-10 rounded-md border border-border bg-background px-4 py-2 text-sm font-medium whitespace-nowrap text-foreground transition-colors hover:hover-effect focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:disabled-effect", className)
790
+ });
791
+ });
792
+ //#endregion
793
+ //#region ../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.2_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
794
+ function setRef$1(ref, value) {
795
+ if (typeof ref === "function") return ref(value);
796
+ else if (ref !== null && ref !== void 0) ref.current = value;
797
+ }
798
+ function composeRefs$1(...refs) {
799
+ return (node) => {
800
+ let hasCleanup = false;
801
+ const cleanups = refs.map((ref) => {
802
+ const cleanup = setRef$1(ref, node);
803
+ if (!hasCleanup && typeof cleanup == "function") hasCleanup = true;
804
+ return cleanup;
805
+ });
806
+ if (hasCleanup) return () => {
807
+ for (let i = 0; i < cleanups.length; i++) {
808
+ const cleanup = cleanups[i];
809
+ if (typeof cleanup == "function") cleanup();
810
+ else setRef$1(refs[i], null);
811
+ }
812
+ };
813
+ };
814
+ }
815
+ function useComposedRefs$1(...refs) {
816
+ return React$1.useCallback(composeRefs$1(...refs), refs);
817
+ }
818
+ //#endregion
819
+ //#region editors/document-model-editor/components/divider.tsx
820
+ function Divider({ className, size = "sm", margin = "md" }) {
821
+ function getSize() {
822
+ if (size === "sm") return "h-px";
823
+ if (size === "md") return "h-1";
824
+ return "h-1.5";
825
+ }
826
+ function getMargin() {
827
+ if (margin === "sm") return "my-4";
828
+ if (margin === "md") return "my-6";
829
+ return "my-8";
830
+ }
831
+ const sizeClass = getSize();
832
+ const marginClass = getMargin();
833
+ return /* @__PURE__ */ jsx("div", { className: twMerge("bg-secondary", sizeClass, marginClass, className) });
834
+ }
835
+ //#endregion
836
+ //#region ../../node_modules/.pnpm/react-hook-form@7.71.2_react@19.2.6/node_modules/react-hook-form/dist/index.esm.mjs
837
+ var isCheckBoxInput = (element) => element.type === "checkbox";
838
+ var isDateObject = (value) => value instanceof Date;
839
+ var isNullOrUndefined = (value) => value == null;
840
+ const isObjectType = (value) => typeof value === "object";
841
+ var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
842
+ var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
843
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
844
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
845
+ var isPlainObject = (tempObject) => {
846
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
847
+ return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
848
+ };
849
+ var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
850
+ function cloneObject(data) {
851
+ if (data instanceof Date) return new Date(data);
852
+ const isFileListInstance = typeof FileList !== "undefined" && data instanceof FileList;
853
+ if (isWeb && (data instanceof Blob || isFileListInstance)) return data;
854
+ const isArray = Array.isArray(data);
855
+ if (!isArray && !(isObject(data) && isPlainObject(data))) return data;
856
+ const copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));
857
+ for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) copy[key] = cloneObject(data[key]);
858
+ return copy;
859
+ }
860
+ var isKey = (value) => /^\w*$/.test(value);
861
+ var isUndefined = (val) => val === void 0;
862
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
863
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
864
+ var get = (object, path, defaultValue) => {
865
+ if (!path || !isObject(object)) return defaultValue;
866
+ const result = (isKey(path) ? [path] : stringToPath(path)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
867
+ return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
868
+ };
869
+ var isBoolean = (value) => typeof value === "boolean";
870
+ var isFunction = (value) => typeof value === "function";
871
+ var set = (object, path, value) => {
872
+ let index = -1;
873
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
874
+ const length = tempPath.length;
875
+ const lastIndex = length - 1;
876
+ while (++index < length) {
877
+ const key = tempPath[index];
878
+ let newValue = value;
879
+ if (index !== lastIndex) {
880
+ const objValue = object[key];
881
+ newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
882
+ }
883
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return;
884
+ object[key] = newValue;
885
+ object = object[key];
886
+ }
887
+ };
888
+ const EVENTS = {
889
+ BLUR: "blur",
890
+ FOCUS_OUT: "focusout",
891
+ CHANGE: "change"
892
+ };
893
+ const VALIDATION_MODE = {
894
+ onBlur: "onBlur",
895
+ onChange: "onChange",
896
+ onSubmit: "onSubmit",
897
+ onTouched: "onTouched",
898
+ all: "all"
899
+ };
900
+ const INPUT_VALIDATION_RULES = {
901
+ max: "max",
902
+ min: "min",
903
+ maxLength: "maxLength",
904
+ minLength: "minLength",
905
+ pattern: "pattern",
906
+ required: "required",
907
+ validate: "validate"
908
+ };
909
+ /**
910
+ * Separate context for `control` to prevent unnecessary rerenders.
911
+ * Internal hooks that only need control use this instead of full form context.
912
+ */
913
+ const HookFormControlContext = React.createContext(null);
914
+ HookFormControlContext.displayName = "HookFormControlContext";
915
+ /**
916
+ * @internal Internal hook to access only control from context.
917
+ */
918
+ const useFormControlContext = () => React.useContext(HookFormControlContext);
919
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
920
+ const result = { defaultValues: control._defaultValues };
921
+ for (const key in formState) Object.defineProperty(result, key, { get: () => {
922
+ const _key = key;
923
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
924
+ localProxyFormState && (localProxyFormState[_key] = true);
925
+ return formState[_key];
926
+ } });
927
+ return result;
928
+ };
929
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
930
+ /**
931
+ * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
932
+ *
933
+ * @remarks
934
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
935
+ *
936
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
937
+ *
938
+ * @example
939
+ * ```tsx
940
+ * function App() {
941
+ * const { register, handleSubmit, control } = useForm({
942
+ * defaultValues: {
943
+ * firstName: "firstName"
944
+ * }});
945
+ * const { dirtyFields } = useFormState({
946
+ * control
947
+ * });
948
+ * const onSubmit = (data) => console.log(data);
949
+ *
950
+ * return (
951
+ * <form onSubmit={handleSubmit(onSubmit)}>
952
+ * <input {...register("firstName")} placeholder="First Name" />
953
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
954
+ * <input type="submit" />
955
+ * </form>
956
+ * );
957
+ * }
958
+ * ```
959
+ */
960
+ function useFormState(props) {
961
+ const formControl = useFormControlContext();
962
+ const { control = formControl, disabled, name, exact } = props || {};
963
+ const [formState, updateFormState] = React.useState(control._formState);
964
+ const _localProxyFormState = React.useRef({
965
+ isDirty: false,
966
+ isLoading: false,
967
+ dirtyFields: false,
968
+ touchedFields: false,
969
+ validatingFields: false,
970
+ isValidating: false,
971
+ isValid: false,
972
+ errors: false
973
+ });
974
+ useIsomorphicLayoutEffect(() => control._subscribe({
975
+ name,
976
+ formState: _localProxyFormState.current,
977
+ exact,
978
+ callback: (formState) => {
979
+ !disabled && updateFormState({
980
+ ...control._formState,
981
+ ...formState
982
+ });
983
+ }
984
+ }), [
985
+ name,
986
+ disabled,
987
+ exact
988
+ ]);
989
+ React.useEffect(() => {
990
+ _localProxyFormState.current.isValid && control._setValid(true);
991
+ }, [control]);
992
+ return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
993
+ }
994
+ var isString = (value) => typeof value === "string";
995
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
996
+ if (isString(names)) {
997
+ isGlobal && _names.watch.add(names);
998
+ return get(formValues, names, defaultValue);
999
+ }
1000
+ if (Array.isArray(names)) return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
1001
+ isGlobal && (_names.watchAll = true);
1002
+ return formValues;
1003
+ };
1004
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
1005
+ function deepEqual(object1, object2, _internal_visited = /* @__PURE__ */ new WeakSet()) {
1006
+ if (isPrimitive(object1) || isPrimitive(object2)) return Object.is(object1, object2);
1007
+ if (isDateObject(object1) && isDateObject(object2)) return Object.is(object1.getTime(), object2.getTime());
1008
+ const keys1 = Object.keys(object1);
1009
+ const keys2 = Object.keys(object2);
1010
+ if (keys1.length !== keys2.length) return false;
1011
+ if (_internal_visited.has(object1) || _internal_visited.has(object2)) return true;
1012
+ _internal_visited.add(object1);
1013
+ _internal_visited.add(object2);
1014
+ for (const key of keys1) {
1015
+ const val1 = object1[key];
1016
+ if (!keys2.includes(key)) return false;
1017
+ if (key !== "ref") {
1018
+ const val2 = object2[key];
1019
+ if (isDateObject(val1) && isDateObject(val2) || isObject(val1) && isObject(val2) || Array.isArray(val1) && Array.isArray(val2) ? !deepEqual(val1, val2, _internal_visited) : !Object.is(val1, val2)) return false;
1020
+ }
1021
+ }
1022
+ return true;
1023
+ }
1024
+ /**
1025
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
1026
+ *
1027
+ * @remarks
1028
+ *
1029
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
1030
+ *
1031
+ * @example
1032
+ * ```tsx
1033
+ * const { control } = useForm();
1034
+ * const values = useWatch({
1035
+ * name: "fieldName"
1036
+ * control,
1037
+ * })
1038
+ * ```
1039
+ */
1040
+ function useWatch(props) {
1041
+ const formControl = useFormControlContext();
1042
+ const { control = formControl, name, defaultValue, disabled, exact, compute } = props || {};
1043
+ const _defaultValue = React.useRef(defaultValue);
1044
+ const _compute = React.useRef(compute);
1045
+ const _computeFormValues = React.useRef(void 0);
1046
+ const _prevControl = React.useRef(control);
1047
+ const _prevName = React.useRef(name);
1048
+ _compute.current = compute;
1049
+ const [value, updateValue] = React.useState(() => {
1050
+ const defaultValue = control._getWatch(name, _defaultValue.current);
1051
+ return _compute.current ? _compute.current(defaultValue) : defaultValue;
1052
+ });
1053
+ const getCurrentOutput = React.useCallback((values) => {
1054
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
1055
+ return _compute.current ? _compute.current(formValues) : formValues;
1056
+ }, [
1057
+ control._formValues,
1058
+ control._names,
1059
+ name
1060
+ ]);
1061
+ const refreshValue = React.useCallback((values) => {
1062
+ if (!disabled) {
1063
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
1064
+ if (_compute.current) {
1065
+ const computedFormValues = _compute.current(formValues);
1066
+ if (!deepEqual(computedFormValues, _computeFormValues.current)) {
1067
+ updateValue(computedFormValues);
1068
+ _computeFormValues.current = computedFormValues;
1069
+ }
1070
+ } else updateValue(formValues);
1071
+ }
1072
+ }, [
1073
+ control._formValues,
1074
+ control._names,
1075
+ disabled,
1076
+ name
1077
+ ]);
1078
+ useIsomorphicLayoutEffect(() => {
1079
+ if (_prevControl.current !== control || !deepEqual(_prevName.current, name)) {
1080
+ _prevControl.current = control;
1081
+ _prevName.current = name;
1082
+ refreshValue();
1083
+ }
1084
+ return control._subscribe({
1085
+ name,
1086
+ formState: { values: true },
1087
+ exact,
1088
+ callback: (formState) => {
1089
+ refreshValue(formState.values);
1090
+ }
1091
+ });
1092
+ }, [
1093
+ control,
1094
+ exact,
1095
+ name,
1096
+ refreshValue
1097
+ ]);
1098
+ React.useEffect(() => control._removeUnmounted());
1099
+ const controlChanged = _prevControl.current !== control;
1100
+ const prevName = _prevName.current;
1101
+ const computedOutput = React.useMemo(() => {
1102
+ if (disabled) return null;
1103
+ const nameChanged = !controlChanged && !deepEqual(prevName, name);
1104
+ return controlChanged || nameChanged ? getCurrentOutput() : null;
1105
+ }, [
1106
+ disabled,
1107
+ controlChanged,
1108
+ name,
1109
+ prevName,
1110
+ getCurrentOutput
1111
+ ]);
1112
+ return computedOutput !== null ? computedOutput : value;
1113
+ }
1114
+ /**
1115
+ * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
1116
+ *
1117
+ * @remarks
1118
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
1119
+ *
1120
+ * @param props - the path name to the form field value, and validation rules.
1121
+ *
1122
+ * @returns field properties, field and form state. {@link UseControllerReturn}
1123
+ *
1124
+ * @example
1125
+ * ```tsx
1126
+ * function Input(props) {
1127
+ * const { field, fieldState, formState } = useController(props);
1128
+ * return (
1129
+ * <div>
1130
+ * <input {...field} placeholder={props.name} />
1131
+ * <p>{fieldState.isTouched && "Touched"}</p>
1132
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
1133
+ * </div>
1134
+ * );
1135
+ * }
1136
+ * ```
1137
+ */
1138
+ function useController(props) {
1139
+ const formControl = useFormControlContext();
1140
+ const { name, disabled, control = formControl, shouldUnregister, defaultValue, exact = true } = props;
1141
+ const isArrayField = isNameInFieldArray(control._names.array, name);
1142
+ const value = useWatch({
1143
+ control,
1144
+ name,
1145
+ defaultValue: React.useMemo(() => get(control._formValues, name, get(control._defaultValues, name, defaultValue)), [
1146
+ control,
1147
+ name,
1148
+ defaultValue
1149
+ ]),
1150
+ exact
1151
+ });
1152
+ const formState = useFormState({
1153
+ control,
1154
+ name,
1155
+ exact
1156
+ });
1157
+ const _props = React.useRef(props);
1158
+ const _previousNameRef = React.useRef(void 0);
1159
+ const _registerProps = React.useRef(control.register(name, {
1160
+ ...props.rules,
1161
+ value,
1162
+ ...isBoolean(props.disabled) ? { disabled: props.disabled } : {}
1163
+ }));
1164
+ _props.current = props;
1165
+ const fieldState = React.useMemo(() => Object.defineProperties({}, {
1166
+ invalid: {
1167
+ enumerable: true,
1168
+ get: () => !!get(formState.errors, name)
1169
+ },
1170
+ isDirty: {
1171
+ enumerable: true,
1172
+ get: () => !!get(formState.dirtyFields, name)
1173
+ },
1174
+ isTouched: {
1175
+ enumerable: true,
1176
+ get: () => !!get(formState.touchedFields, name)
1177
+ },
1178
+ isValidating: {
1179
+ enumerable: true,
1180
+ get: () => !!get(formState.validatingFields, name)
1181
+ },
1182
+ error: {
1183
+ enumerable: true,
1184
+ get: () => get(formState.errors, name)
1185
+ }
1186
+ }), [formState, name]);
1187
+ const onChange = React.useCallback((event) => _registerProps.current.onChange({
1188
+ target: {
1189
+ value: getEventValue(event),
1190
+ name
1191
+ },
1192
+ type: EVENTS.CHANGE
1193
+ }), [name]);
1194
+ const onBlur = React.useCallback(() => _registerProps.current.onBlur({
1195
+ target: {
1196
+ value: get(control._formValues, name),
1197
+ name
1198
+ },
1199
+ type: EVENTS.BLUR
1200
+ }), [name, control._formValues]);
1201
+ const ref = React.useCallback((elm) => {
1202
+ const field = get(control._fields, name);
1203
+ if (field && field._f && elm) field._f.ref = {
1204
+ focus: () => isFunction(elm.focus) && elm.focus(),
1205
+ select: () => isFunction(elm.select) && elm.select(),
1206
+ setCustomValidity: (message) => isFunction(elm.setCustomValidity) && elm.setCustomValidity(message),
1207
+ reportValidity: () => isFunction(elm.reportValidity) && elm.reportValidity()
1208
+ };
1209
+ }, [control._fields, name]);
1210
+ const field = React.useMemo(() => ({
1211
+ name,
1212
+ value,
1213
+ ...isBoolean(disabled) || formState.disabled ? { disabled: formState.disabled || disabled } : {},
1214
+ onChange,
1215
+ onBlur,
1216
+ ref
1217
+ }), [
1218
+ name,
1219
+ disabled,
1220
+ formState.disabled,
1221
+ onChange,
1222
+ onBlur,
1223
+ ref,
1224
+ value
1225
+ ]);
1226
+ React.useEffect(() => {
1227
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
1228
+ const previousName = _previousNameRef.current;
1229
+ if (previousName && previousName !== name && !isArrayField) control.unregister(previousName);
1230
+ control.register(name, {
1231
+ ..._props.current.rules,
1232
+ ...isBoolean(_props.current.disabled) ? { disabled: _props.current.disabled } : {}
1233
+ });
1234
+ const updateMounted = (name, value) => {
1235
+ const field = get(control._fields, name);
1236
+ if (field && field._f) field._f.mount = value;
1237
+ };
1238
+ updateMounted(name, true);
1239
+ if (_shouldUnregisterField) {
1240
+ const value = cloneObject(get(control._options.defaultValues, name, _props.current.defaultValue));
1241
+ set(control._defaultValues, name, value);
1242
+ if (isUndefined(get(control._formValues, name))) set(control._formValues, name, value);
1243
+ }
1244
+ !isArrayField && control.register(name);
1245
+ _previousNameRef.current = name;
1246
+ return () => {
1247
+ (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false);
1248
+ };
1249
+ }, [
1250
+ name,
1251
+ control,
1252
+ isArrayField,
1253
+ shouldUnregister
1254
+ ]);
1255
+ React.useEffect(() => {
1256
+ control._setDisabledField({
1257
+ disabled,
1258
+ name
1259
+ });
1260
+ }, [
1261
+ disabled,
1262
+ name,
1263
+ control
1264
+ ]);
1265
+ return React.useMemo(() => ({
1266
+ field,
1267
+ formState,
1268
+ fieldState
1269
+ }), [
1270
+ field,
1271
+ formState,
1272
+ fieldState
1273
+ ]);
1274
+ }
1275
+ /**
1276
+ * Component based on `useController` hook to work with controlled component.
1277
+ *
1278
+ * @remarks
1279
+ * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
1280
+ *
1281
+ * @param props - the path name to the form field value, and validation rules.
1282
+ *
1283
+ * @returns provide field handler functions, field and form state.
1284
+ *
1285
+ * @example
1286
+ * ```tsx
1287
+ * function App() {
1288
+ * const { control } = useForm<FormValues>({
1289
+ * defaultValues: {
1290
+ * test: ""
1291
+ * }
1292
+ * });
1293
+ *
1294
+ * return (
1295
+ * <form>
1296
+ * <Controller
1297
+ * control={control}
1298
+ * name="test"
1299
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
1300
+ * <>
1301
+ * <input
1302
+ * onChange={onChange} // send value to hook form
1303
+ * onBlur={onBlur} // notify when input is touched
1304
+ * value={value} // return updated value
1305
+ * ref={ref} // set ref for focus management
1306
+ * />
1307
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
1308
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
1309
+ * </>
1310
+ * )}
1311
+ * />
1312
+ * </form>
1313
+ * );
1314
+ * }
1315
+ * ```
1316
+ */
1317
+ const Controller = (props) => props.render(useController(props));
1318
+ const HookFormContext = React.createContext(null);
1319
+ HookFormContext.displayName = "HookFormContext";
1320
+ /**
1321
+ * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
1322
+ *
1323
+ * @remarks
1324
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
1325
+ *
1326
+ * @returns return all useForm methods
1327
+ *
1328
+ * @example
1329
+ * ```tsx
1330
+ * function App() {
1331
+ * const methods = useForm();
1332
+ * const onSubmit = data => console.log(data);
1333
+ *
1334
+ * return (
1335
+ * <FormProvider {...methods} >
1336
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
1337
+ * <NestedInput />
1338
+ * <input type="submit" />
1339
+ * </form>
1340
+ * </FormProvider>
1341
+ * );
1342
+ * }
1343
+ *
1344
+ * function NestedInput() {
1345
+ * const { register } = useFormContext(); // retrieve all hook methods
1346
+ * return <input {...register("test")} />;
1347
+ * }
1348
+ * ```
1349
+ */
1350
+ const useFormContext = () => React.useContext(HookFormContext);
1351
+ /**
1352
+ * A provider component that propagates the `useForm` methods to all children components via [React Context](https://react.dev/reference/react/useContext) API. To be used with {@link useFormContext}.
1353
+ *
1354
+ * @remarks
1355
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
1356
+ *
1357
+ * @param props - all useForm methods
1358
+ *
1359
+ * @example
1360
+ * ```tsx
1361
+ * function App() {
1362
+ * const methods = useForm();
1363
+ * const onSubmit = data => console.log(data);
1364
+ *
1365
+ * return (
1366
+ * <FormProvider {...methods} >
1367
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
1368
+ * <NestedInput />
1369
+ * <input type="submit" />
1370
+ * </form>
1371
+ * </FormProvider>
1372
+ * );
1373
+ * }
1374
+ *
1375
+ * function NestedInput() {
1376
+ * const { register } = useFormContext(); // retrieve all hook methods
1377
+ * return <input {...register("test")} />;
1378
+ * }
1379
+ * ```
1380
+ */
1381
+ const FormProvider = (props) => {
1382
+ const { children, watch, getValues, getFieldState, setError, clearErrors, setValue, trigger, formState, resetField, reset, handleSubmit, unregister, control, register, setFocus, subscribe } = props;
1383
+ return React.createElement(HookFormContext.Provider, { value: React.useMemo(() => ({
1384
+ watch,
1385
+ getValues,
1386
+ getFieldState,
1387
+ setError,
1388
+ clearErrors,
1389
+ setValue,
1390
+ trigger,
1391
+ formState,
1392
+ resetField,
1393
+ reset,
1394
+ handleSubmit,
1395
+ unregister,
1396
+ control,
1397
+ register,
1398
+ setFocus,
1399
+ subscribe
1400
+ }), [
1401
+ clearErrors,
1402
+ control,
1403
+ formState,
1404
+ getFieldState,
1405
+ getValues,
1406
+ handleSubmit,
1407
+ register,
1408
+ reset,
1409
+ resetField,
1410
+ setError,
1411
+ setFocus,
1412
+ setValue,
1413
+ subscribe,
1414
+ trigger,
1415
+ unregister,
1416
+ watch
1417
+ ]) }, React.createElement(HookFormControlContext.Provider, { value: control }, children));
1418
+ };
1419
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
1420
+ ...errors[name],
1421
+ types: {
1422
+ ...errors[name] && errors[name].types ? errors[name].types : {},
1423
+ [type]: message || true
1424
+ }
1425
+ } : {};
1426
+ var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
1427
+ var createSubject = () => {
1428
+ let _observers = [];
1429
+ const next = (value) => {
1430
+ for (const observer of _observers) observer.next && observer.next(value);
1431
+ };
1432
+ const subscribe = (observer) => {
1433
+ _observers.push(observer);
1434
+ return { unsubscribe: () => {
1435
+ _observers = _observers.filter((o) => o !== observer);
1436
+ } };
1437
+ };
1438
+ const unsubscribe = () => {
1439
+ _observers = [];
1440
+ };
1441
+ return {
1442
+ get observers() {
1443
+ return _observers;
1444
+ },
1445
+ next,
1446
+ subscribe,
1447
+ unsubscribe
1448
+ };
1449
+ };
1450
+ function extractFormValues(fieldsState, formValues) {
1451
+ const values = {};
1452
+ for (const key in fieldsState) if (fieldsState.hasOwnProperty(key)) {
1453
+ const fieldState = fieldsState[key];
1454
+ const fieldValue = formValues[key];
1455
+ if (fieldState && isObject(fieldState) && fieldValue) {
1456
+ const nestedFieldsState = extractFormValues(fieldState, fieldValue);
1457
+ if (isObject(nestedFieldsState)) values[key] = nestedFieldsState;
1458
+ } else if (fieldsState[key]) values[key] = fieldValue;
1459
+ }
1460
+ return values;
1461
+ }
1462
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
1463
+ var isFileInput = (element) => element.type === "file";
1464
+ var isHTMLElement = (value) => {
1465
+ if (!isWeb) return false;
1466
+ const owner = value ? value.ownerDocument : 0;
1467
+ return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
1468
+ };
1469
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
1470
+ var isRadioInput = (element) => element.type === "radio";
1471
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1472
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1473
+ function baseGet(object, updatePath) {
1474
+ const length = updatePath.slice(0, -1).length;
1475
+ let index = 0;
1476
+ while (index < length) object = isUndefined(object) ? index++ : object[updatePath[index++]];
1477
+ return object;
1478
+ }
1479
+ function isEmptyArray(obj) {
1480
+ for (const key in obj) if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) return false;
1481
+ return true;
1482
+ }
1483
+ function unset(object, path) {
1484
+ const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
1485
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
1486
+ const index = paths.length - 1;
1487
+ const key = paths[index];
1488
+ if (childObject) delete childObject[key];
1489
+ if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) unset(object, paths.slice(0, -1));
1490
+ return object;
1491
+ }
1492
+ var objectHasFunction = (data) => {
1493
+ for (const key in data) if (isFunction(data[key])) return true;
1494
+ return false;
1495
+ };
1496
+ function isTraversable(value) {
1497
+ return Array.isArray(value) || isObject(value) && !objectHasFunction(value);
1498
+ }
1499
+ function markFieldsDirty(data, fields = {}) {
1500
+ for (const key in data) {
1501
+ const value = data[key];
1502
+ if (isTraversable(value)) {
1503
+ fields[key] = Array.isArray(value) ? [] : {};
1504
+ markFieldsDirty(value, fields[key]);
1505
+ } else if (!isUndefined(value)) fields[key] = true;
1506
+ }
1507
+ return fields;
1508
+ }
1509
+ function getDirtyFields(data, formValues, dirtyFieldsFromValues) {
1510
+ if (!dirtyFieldsFromValues) dirtyFieldsFromValues = markFieldsDirty(formValues);
1511
+ for (const key in data) {
1512
+ const value = data[key];
1513
+ if (isTraversable(value)) {
1514
+ if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) dirtyFieldsFromValues[key] = markFieldsDirty(value, Array.isArray(value) ? [] : {});
1515
+ else getDirtyFields(value, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1516
+ } else {
1517
+ const formValue = formValues[key];
1518
+ dirtyFieldsFromValues[key] = !deepEqual(value, formValue);
1519
+ }
1520
+ }
1521
+ return dirtyFieldsFromValues;
1522
+ }
1523
+ const defaultResult = {
1524
+ value: false,
1525
+ isValid: false
1526
+ };
1527
+ const validResult = {
1528
+ value: true,
1529
+ isValid: true
1530
+ };
1531
+ var getCheckboxValue = (options) => {
1532
+ if (Array.isArray(options)) {
1533
+ if (options.length > 1) {
1534
+ const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
1535
+ return {
1536
+ value: values,
1537
+ isValid: !!values.length
1538
+ };
1539
+ }
1540
+ return options[0].checked && !options[0].disabled ? options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : {
1541
+ value: options[0].value,
1542
+ isValid: true
1543
+ } : validResult : defaultResult;
1544
+ }
1545
+ return defaultResult;
1546
+ };
1547
+ 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;
1548
+ const defaultReturn = {
1549
+ isValid: false,
1550
+ value: null
1551
+ };
1552
+ var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
1553
+ isValid: true,
1554
+ value: option.value
1555
+ } : previous, defaultReturn) : defaultReturn;
1556
+ function getFieldValue(_f) {
1557
+ const ref = _f.ref;
1558
+ if (isFileInput(ref)) return ref.files;
1559
+ if (isRadioInput(ref)) return getRadioValue(_f.refs).value;
1560
+ if (isMultipleSelect(ref)) return [...ref.selectedOptions].map(({ value }) => value);
1561
+ if (isCheckBoxInput(ref)) return getCheckboxValue(_f.refs).value;
1562
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1563
+ }
1564
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1565
+ const fields = {};
1566
+ for (const name of fieldsNames) {
1567
+ const field = get(_fields, name);
1568
+ field && set(fields, name, field._f);
1569
+ }
1570
+ return {
1571
+ criteriaMode,
1572
+ names: [...fieldsNames],
1573
+ fields,
1574
+ shouldUseNativeValidation
1575
+ };
1576
+ };
1577
+ var isRegex = (value) => value instanceof RegExp;
1578
+ var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
1579
+ var getValidationModes = (mode) => ({
1580
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
1581
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
1582
+ isOnChange: mode === VALIDATION_MODE.onChange,
1583
+ isOnAll: mode === VALIDATION_MODE.all,
1584
+ isOnTouch: mode === VALIDATION_MODE.onTouched
1585
+ });
1586
+ const ASYNC_FUNCTION = "AsyncFunction";
1587
+ var hasPromiseValidation = (fieldReference) => !!fieldReference && !!fieldReference.validate && !!(isFunction(fieldReference.validate) && fieldReference.validate.constructor.name === ASYNC_FUNCTION || isObject(fieldReference.validate) && Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION));
1588
+ var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
1589
+ 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))));
1590
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
1591
+ for (const key of fieldsNames || Object.keys(fields)) {
1592
+ const field = get(fields, key);
1593
+ if (field) {
1594
+ const { _f, ...currentField } = field;
1595
+ if (_f) {
1596
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) return true;
1597
+ else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) return true;
1598
+ else if (iterateFieldsByAction(currentField, action)) break;
1599
+ } else if (isObject(currentField)) {
1600
+ if (iterateFieldsByAction(currentField, action)) break;
1601
+ }
1602
+ }
1603
+ }
1604
+ };
1605
+ function schemaErrorLookup(errors, _fields, name) {
1606
+ const error = get(errors, name);
1607
+ if (error || isKey(name)) return {
1608
+ error,
1609
+ name
1610
+ };
1611
+ const names = name.split(".");
1612
+ while (names.length) {
1613
+ const fieldName = names.join(".");
1614
+ const field = get(_fields, fieldName);
1615
+ const foundError = get(errors, fieldName);
1616
+ if (field && !Array.isArray(field) && name !== fieldName) return { name };
1617
+ if (foundError && foundError.type) return {
1618
+ name: fieldName,
1619
+ error: foundError
1620
+ };
1621
+ if (foundError && foundError.root && foundError.root.type) return {
1622
+ name: `${fieldName}.root`,
1623
+ error: foundError.root
1624
+ };
1625
+ names.pop();
1626
+ }
1627
+ return { name };
1628
+ }
1629
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
1630
+ updateFormState(formStateData);
1631
+ const { name, ...formState } = formStateData;
1632
+ return isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
1633
+ };
1634
+ var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
1635
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1636
+ if (mode.isOnAll) return false;
1637
+ else if (!isSubmitted && mode.isOnTouch) return !(isTouched || isBlurEvent);
1638
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) return !isBlurEvent;
1639
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) return isBlurEvent;
1640
+ return true;
1641
+ };
1642
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1643
+ var updateFieldArrayRootError = (errors, error, name) => {
1644
+ const fieldArrayErrors = convertToArrayPayload(get(errors, name));
1645
+ set(fieldArrayErrors, "root", error[name]);
1646
+ set(errors, name, fieldArrayErrors);
1647
+ return errors;
1648
+ };
1649
+ function getValidateError(result, ref, type = "validate") {
1650
+ if (isString(result) || Array.isArray(result) && result.every(isString) || isBoolean(result) && !result) return {
1651
+ type,
1652
+ message: isString(result) ? result : "",
1653
+ ref
1654
+ };
1655
+ }
1656
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
1657
+ value: validationData,
1658
+ message: ""
1659
+ };
1660
+ var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
1661
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount } = field._f;
1662
+ const inputValue = get(formValues, name);
1663
+ if (!mount || disabledFieldNames.has(name)) return {};
1664
+ const inputRef = refs ? refs[0] : ref;
1665
+ const setCustomValidity = (message) => {
1666
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
1667
+ inputRef.setCustomValidity(isBoolean(message) ? "" : message || "");
1668
+ inputRef.reportValidity();
1669
+ }
1670
+ };
1671
+ const error = {};
1672
+ const isRadio = isRadioInput(ref);
1673
+ const isCheckBox = isCheckBoxInput(ref);
1674
+ const isRadioOrCheckbox = isRadio || isCheckBox;
1675
+ const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
1676
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
1677
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
1678
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
1679
+ error[name] = {
1680
+ type: exceedMax ? maxType : minType,
1681
+ message,
1682
+ ref,
1683
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message)
1684
+ };
1685
+ };
1686
+ if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
1687
+ const { value, message } = isString(required) ? {
1688
+ value: !!required,
1689
+ message: required
1690
+ } : getValueAndMessage(required);
1691
+ if (value) {
1692
+ error[name] = {
1693
+ type: INPUT_VALIDATION_RULES.required,
1694
+ message,
1695
+ ref: inputRef,
1696
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
1697
+ };
1698
+ if (!validateAllFieldCriteria) {
1699
+ setCustomValidity(message);
1700
+ return error;
1701
+ }
1702
+ }
1703
+ }
1704
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
1705
+ let exceedMax;
1706
+ let exceedMin;
1707
+ const maxOutput = getValueAndMessage(max);
1708
+ const minOutput = getValueAndMessage(min);
1709
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
1710
+ const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
1711
+ if (!isNullOrUndefined(maxOutput.value)) exceedMax = valueNumber > maxOutput.value;
1712
+ if (!isNullOrUndefined(minOutput.value)) exceedMin = valueNumber < minOutput.value;
1713
+ } else {
1714
+ const valueDate = ref.valueAsDate || new Date(inputValue);
1715
+ const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
1716
+ const isTime = ref.type == "time";
1717
+ const isWeek = ref.type == "week";
1718
+ if (isString(maxOutput.value) && inputValue) exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
1719
+ if (isString(minOutput.value) && inputValue) exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
1720
+ }
1721
+ if (exceedMax || exceedMin) {
1722
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
1723
+ if (!validateAllFieldCriteria) {
1724
+ setCustomValidity(error[name].message);
1725
+ return error;
1726
+ }
1727
+ }
1728
+ }
1729
+ if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
1730
+ const maxLengthOutput = getValueAndMessage(maxLength);
1731
+ const minLengthOutput = getValueAndMessage(minLength);
1732
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
1733
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
1734
+ if (exceedMax || exceedMin) {
1735
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
1736
+ if (!validateAllFieldCriteria) {
1737
+ setCustomValidity(error[name].message);
1738
+ return error;
1739
+ }
1740
+ }
1741
+ }
1742
+ if (pattern && !isEmpty && isString(inputValue)) {
1743
+ const { value: patternValue, message } = getValueAndMessage(pattern);
1744
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
1745
+ error[name] = {
1746
+ type: INPUT_VALIDATION_RULES.pattern,
1747
+ message,
1748
+ ref,
1749
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
1750
+ };
1751
+ if (!validateAllFieldCriteria) {
1752
+ setCustomValidity(message);
1753
+ return error;
1754
+ }
1755
+ }
1756
+ }
1757
+ if (validate) {
1758
+ if (isFunction(validate)) {
1759
+ const validateError = getValidateError(await validate(inputValue, formValues), inputRef);
1760
+ if (validateError) {
1761
+ error[name] = {
1762
+ ...validateError,
1763
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
1764
+ };
1765
+ if (!validateAllFieldCriteria) {
1766
+ setCustomValidity(validateError.message);
1767
+ return error;
1768
+ }
1769
+ }
1770
+ } else if (isObject(validate)) {
1771
+ let validationResult = {};
1772
+ for (const key in validate) {
1773
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) break;
1774
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
1775
+ if (validateError) {
1776
+ validationResult = {
1777
+ ...validateError,
1778
+ ...appendErrorsCurry(key, validateError.message)
1779
+ };
1780
+ setCustomValidity(validateError.message);
1781
+ if (validateAllFieldCriteria) error[name] = validationResult;
1782
+ }
1783
+ }
1784
+ if (!isEmptyObject(validationResult)) {
1785
+ error[name] = {
1786
+ ref: inputRef,
1787
+ ...validationResult
1788
+ };
1789
+ if (!validateAllFieldCriteria) return error;
1790
+ }
1791
+ }
1792
+ }
1793
+ setCustomValidity(true);
1794
+ return error;
1795
+ };
1796
+ const defaultOptions = {
1797
+ mode: VALIDATION_MODE.onSubmit,
1798
+ reValidateMode: VALIDATION_MODE.onChange,
1799
+ shouldFocusError: true
1800
+ };
1801
+ function createFormControl(props = {}) {
1802
+ let _options = {
1803
+ ...defaultOptions,
1804
+ ...props
1805
+ };
1806
+ let _formState = {
1807
+ submitCount: 0,
1808
+ isDirty: false,
1809
+ isReady: false,
1810
+ isLoading: isFunction(_options.defaultValues),
1811
+ isValidating: false,
1812
+ isSubmitted: false,
1813
+ isSubmitting: false,
1814
+ isSubmitSuccessful: false,
1815
+ isValid: false,
1816
+ touchedFields: {},
1817
+ dirtyFields: {},
1818
+ validatingFields: {},
1819
+ errors: _options.errors || {},
1820
+ disabled: _options.disabled || false
1821
+ };
1822
+ let _fields = {};
1823
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
1824
+ let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
1825
+ let _state = {
1826
+ action: false,
1827
+ mount: false,
1828
+ watch: false,
1829
+ keepIsValid: false
1830
+ };
1831
+ let _names = {
1832
+ mount: /* @__PURE__ */ new Set(),
1833
+ disabled: /* @__PURE__ */ new Set(),
1834
+ unMount: /* @__PURE__ */ new Set(),
1835
+ array: /* @__PURE__ */ new Set(),
1836
+ watch: /* @__PURE__ */ new Set()
1837
+ };
1838
+ let delayErrorCallback;
1839
+ let timer = 0;
1840
+ const defaultProxyFormState = {
1841
+ isDirty: false,
1842
+ dirtyFields: false,
1843
+ validatingFields: false,
1844
+ touchedFields: false,
1845
+ isValidating: false,
1846
+ isValid: false,
1847
+ errors: false
1848
+ };
1849
+ const _proxyFormState = { ...defaultProxyFormState };
1850
+ let _proxySubscribeFormState = { ..._proxyFormState };
1851
+ const _subjects = {
1852
+ array: createSubject(),
1853
+ state: createSubject()
1854
+ };
1855
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1856
+ const debounce = (callback) => (wait) => {
1857
+ clearTimeout(timer);
1858
+ timer = setTimeout(callback, wait);
1859
+ };
1860
+ const _setValid = async (shouldUpdateValid) => {
1861
+ if (_state.keepIsValid) return;
1862
+ if (!_options.disabled && (_proxyFormState.isValid || _proxySubscribeFormState.isValid || shouldUpdateValid)) {
1863
+ let isValid;
1864
+ if (_options.resolver) {
1865
+ isValid = isEmptyObject((await _runSchema()).errors);
1866
+ _updateIsValidating();
1867
+ } else isValid = await executeBuiltInValidation(_fields, true);
1868
+ if (isValid !== _formState.isValid) _subjects.state.next({ isValid });
1869
+ }
1870
+ };
1871
+ const _updateIsValidating = (names, isValidating) => {
1872
+ if (!_options.disabled && (_proxyFormState.isValidating || _proxyFormState.validatingFields || _proxySubscribeFormState.isValidating || _proxySubscribeFormState.validatingFields)) {
1873
+ (names || Array.from(_names.mount)).forEach((name) => {
1874
+ if (name) isValidating ? set(_formState.validatingFields, name, isValidating) : unset(_formState.validatingFields, name);
1875
+ });
1876
+ _subjects.state.next({
1877
+ validatingFields: _formState.validatingFields,
1878
+ isValidating: !isEmptyObject(_formState.validatingFields)
1879
+ });
1880
+ }
1881
+ };
1882
+ const _setFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1883
+ if (args && method && !_options.disabled) {
1884
+ _state.action = true;
1885
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1886
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
1887
+ shouldSetValues && set(_fields, name, fieldValues);
1888
+ }
1889
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
1890
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
1891
+ shouldSetValues && set(_formState.errors, name, errors);
1892
+ unsetEmptyArray(_formState.errors, name);
1893
+ }
1894
+ if ((_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
1895
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1896
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1897
+ }
1898
+ if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1899
+ _subjects.state.next({
1900
+ name,
1901
+ isDirty: _getDirty(name, values),
1902
+ dirtyFields: _formState.dirtyFields,
1903
+ errors: _formState.errors,
1904
+ isValid: _formState.isValid
1905
+ });
1906
+ } else set(_formValues, name, values);
1907
+ };
1908
+ const updateErrors = (name, error) => {
1909
+ set(_formState.errors, name, error);
1910
+ _subjects.state.next({ errors: _formState.errors });
1911
+ };
1912
+ const _setErrors = (errors) => {
1913
+ _formState.errors = errors;
1914
+ _subjects.state.next({
1915
+ errors: _formState.errors,
1916
+ isValid: false
1917
+ });
1918
+ };
1919
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1920
+ const field = get(_fields, name);
1921
+ if (field) {
1922
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1923
+ isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
1924
+ _state.mount && !_state.action && _setValid();
1925
+ }
1926
+ };
1927
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1928
+ let shouldUpdateField = false;
1929
+ let isPreviousDirty = false;
1930
+ const output = { name };
1931
+ if (!_options.disabled) {
1932
+ if (!isBlurEvent || shouldDirty) {
1933
+ if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {
1934
+ isPreviousDirty = _formState.isDirty;
1935
+ _formState.isDirty = output.isDirty = _getDirty();
1936
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
1937
+ }
1938
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1939
+ isPreviousDirty = !!get(_formState.dirtyFields, name);
1940
+ isCurrentFieldPristine ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
1941
+ output.dirtyFields = _formState.dirtyFields;
1942
+ shouldUpdateField = shouldUpdateField || (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) && isPreviousDirty !== !isCurrentFieldPristine;
1943
+ }
1944
+ if (isBlurEvent) {
1945
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
1946
+ if (!isPreviousFieldTouched) {
1947
+ set(_formState.touchedFields, name, isBlurEvent);
1948
+ output.touchedFields = _formState.touchedFields;
1949
+ shouldUpdateField = shouldUpdateField || (_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && isPreviousFieldTouched !== isBlurEvent;
1950
+ }
1951
+ }
1952
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1953
+ }
1954
+ return shouldUpdateField ? output : {};
1955
+ };
1956
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1957
+ const previousFieldError = get(_formState.errors, name);
1958
+ const shouldUpdateValid = (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isBoolean(isValid) && _formState.isValid !== isValid;
1959
+ if (_options.delayError && error) {
1960
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1961
+ delayErrorCallback(_options.delayError);
1962
+ } else {
1963
+ clearTimeout(timer);
1964
+ delayErrorCallback = null;
1965
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1966
+ }
1967
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
1968
+ const updatedFormState = {
1969
+ ...fieldState,
1970
+ ...shouldUpdateValid && isBoolean(isValid) ? { isValid } : {},
1971
+ errors: _formState.errors,
1972
+ name
1973
+ };
1974
+ _formState = {
1975
+ ..._formState,
1976
+ ...updatedFormState
1977
+ };
1978
+ _subjects.state.next(updatedFormState);
1979
+ }
1980
+ };
1981
+ const _runSchema = async (name) => {
1982
+ _updateIsValidating(name, true);
1983
+ return await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1984
+ };
1985
+ const executeSchemaAndUpdateState = async (names) => {
1986
+ const { errors } = await _runSchema(names);
1987
+ _updateIsValidating(names);
1988
+ if (names) for (const name of names) {
1989
+ const error = get(errors, name);
1990
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1991
+ }
1992
+ else _formState.errors = errors;
1993
+ return errors;
1994
+ };
1995
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = { valid: true }) => {
1996
+ for (const name in fields) {
1997
+ const field = fields[name];
1998
+ if (field) {
1999
+ const { _f, ...fieldValue } = field;
2000
+ if (_f) {
2001
+ const isFieldArrayRoot = _names.array.has(_f.name);
2002
+ const isPromiseFunction = field._f && hasPromiseValidation(field._f);
2003
+ if (isPromiseFunction && _proxyFormState.validatingFields) _updateIsValidating([_f.name], true);
2004
+ const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
2005
+ if (isPromiseFunction && _proxyFormState.validatingFields) _updateIsValidating([_f.name]);
2006
+ if (fieldError[_f.name]) {
2007
+ context.valid = false;
2008
+ if (shouldOnlyCheckValid || props.shouldUseNativeValidation) break;
2009
+ }
2010
+ !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));
2011
+ }
2012
+ !isEmptyObject(fieldValue) && await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context);
2013
+ }
2014
+ }
2015
+ return context.valid;
2016
+ };
2017
+ const _removeUnmounted = () => {
2018
+ for (const name of _names.unMount) {
2019
+ const field = get(_fields, name);
2020
+ field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
2021
+ }
2022
+ _names.unMount = /* @__PURE__ */ new Set();
2023
+ };
2024
+ const _getDirty = (name, data) => !_options.disabled && (name && data && set(_formValues, name, data), !deepEqual(getValues(), _defaultValues));
2025
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, { ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue }, isGlobal, defaultValue);
2026
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
2027
+ const setFieldValue = (name, value, options = {}) => {
2028
+ const field = get(_fields, name);
2029
+ let fieldValue = value;
2030
+ if (field) {
2031
+ const fieldReference = field._f;
2032
+ if (fieldReference) {
2033
+ !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
2034
+ fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
2035
+ if (isMultipleSelect(fieldReference.ref)) [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
2036
+ else if (fieldReference.refs) {
2037
+ if (isCheckBoxInput(fieldReference.ref)) fieldReference.refs.forEach((checkboxRef) => {
2038
+ if (!checkboxRef.defaultChecked || !checkboxRef.disabled) {
2039
+ if (Array.isArray(fieldValue)) checkboxRef.checked = !!fieldValue.find((data) => data === checkboxRef.value);
2040
+ else checkboxRef.checked = fieldValue === checkboxRef.value || !!fieldValue;
2041
+ }
2042
+ });
2043
+ else fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
2044
+ } else if (isFileInput(fieldReference.ref)) fieldReference.ref.value = "";
2045
+ else {
2046
+ fieldReference.ref.value = fieldValue;
2047
+ if (!fieldReference.ref.type) _subjects.state.next({
2048
+ name,
2049
+ values: cloneObject(_formValues)
2050
+ });
2051
+ }
2052
+ }
2053
+ }
2054
+ (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
2055
+ options.shouldValidate && trigger(name);
2056
+ };
2057
+ const setValues = (name, value, options) => {
2058
+ for (const fieldKey in value) {
2059
+ if (!value.hasOwnProperty(fieldKey)) return;
2060
+ const fieldValue = value[fieldKey];
2061
+ const fieldName = name + "." + fieldKey;
2062
+ const field = get(_fields, fieldName);
2063
+ (_names.array.has(name) || isObject(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options);
2064
+ }
2065
+ };
2066
+ const setValue = (name, value, options = {}) => {
2067
+ const field = get(_fields, name);
2068
+ const isFieldArray = _names.array.has(name);
2069
+ const cloneValue = cloneObject(value);
2070
+ set(_formValues, name, cloneValue);
2071
+ if (isFieldArray) {
2072
+ _subjects.array.next({
2073
+ name,
2074
+ values: cloneObject(_formValues)
2075
+ });
2076
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields || _proxySubscribeFormState.isDirty || _proxySubscribeFormState.dirtyFields) && options.shouldDirty) _subjects.state.next({
2077
+ name,
2078
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
2079
+ isDirty: _getDirty(name, cloneValue)
2080
+ });
2081
+ } else field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options);
2082
+ if (isWatched(name, _names)) _subjects.state.next({
2083
+ ..._formState,
2084
+ name,
2085
+ values: cloneObject(_formValues)
2086
+ });
2087
+ else _subjects.state.next({
2088
+ name: _state.mount ? name : void 0,
2089
+ values: cloneObject(_formValues)
2090
+ });
2091
+ };
2092
+ const onChange = async (event) => {
2093
+ _state.mount = true;
2094
+ const target = event.target;
2095
+ let name = target.name;
2096
+ let isFieldValueUpdated = true;
2097
+ const field = get(_fields, name);
2098
+ const _updateIsFieldValueUpdated = (fieldValue) => {
2099
+ isFieldValueUpdated = Number.isNaN(fieldValue) || isDateObject(fieldValue) && isNaN(fieldValue.getTime()) || deepEqual(fieldValue, get(_formValues, name, fieldValue));
2100
+ };
2101
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
2102
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
2103
+ if (field) {
2104
+ let error;
2105
+ let isValid;
2106
+ const fieldValue = target.type ? getFieldValue(field._f) : getEventValue(event);
2107
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
2108
+ const shouldSkipValidation = !hasValidation(field._f) && !_options.resolver && !get(_formState.errors, name) && !field._f.deps || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
2109
+ const watched = isWatched(name, _names, isBlurEvent);
2110
+ set(_formValues, name, fieldValue);
2111
+ if (isBlurEvent) {
2112
+ if (!target || !target.readOnly) {
2113
+ field._f.onBlur && field._f.onBlur(event);
2114
+ delayErrorCallback && delayErrorCallback(0);
2115
+ }
2116
+ } else if (field._f.onChange) field._f.onChange(event);
2117
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);
2118
+ const shouldRender = !isEmptyObject(fieldState) || watched;
2119
+ !isBlurEvent && _subjects.state.next({
2120
+ name,
2121
+ type: event.type,
2122
+ values: cloneObject(_formValues)
2123
+ });
2124
+ if (shouldSkipValidation) {
2125
+ if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) {
2126
+ if (_options.mode === "onBlur") {
2127
+ if (isBlurEvent) _setValid();
2128
+ } else if (!isBlurEvent) _setValid();
2129
+ }
2130
+ return shouldRender && _subjects.state.next({
2131
+ name,
2132
+ ...watched ? {} : fieldState
2133
+ });
2134
+ }
2135
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
2136
+ if (_options.resolver) {
2137
+ const { errors } = await _runSchema([name]);
2138
+ _updateIsValidating([name]);
2139
+ _updateIsFieldValueUpdated(fieldValue);
2140
+ if (isFieldValueUpdated) {
2141
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
2142
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
2143
+ error = errorLookupResult.error;
2144
+ name = errorLookupResult.name;
2145
+ isValid = isEmptyObject(errors);
2146
+ }
2147
+ } else {
2148
+ _updateIsValidating([name], true);
2149
+ error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
2150
+ _updateIsValidating([name]);
2151
+ _updateIsFieldValueUpdated(fieldValue);
2152
+ if (isFieldValueUpdated) {
2153
+ if (error) isValid = false;
2154
+ else if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) isValid = await executeBuiltInValidation(_fields, true);
2155
+ }
2156
+ }
2157
+ if (isFieldValueUpdated) {
2158
+ field._f.deps && (!Array.isArray(field._f.deps) || field._f.deps.length > 0) && trigger(field._f.deps);
2159
+ shouldRenderByError(name, isValid, error, fieldState);
2160
+ }
2161
+ }
2162
+ };
2163
+ const _focusInput = (ref, key) => {
2164
+ if (get(_formState.errors, key) && ref.focus) {
2165
+ ref.focus();
2166
+ return 1;
2167
+ }
2168
+ };
2169
+ const trigger = async (name, options = {}) => {
2170
+ let isValid;
2171
+ let validationResult;
2172
+ const fieldNames = convertToArrayPayload(name);
2173
+ if (_options.resolver) {
2174
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
2175
+ isValid = isEmptyObject(errors);
2176
+ validationResult = name ? !fieldNames.some((name) => get(errors, name)) : isValid;
2177
+ } else if (name) {
2178
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
2179
+ const field = get(_fields, fieldName);
2180
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
2181
+ }))).every(Boolean);
2182
+ (validationResult || _formState.isValid) && _setValid();
2183
+ } else validationResult = isValid = await executeBuiltInValidation(_fields);
2184
+ _subjects.state.next({
2185
+ ...!isString(name) || (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isValid !== _formState.isValid ? {} : { name },
2186
+ ..._options.resolver || !name ? { isValid } : {},
2187
+ errors: _formState.errors
2188
+ });
2189
+ options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
2190
+ return validationResult;
2191
+ };
2192
+ const getValues = (fieldNames, config) => {
2193
+ let values = { ..._state.mount ? _formValues : _defaultValues };
2194
+ if (config) values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values);
2195
+ return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
2196
+ };
2197
+ const getFieldState = (name, formState) => ({
2198
+ invalid: !!get((formState || _formState).errors, name),
2199
+ isDirty: !!get((formState || _formState).dirtyFields, name),
2200
+ error: get((formState || _formState).errors, name),
2201
+ isValidating: !!get(_formState.validatingFields, name),
2202
+ isTouched: !!get((formState || _formState).touchedFields, name)
2203
+ });
2204
+ const clearErrors = (name) => {
2205
+ const names = name ? convertToArrayPayload(name) : void 0;
2206
+ names === null || names === void 0 || names.forEach((inputName) => unset(_formState.errors, inputName));
2207
+ if (names) names.forEach((inputName) => {
2208
+ _subjects.state.next({
2209
+ name: inputName,
2210
+ errors: _formState.errors
2211
+ });
2212
+ });
2213
+ else _subjects.state.next({ errors: {} });
2214
+ };
2215
+ const setError = (name, error, options) => {
2216
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
2217
+ const { ref: currentRef, message, type, ...restOfErrorTree } = get(_formState.errors, name) || {};
2218
+ set(_formState.errors, name, {
2219
+ ...restOfErrorTree,
2220
+ ...error,
2221
+ ref
2222
+ });
2223
+ _subjects.state.next({
2224
+ name,
2225
+ errors: _formState.errors,
2226
+ isValid: false
2227
+ });
2228
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
2229
+ };
2230
+ const watch = (name, defaultValue) => isFunction(name) ? _subjects.state.subscribe({ next: (payload) => "values" in payload && name(_getWatch(void 0, defaultValue), payload) }) : _getWatch(name, defaultValue, true);
2231
+ const _subscribe = (props) => _subjects.state.subscribe({ next: (formState) => {
2232
+ if (shouldSubscribeByName(props.name, formState.name, props.exact) && shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) props.callback({
2233
+ values: { ..._formValues },
2234
+ ..._formState,
2235
+ ...formState,
2236
+ defaultValues: _defaultValues
2237
+ });
2238
+ } }).unsubscribe;
2239
+ const subscribe = (props) => {
2240
+ _state.mount = true;
2241
+ _proxySubscribeFormState = {
2242
+ ..._proxySubscribeFormState,
2243
+ ...props.formState
2244
+ };
2245
+ return _subscribe({
2246
+ ...props,
2247
+ formState: {
2248
+ ...defaultProxyFormState,
2249
+ ...props.formState
2250
+ }
2251
+ });
2252
+ };
2253
+ const unregister = (name, options = {}) => {
2254
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
2255
+ _names.mount.delete(fieldName);
2256
+ _names.array.delete(fieldName);
2257
+ if (!options.keepValue) {
2258
+ unset(_fields, fieldName);
2259
+ unset(_formValues, fieldName);
2260
+ }
2261
+ !options.keepError && unset(_formState.errors, fieldName);
2262
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
2263
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
2264
+ !options.keepIsValidating && unset(_formState.validatingFields, fieldName);
2265
+ !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
2266
+ }
2267
+ _subjects.state.next({ values: cloneObject(_formValues) });
2268
+ _subjects.state.next({
2269
+ ..._formState,
2270
+ ...!options.keepDirty ? {} : { isDirty: _getDirty() }
2271
+ });
2272
+ !options.keepIsValid && _setValid();
2273
+ };
2274
+ const _setDisabledField = ({ disabled, name }) => {
2275
+ if (isBoolean(disabled) && _state.mount || !!disabled || _names.disabled.has(name)) {
2276
+ const disabledStateChanged = _names.disabled.has(name) !== !!disabled;
2277
+ disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
2278
+ disabledStateChanged && _state.mount && !_state.action && _setValid();
2279
+ }
2280
+ };
2281
+ const register = (name, options = {}) => {
2282
+ let field = get(_fields, name);
2283
+ const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
2284
+ set(_fields, name, {
2285
+ ...field || {},
2286
+ _f: {
2287
+ ...field && field._f ? field._f : { ref: { name } },
2288
+ name,
2289
+ mount: true,
2290
+ ...options
2291
+ }
2292
+ });
2293
+ _names.mount.add(name);
2294
+ if (field) _setDisabledField({
2295
+ disabled: isBoolean(options.disabled) ? options.disabled : _options.disabled,
2296
+ name
2297
+ });
2298
+ else updateValidAndValue(name, true, options.value);
2299
+ return {
2300
+ ...disabledIsDefined ? { disabled: options.disabled || _options.disabled } : {},
2301
+ ..._options.progressive ? {
2302
+ required: !!options.required,
2303
+ min: getRuleValue(options.min),
2304
+ max: getRuleValue(options.max),
2305
+ minLength: getRuleValue(options.minLength),
2306
+ maxLength: getRuleValue(options.maxLength),
2307
+ pattern: getRuleValue(options.pattern)
2308
+ } : {},
2309
+ name,
2310
+ onChange,
2311
+ onBlur: onChange,
2312
+ ref: (ref) => {
2313
+ if (ref) {
2314
+ register(name, options);
2315
+ field = get(_fields, name);
2316
+ const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
2317
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
2318
+ const refs = field._f.refs || [];
2319
+ if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) return;
2320
+ set(_fields, name, { _f: {
2321
+ ...field._f,
2322
+ ...radioOrCheckbox ? {
2323
+ refs: [
2324
+ ...refs.filter(live),
2325
+ fieldRef,
2326
+ ...Array.isArray(get(_defaultValues, name)) ? [{}] : []
2327
+ ],
2328
+ ref: {
2329
+ type: fieldRef.type,
2330
+ name
2331
+ }
2332
+ } : { ref: fieldRef }
2333
+ } });
2334
+ updateValidAndValue(name, false, void 0, fieldRef);
2335
+ } else {
2336
+ field = get(_fields, name, {});
2337
+ if (field._f) field._f.mount = false;
2338
+ (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
2339
+ }
2340
+ }
2341
+ };
2342
+ };
2343
+ const _focusError = () => _options.shouldFocusError && iterateFieldsByAction(_fields, _focusInput, _names.mount);
2344
+ const _disableForm = (disabled) => {
2345
+ if (isBoolean(disabled)) {
2346
+ _subjects.state.next({ disabled });
2347
+ iterateFieldsByAction(_fields, (ref, name) => {
2348
+ const currentField = get(_fields, name);
2349
+ if (currentField) {
2350
+ ref.disabled = currentField._f.disabled || disabled;
2351
+ if (Array.isArray(currentField._f.refs)) currentField._f.refs.forEach((inputRef) => {
2352
+ inputRef.disabled = currentField._f.disabled || disabled;
2353
+ });
2354
+ }
2355
+ }, 0, false);
2356
+ }
2357
+ };
2358
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
2359
+ let onValidError = void 0;
2360
+ if (e) {
2361
+ e.preventDefault && e.preventDefault();
2362
+ e.persist && e.persist();
2363
+ }
2364
+ let fieldValues = cloneObject(_formValues);
2365
+ _subjects.state.next({ isSubmitting: true });
2366
+ if (_options.resolver) {
2367
+ const { errors, values } = await _runSchema();
2368
+ _updateIsValidating();
2369
+ _formState.errors = errors;
2370
+ fieldValues = cloneObject(values);
2371
+ } else await executeBuiltInValidation(_fields);
2372
+ if (_names.disabled.size) for (const name of _names.disabled) unset(fieldValues, name);
2373
+ unset(_formState.errors, "root");
2374
+ if (isEmptyObject(_formState.errors)) {
2375
+ _subjects.state.next({ errors: {} });
2376
+ try {
2377
+ await onValid(fieldValues, e);
2378
+ } catch (error) {
2379
+ onValidError = error;
2380
+ }
2381
+ } else {
2382
+ if (onInvalid) await onInvalid({ ..._formState.errors }, e);
2383
+ _focusError();
2384
+ setTimeout(_focusError);
2385
+ }
2386
+ _subjects.state.next({
2387
+ isSubmitted: true,
2388
+ isSubmitting: false,
2389
+ isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
2390
+ submitCount: _formState.submitCount + 1,
2391
+ errors: _formState.errors
2392
+ });
2393
+ if (onValidError) throw onValidError;
2394
+ };
2395
+ const resetField = (name, options = {}) => {
2396
+ if (get(_fields, name)) {
2397
+ if (isUndefined(options.defaultValue)) setValue(name, cloneObject(get(_defaultValues, name)));
2398
+ else {
2399
+ setValue(name, options.defaultValue);
2400
+ set(_defaultValues, name, cloneObject(options.defaultValue));
2401
+ }
2402
+ if (!options.keepTouched) unset(_formState.touchedFields, name);
2403
+ if (!options.keepDirty) {
2404
+ unset(_formState.dirtyFields, name);
2405
+ _formState.isDirty = options.defaultValue ? _getDirty(name, cloneObject(get(_defaultValues, name))) : _getDirty();
2406
+ }
2407
+ if (!options.keepError) {
2408
+ unset(_formState.errors, name);
2409
+ _proxyFormState.isValid && _setValid();
2410
+ }
2411
+ _subjects.state.next({ ..._formState });
2412
+ }
2413
+ };
2414
+ const _reset = (formValues, keepStateOptions = {}) => {
2415
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2416
+ const cloneUpdatedValues = cloneObject(updatedValues);
2417
+ const isEmptyResetValues = isEmptyObject(formValues);
2418
+ const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
2419
+ if (!keepStateOptions.keepDefaultValues) _defaultValues = updatedValues;
2420
+ if (!keepStateOptions.keepValues) {
2421
+ if (keepStateOptions.keepDirtyValues) {
2422
+ const fieldsToCheck = /* @__PURE__ */ new Set([..._names.mount, ...Object.keys(getDirtyFields(_defaultValues, _formValues))]);
2423
+ for (const fieldName of Array.from(fieldsToCheck)) {
2424
+ const isDirty = get(_formState.dirtyFields, fieldName);
2425
+ const existingValue = get(_formValues, fieldName);
2426
+ const newValue = get(values, fieldName);
2427
+ if (isDirty && !isUndefined(existingValue)) set(values, fieldName, existingValue);
2428
+ else if (!isDirty && !isUndefined(newValue)) setValue(fieldName, newValue);
2429
+ }
2430
+ } else {
2431
+ if (isWeb && isUndefined(formValues)) for (const name of _names.mount) {
2432
+ const field = get(_fields, name);
2433
+ if (field && field._f) {
2434
+ const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
2435
+ if (isHTMLElement(fieldReference)) {
2436
+ const form = fieldReference.closest("form");
2437
+ if (form) {
2438
+ form.reset();
2439
+ break;
2440
+ }
2441
+ }
2442
+ }
2443
+ }
2444
+ if (keepStateOptions.keepFieldsRef) for (const fieldName of _names.mount) setValue(fieldName, get(values, fieldName));
2445
+ else _fields = {};
2446
+ }
2447
+ _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneObject(values);
2448
+ _subjects.array.next({ values: { ...values } });
2449
+ _subjects.state.next({ values: { ...values } });
2450
+ }
2451
+ _names = {
2452
+ mount: keepStateOptions.keepDirtyValues ? _names.mount : /* @__PURE__ */ new Set(),
2453
+ unMount: /* @__PURE__ */ new Set(),
2454
+ array: /* @__PURE__ */ new Set(),
2455
+ disabled: /* @__PURE__ */ new Set(),
2456
+ watch: /* @__PURE__ */ new Set(),
2457
+ watchAll: false,
2458
+ focus: ""
2459
+ };
2460
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid || !!keepStateOptions.keepDirtyValues || !_options.shouldUnregister && !isEmptyObject(values);
2461
+ _state.watch = !!_options.shouldUnregister;
2462
+ _state.keepIsValid = !!keepStateOptions.keepIsValid;
2463
+ _state.action = false;
2464
+ if (!keepStateOptions.keepErrors) _formState.errors = {};
2465
+ _subjects.state.next({
2466
+ submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
2467
+ isDirty: isEmptyResetValues ? false : keepStateOptions.keepDirty ? _formState.isDirty : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
2468
+ isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
2469
+ dirtyFields: isEmptyResetValues ? {} : keepStateOptions.keepDirtyValues ? keepStateOptions.keepDefaultValues && _formValues ? getDirtyFields(_defaultValues, _formValues) : _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : keepStateOptions.keepDirty ? _formState.dirtyFields : {},
2470
+ touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
2471
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2472
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
2473
+ isSubmitting: false,
2474
+ defaultValues: _defaultValues
2475
+ });
2476
+ };
2477
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, {
2478
+ ..._options.resetOptions,
2479
+ ...keepStateOptions
2480
+ });
2481
+ const setFocus = (name, options = {}) => {
2482
+ const field = get(_fields, name);
2483
+ const fieldReference = field && field._f;
2484
+ if (fieldReference) {
2485
+ const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
2486
+ if (fieldRef.focus) setTimeout(() => {
2487
+ fieldRef.focus();
2488
+ options.shouldSelect && isFunction(fieldRef.select) && fieldRef.select();
2489
+ });
2490
+ }
2491
+ };
2492
+ const _setFormState = (updatedFormState) => {
2493
+ _formState = {
2494
+ ..._formState,
2495
+ ...updatedFormState
2496
+ };
2497
+ };
2498
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
2499
+ reset(values, _options.resetOptions);
2500
+ _subjects.state.next({ isLoading: false });
2501
+ });
2502
+ const methods = {
2503
+ control: {
2504
+ register,
2505
+ unregister,
2506
+ getFieldState,
2507
+ handleSubmit,
2508
+ setError,
2509
+ _subscribe,
2510
+ _runSchema,
2511
+ _updateIsValidating,
2512
+ _focusError,
2513
+ _getWatch,
2514
+ _getDirty,
2515
+ _setValid,
2516
+ _setFieldArray,
2517
+ _setDisabledField,
2518
+ _setErrors,
2519
+ _getFieldArray,
2520
+ _reset,
2521
+ _resetDefaultValues,
2522
+ _removeUnmounted,
2523
+ _disableForm,
2524
+ _subjects,
2525
+ _proxyFormState,
2526
+ get _fields() {
2527
+ return _fields;
2528
+ },
2529
+ get _formValues() {
2530
+ return _formValues;
2531
+ },
2532
+ get _state() {
2533
+ return _state;
2534
+ },
2535
+ set _state(value) {
2536
+ _state = value;
2537
+ },
2538
+ get _defaultValues() {
2539
+ return _defaultValues;
2540
+ },
2541
+ get _names() {
2542
+ return _names;
2543
+ },
2544
+ set _names(value) {
2545
+ _names = value;
2546
+ },
2547
+ get _formState() {
2548
+ return _formState;
2549
+ },
2550
+ get _options() {
2551
+ return _options;
2552
+ },
2553
+ set _options(value) {
2554
+ _options = {
2555
+ ..._options,
2556
+ ...value
2557
+ };
2558
+ }
2559
+ },
2560
+ subscribe,
2561
+ trigger,
2562
+ register,
2563
+ handleSubmit,
2564
+ watch,
2565
+ setValue,
2566
+ getValues,
2567
+ reset,
2568
+ resetField,
2569
+ clearErrors,
2570
+ unregister,
2571
+ setError,
2572
+ setFocus,
2573
+ getFieldState
2574
+ };
2575
+ return {
2576
+ ...methods,
2577
+ formControl: methods
2578
+ };
2579
+ }
2580
+ /**
2581
+ * Custom hook to manage the entire form.
2582
+ *
2583
+ * @remarks
2584
+ * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2585
+ *
2586
+ * @param props - form configuration and validation parameters.
2587
+ *
2588
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2589
+ *
2590
+ * @example
2591
+ * ```tsx
2592
+ * function App() {
2593
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2594
+ * const onSubmit = data => console.log(data);
2595
+ *
2596
+ * console.log(watch("example"));
2597
+ *
2598
+ * return (
2599
+ * <form onSubmit={handleSubmit(onSubmit)}>
2600
+ * <input defaultValue="test" {...register("example")} />
2601
+ * <input {...register("exampleRequired", { required: true })} />
2602
+ * {errors.exampleRequired && <span>This field is required</span>}
2603
+ * <button>Submit</button>
2604
+ * </form>
2605
+ * );
2606
+ * }
2607
+ * ```
2608
+ */
2609
+ function useForm(props = {}) {
2610
+ const _formControl = React.useRef(void 0);
2611
+ const _values = React.useRef(void 0);
2612
+ const [formState, updateFormState] = React.useState({
2613
+ isDirty: false,
2614
+ isValidating: false,
2615
+ isLoading: isFunction(props.defaultValues),
2616
+ isSubmitted: false,
2617
+ isSubmitting: false,
2618
+ isSubmitSuccessful: false,
2619
+ isValid: false,
2620
+ submitCount: 0,
2621
+ dirtyFields: {},
2622
+ touchedFields: {},
2623
+ validatingFields: {},
2624
+ errors: props.errors || {},
2625
+ disabled: props.disabled || false,
2626
+ isReady: false,
2627
+ defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
2628
+ });
2629
+ if (!_formControl.current) {
2630
+ if (props.formControl) {
2631
+ _formControl.current = {
2632
+ ...props.formControl,
2633
+ formState
2634
+ };
2635
+ if (props.defaultValues && !isFunction(props.defaultValues)) props.formControl.reset(props.defaultValues, props.resetOptions);
2636
+ } else {
2637
+ const { formControl, ...rest } = createFormControl(props);
2638
+ _formControl.current = {
2639
+ ...rest,
2640
+ formState
2641
+ };
2642
+ }
2643
+ }
2644
+ const control = _formControl.current.control;
2645
+ control._options = props;
2646
+ useIsomorphicLayoutEffect(() => {
2647
+ const sub = control._subscribe({
2648
+ formState: control._proxyFormState,
2649
+ callback: () => updateFormState({ ...control._formState }),
2650
+ reRenderRoot: true
2651
+ });
2652
+ updateFormState((data) => ({
2653
+ ...data,
2654
+ isReady: true
2655
+ }));
2656
+ control._formState.isReady = true;
2657
+ return sub;
2658
+ }, [control]);
2659
+ React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
2660
+ React.useEffect(() => {
2661
+ if (props.mode) control._options.mode = props.mode;
2662
+ if (props.reValidateMode) control._options.reValidateMode = props.reValidateMode;
2663
+ }, [
2664
+ control,
2665
+ props.mode,
2666
+ props.reValidateMode
2667
+ ]);
2668
+ React.useEffect(() => {
2669
+ if (props.errors) {
2670
+ control._setErrors(props.errors);
2671
+ control._focusError();
2672
+ }
2673
+ }, [control, props.errors]);
2674
+ React.useEffect(() => {
2675
+ props.shouldUnregister && control._subjects.state.next({ values: control._getWatch() });
2676
+ }, [control, props.shouldUnregister]);
2677
+ React.useEffect(() => {
2678
+ if (control._proxyFormState.isDirty) {
2679
+ const isDirty = control._getDirty();
2680
+ if (isDirty !== formState.isDirty) control._subjects.state.next({ isDirty });
2681
+ }
2682
+ }, [control, formState.isDirty]);
2683
+ React.useEffect(() => {
2684
+ var _a;
2685
+ if (props.values && !deepEqual(props.values, _values.current)) {
2686
+ control._reset(props.values, {
2687
+ keepFieldsRef: true,
2688
+ ...control._options.resetOptions
2689
+ });
2690
+ if (!((_a = control._options.resetOptions) === null || _a === void 0 ? void 0 : _a.keepIsValid)) control._setValid();
2691
+ _values.current = props.values;
2692
+ updateFormState((state) => ({ ...state }));
2693
+ } else control._resetDefaultValues();
2694
+ }, [control, props.values]);
2695
+ React.useEffect(() => {
2696
+ if (!control._state.mount) {
2697
+ control._setValid();
2698
+ control._state.mount = true;
2699
+ }
2700
+ if (control._state.watch) {
2701
+ control._state.watch = false;
2702
+ control._subjects.state.next({ ...control._formState });
2703
+ }
2704
+ control._removeUnmounted();
2705
+ });
2706
+ _formControl.current.formState = React.useMemo(() => getProxyFormState(formState, control), [control, formState]);
2707
+ return _formControl.current;
2708
+ }
2709
+ //#endregion
2710
+ //#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/dist/resolvers.mjs
2711
+ const r$1 = (t, r, o) => {
2712
+ if (t && "reportValidity" in t) {
2713
+ const s = get(o, r);
2714
+ t.setCustomValidity(s && s.message || ""), t.reportValidity();
2715
+ }
2716
+ };
2717
+ const o = (e, t) => {
2718
+ for (const o in t.fields) {
2719
+ const s = t.fields[o];
2720
+ s && s.ref && "reportValidity" in s.ref ? r$1(s.ref, o, e) : s && s.refs && s.refs.forEach((t) => r$1(t, o, e));
2721
+ }
2722
+ };
2723
+ const s$1 = (r, s) => {
2724
+ s.shouldUseNativeValidation && o(r, s);
2725
+ const n = {};
2726
+ for (const o in r) {
2727
+ const f = get(s.fields, o), c = Object.assign(r[o] || {}, { ref: f && f.ref });
2728
+ if (i$1(s.names || Object.keys(r), o)) {
2729
+ const r = Object.assign({}, get(n, o));
2730
+ set(r, "root", c), set(n, o, r);
2731
+ } else set(n, o, c);
2732
+ }
2733
+ return n;
2734
+ };
2735
+ const i$1 = (e, t) => {
2736
+ const r = n$1(t);
2737
+ return e.some((e) => n$1(e).match(`^${r}\\.\\d+`));
2738
+ };
2739
+ function n$1(e) {
2740
+ return e.replace(/\]|\[/g, "");
2741
+ }
2742
+ //#endregion
2743
+ //#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/zod/dist/zod.mjs
2744
+ function t(r, e) {
2745
+ try {
2746
+ var o = r();
2747
+ } catch (r) {
2748
+ return e(r);
2749
+ }
2750
+ return o && o.then ? o.then(void 0, e) : o;
2751
+ }
2752
+ function s(r, e) {
2753
+ for (var n = {}; r.length;) {
2754
+ var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
2755
+ if (!n[a]) if ("unionErrors" in t) {
2756
+ var u = t.unionErrors[0].errors[0];
2757
+ n[a] = {
2758
+ message: u.message,
2759
+ type: u.code
2760
+ };
2761
+ } else n[a] = {
2762
+ message: i,
2763
+ type: s
2764
+ };
2765
+ if ("unionErrors" in t && t.unionErrors.forEach(function(e) {
2766
+ return e.errors.forEach(function(e) {
2767
+ return r.push(e);
2768
+ });
2769
+ }), e) {
2770
+ var c = n[a].types, f = c && c[t.code];
2771
+ n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
2772
+ }
2773
+ r.shift();
2774
+ }
2775
+ return n;
2776
+ }
2777
+ function i(r, e) {
2778
+ for (var n = {}; r.length;) {
2779
+ var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
2780
+ if (!n[a]) if ("invalid_union" === t.code && t.errors.length > 0) {
2781
+ var u = t.errors[0][0];
2782
+ n[a] = {
2783
+ message: u.message,
2784
+ type: u.code
2785
+ };
2786
+ } else n[a] = {
2787
+ message: i,
2788
+ type: s
2789
+ };
2790
+ if ("invalid_union" === t.code && t.errors.forEach(function(e) {
2791
+ return e.forEach(function(e) {
2792
+ return r.push(e);
2793
+ });
2794
+ }), e) {
2795
+ var c = n[a].types, f = c && c[t.code];
2796
+ n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
2797
+ }
2798
+ r.shift();
2799
+ }
2800
+ return n;
2801
+ }
2802
+ function a(o$1, a, u) {
2803
+ if (void 0 === u && (u = {}), function(r) {
2804
+ return "_def" in r && "object" == typeof r._def && "typeName" in r._def;
2805
+ }(o$1)) return function(n, i, c) {
2806
+ try {
2807
+ return Promise.resolve(t(function() {
2808
+ return Promise.resolve(o$1["sync" === u.mode ? "parse" : "parseAsync"](n, a)).then(function(e) {
2809
+ return c.shouldUseNativeValidation && o({}, c), {
2810
+ errors: {},
2811
+ values: u.raw ? Object.assign({}, n) : e
2812
+ };
2813
+ });
2814
+ }, function(r) {
2815
+ if (function(r) {
2816
+ return Array.isArray(null == r ? void 0 : r.issues);
2817
+ }(r)) return {
2818
+ values: {},
2819
+ errors: s$1(s(r.errors, !c.shouldUseNativeValidation && "all" === c.criteriaMode), c)
2820
+ };
2821
+ throw r;
2822
+ }));
2823
+ } catch (r) {
2824
+ return Promise.reject(r);
2825
+ }
2826
+ };
2827
+ if (function(r) {
2828
+ return "_zod" in r && "object" == typeof r._zod;
2829
+ }(o$1)) return function(s, c, f) {
2830
+ try {
2831
+ return Promise.resolve(t(function() {
2832
+ return Promise.resolve(("sync" === u.mode ? n.parse : n.parseAsync)(o$1, s, a)).then(function(e) {
2833
+ return f.shouldUseNativeValidation && o({}, f), {
2834
+ errors: {},
2835
+ values: u.raw ? Object.assign({}, s) : e
2836
+ };
2837
+ });
2838
+ }, function(r) {
2839
+ if (function(r) {
2840
+ return r instanceof n.$ZodError;
2841
+ }(r)) return {
2842
+ values: {},
2843
+ errors: s$1(i(r.issues, !f.shouldUseNativeValidation && "all" === f.criteriaMode), f)
2844
+ };
2845
+ throw r;
2846
+ }));
2847
+ } catch (r) {
2848
+ return Promise.reject(r);
2849
+ }
2850
+ };
2851
+ throw new Error("Invalid input: not a Zod schema");
2852
+ }
2853
+ //#endregion
2854
+ //#region editors/document-model-editor/schemas/inputs.ts
2855
+ const isUppercase = (value) => !/\p{Ll}/u.test(value);
2856
+ const isLowercase = (value) => !/\p{Lu}/u.test(value);
2857
+ function createNameSchema(options = {}) {
2858
+ const { required = false, allowEmpty = false, unique = [] } = options;
2859
+ const baseSchema = allowEmpty ? z.string() : z.string().min(1);
2860
+ const uniqueRefinement = baseSchema.refine((value) => {
2861
+ if (!value && allowEmpty) return true;
2862
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
2863
+ }, { message: "Item with this name already exists" });
2864
+ if (!required) return unique.length > 0 ? z.string().optional().refine((value) => {
2865
+ if (value === void 0) return true;
2866
+ if (!value && allowEmpty) return true;
2867
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
2868
+ }, { message: "Item with this name already exists" }) : z.string().optional();
2869
+ return unique.length > 0 ? uniqueRefinement : baseSchema;
2870
+ }
2871
+ function createConstantCaseSchema(options = {}) {
2872
+ return createNameSchema(options).transform((value) => value ? value.toUpperCase() : value).refine((value) => !value || isUppercase(value), { message: "Must be uppercase" });
2873
+ }
2874
+ function createLowercaseSnakeCaseSchema(options = {}) {
2875
+ return createNameSchema(options).transform((value) => value ? value.toLowerCase() : value).refine((value) => !value || isLowercase(value), { message: "Must be lowercase" });
2876
+ }
2877
+ function toLowercaseSnakeCase(value, options = {}) {
2878
+ return createLowercaseSnakeCaseSchema(options).parse(snakeCase(value));
2879
+ }
2880
+ function toConstantCase(value, options = {}) {
2881
+ return createConstantCaseSchema(options).parse(constantCase(value));
2882
+ }
2883
+ z.object({
2884
+ name: createNameSchema({ allowEmpty: true }),
2885
+ website: z.union([z.url(), z.literal("")]).optional().default("")
2886
+ }).default({
2887
+ name: "",
2888
+ website: ""
2889
+ });
2890
+ //#endregion
2891
+ //#region ../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.3_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
2892
+ function setRef(ref, value) {
2893
+ if (typeof ref === "function") return ref(value);
2894
+ else if (ref !== null && ref !== void 0) ref.current = value;
2895
+ }
2896
+ function composeRefs(...refs) {
2897
+ return (node) => {
2898
+ let hasCleanup = false;
2899
+ const cleanups = refs.map((ref) => {
2900
+ const cleanup = setRef(ref, node);
2901
+ if (!hasCleanup && typeof cleanup == "function") hasCleanup = true;
2902
+ return cleanup;
2903
+ });
2904
+ if (hasCleanup) return () => {
2905
+ for (let i = 0; i < cleanups.length; i++) {
2906
+ const cleanup = cleanups[i];
2907
+ if (typeof cleanup == "function") cleanup();
2908
+ else setRef(refs[i], null);
2909
+ }
2910
+ };
2911
+ };
2912
+ }
2913
+ function useComposedRefs(...refs) {
2914
+ return React$1.useCallback(composeRefs(...refs), refs);
2915
+ }
2916
+ //#endregion
2917
+ //#region ../../node_modules/.pnpm/@radix-ui+react-slot@1.3.0_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-slot/dist/index.mjs
2918
+ // @__NO_SIDE_EFFECTS__
2919
+ function createSlot$1(ownerName) {
2920
+ const Slot2 = React$1.forwardRef((props, forwardedRef) => {
2921
+ let { children, ...slotProps } = props;
2922
+ let slottableElement = null;
2923
+ let hasSlottable = false;
2924
+ const newChildren = [];
2925
+ if (isLazyComponent$1(children) && typeof use$1 === "function") children = use$1(children._payload);
2926
+ React$1.Children.forEach(children, (maybeSlottable) => {
2927
+ if (isSlottable$1(maybeSlottable)) {
2928
+ hasSlottable = true;
2929
+ const slottable = maybeSlottable;
2930
+ let child = "child" in slottable.props ? slottable.props.child : slottable.props.children;
2931
+ if (isLazyComponent$1(child) && typeof use$1 === "function") child = use$1(child._payload);
2932
+ slottableElement = getSlottableElementFromSlottable(slottable, child);
2933
+ newChildren.push(slottableElement?.props?.children);
2934
+ } else newChildren.push(maybeSlottable);
2935
+ });
2936
+ if (slottableElement) slottableElement = React$1.cloneElement(slottableElement, void 0, newChildren);
2937
+ else if (!hasSlottable && React$1.Children.count(children) === 1 && React$1.isValidElement(children)) slottableElement = children;
2938
+ const slottableElementRef = slottableElement ? getElementRef$1(slottableElement) : void 0;
2939
+ const composedRef = useComposedRefs(forwardedRef, slottableElementRef);
2940
+ if (!slottableElement) {
2941
+ if (children || children === 0) throw new Error(hasSlottable ? createSlottableError(ownerName) : createSlotError(ownerName));
2942
+ return children;
2943
+ }
2944
+ const mergedProps = mergeProps$1(slotProps, slottableElement.props ?? {});
2945
+ if (slottableElement.type !== React$1.Fragment) mergedProps.ref = forwardedRef ? composedRef : slottableElementRef;
2946
+ return React$1.cloneElement(slottableElement, mergedProps);
2947
+ });
2948
+ Slot2.displayName = `${ownerName}.Slot`;
2949
+ return Slot2;
2950
+ }
2951
+ var Slot = /* @__PURE__ */ createSlot$1("Slot");
2952
+ var SLOTTABLE_IDENTIFIER$1 = Symbol.for("radix.slottable");
2953
+ var getSlottableElementFromSlottable = (slottable, child) => {
2954
+ if ("child" in slottable.props) {
2955
+ const child2 = slottable.props.child;
2956
+ if (!React$1.isValidElement(child2)) return null;
2957
+ return React$1.cloneElement(child2, void 0, slottable.props.children(child2.props.children));
2958
+ }
2959
+ return React$1.isValidElement(child) ? child : null;
2960
+ };
2961
+ function mergeProps$1(slotProps, childProps) {
2962
+ const overrideProps = { ...childProps };
2963
+ for (const propName in childProps) {
2964
+ const slotPropValue = slotProps[propName];
2965
+ const childPropValue = childProps[propName];
2966
+ if (/^on[A-Z]/.test(propName)) {
2967
+ if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
2968
+ const result = childPropValue(...args);
2969
+ slotPropValue(...args);
2970
+ return result;
2971
+ };
2972
+ else if (slotPropValue) overrideProps[propName] = slotPropValue;
2973
+ } else if (propName === "style") overrideProps[propName] = {
2974
+ ...slotPropValue,
2975
+ ...childPropValue
2976
+ };
2977
+ else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
2978
+ }
2979
+ return {
2980
+ ...slotProps,
2981
+ ...overrideProps
2982
+ };
2983
+ }
2984
+ function getElementRef$1(element) {
2985
+ let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
2986
+ let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
2987
+ if (mayWarn) return element.ref;
2988
+ getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
2989
+ mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
2990
+ if (mayWarn) return element.props.ref;
2991
+ return element.props.ref || element.ref;
2992
+ }
2993
+ function isSlottable$1(child) {
2994
+ return React$1.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$1;
2995
+ }
2996
+ var REACT_LAZY_TYPE$1 = Symbol.for("react.lazy");
2997
+ function isLazyComponent$1(element) {
2998
+ return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE$1 && "_payload" in element && isPromiseLike$1(element._payload);
2999
+ }
3000
+ function isPromiseLike$1(value) {
3001
+ return typeof value === "object" && value !== null && "then" in value;
3002
+ }
3003
+ var createSlotError = (ownerName) => {
3004
+ return `${ownerName} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`;
3005
+ };
3006
+ var createSlottableError = (ownerName) => {
3007
+ return `${ownerName} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`;
3008
+ };
3009
+ var use$1 = React$1[" use ".trim().toString()];
3010
+ //#endregion
3011
+ //#region editors/document-model-editor/context/form-context.ts
3012
+ const FormFieldContext = React.createContext({});
3013
+ const FormItemContext = React.createContext({});
3014
+ //#endregion
3015
+ //#region editors/document-model-editor/hooks/useFormField.ts
3016
+ const useFormField = () => {
3017
+ const fieldContext = React.useContext(FormFieldContext);
3018
+ const itemContext = React.useContext(FormItemContext);
3019
+ const { getFieldState, formState } = useFormContext();
3020
+ const fieldState = getFieldState(fieldContext.name, formState);
3021
+ if (!fieldContext) throw new Error("useFormField should be used within <FormField>");
3022
+ const { id } = itemContext;
3023
+ return {
3024
+ id,
3025
+ name: fieldContext.name,
3026
+ formItemId: `${id}-form-item`,
3027
+ formDescriptionId: `${id}-form-item-description`,
3028
+ formMessageId: `${id}-form-item-message`,
3029
+ ...fieldState
3030
+ };
3031
+ };
3032
+ //#endregion
3033
+ //#region ../../node_modules/.pnpm/@radix-ui+react-slot@1.2.4_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-slot/dist/index.mjs
3034
+ var REACT_LAZY_TYPE = Symbol.for("react.lazy");
3035
+ var use = React$1[" use ".trim().toString()];
3036
+ function isPromiseLike(value) {
3037
+ return typeof value === "object" && value !== null && "then" in value;
3038
+ }
3039
+ function isLazyComponent(element) {
3040
+ return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE && "_payload" in element && isPromiseLike(element._payload);
3041
+ }
3042
+ // @__NO_SIDE_EFFECTS__
3043
+ function createSlot(ownerName) {
3044
+ const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
3045
+ const Slot2 = React$1.forwardRef((props, forwardedRef) => {
3046
+ let { children, ...slotProps } = props;
3047
+ if (isLazyComponent(children) && typeof use === "function") children = use(children._payload);
3048
+ const childrenArray = React$1.Children.toArray(children);
3049
+ const slottable = childrenArray.find(isSlottable);
3050
+ if (slottable) {
3051
+ const newElement = slottable.props.children;
3052
+ const newChildren = childrenArray.map((child) => {
3053
+ if (child === slottable) {
3054
+ if (React$1.Children.count(newElement) > 1) return React$1.Children.only(null);
3055
+ return React$1.isValidElement(newElement) ? newElement.props.children : null;
3056
+ } else return child;
3057
+ });
3058
+ return /* @__PURE__ */ jsx(SlotClone, {
3059
+ ...slotProps,
3060
+ ref: forwardedRef,
3061
+ children: React$1.isValidElement(newElement) ? React$1.cloneElement(newElement, void 0, newChildren) : null
3062
+ });
3063
+ }
3064
+ return /* @__PURE__ */ jsx(SlotClone, {
3065
+ ...slotProps,
3066
+ ref: forwardedRef,
3067
+ children
3068
+ });
3069
+ });
3070
+ Slot2.displayName = `${ownerName}.Slot`;
3071
+ return Slot2;
3072
+ }
3073
+ // @__NO_SIDE_EFFECTS__
3074
+ function createSlotClone(ownerName) {
3075
+ const SlotClone = React$1.forwardRef((props, forwardedRef) => {
3076
+ let { children, ...slotProps } = props;
3077
+ if (isLazyComponent(children) && typeof use === "function") children = use(children._payload);
3078
+ if (React$1.isValidElement(children)) {
3079
+ const childrenRef = getElementRef(children);
3080
+ const props2 = mergeProps(slotProps, children.props);
3081
+ if (children.type !== React$1.Fragment) props2.ref = forwardedRef ? composeRefs$1(forwardedRef, childrenRef) : childrenRef;
3082
+ return React$1.cloneElement(children, props2);
3083
+ }
3084
+ return React$1.Children.count(children) > 1 ? React$1.Children.only(null) : null;
3085
+ });
3086
+ SlotClone.displayName = `${ownerName}.SlotClone`;
3087
+ return SlotClone;
3088
+ }
3089
+ var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
3090
+ function isSlottable(child) {
3091
+ return React$1.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;
3092
+ }
3093
+ function mergeProps(slotProps, childProps) {
3094
+ const overrideProps = { ...childProps };
3095
+ for (const propName in childProps) {
3096
+ const slotPropValue = slotProps[propName];
3097
+ const childPropValue = childProps[propName];
3098
+ if (/^on[A-Z]/.test(propName)) {
3099
+ if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
3100
+ const result = childPropValue(...args);
3101
+ slotPropValue(...args);
3102
+ return result;
3103
+ };
3104
+ else if (slotPropValue) overrideProps[propName] = slotPropValue;
3105
+ } else if (propName === "style") overrideProps[propName] = {
3106
+ ...slotPropValue,
3107
+ ...childPropValue
3108
+ };
3109
+ else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
3110
+ }
3111
+ return {
3112
+ ...slotProps,
3113
+ ...overrideProps
3114
+ };
3115
+ }
3116
+ function getElementRef(element) {
3117
+ let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
3118
+ let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
3119
+ if (mayWarn) return element.ref;
3120
+ getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
3121
+ mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
3122
+ if (mayWarn) return element.props.ref;
3123
+ return element.props.ref || element.ref;
3124
+ }
3125
+ //#endregion
3126
+ //#region ../../node_modules/.pnpm/@radix-ui+react-primitive@2.1.4_@types+react-dom@19.2.3_@types+react@19.2.14__@types+re_c8c8fd2647f03197dbf56370d7498033/node_modules/@radix-ui/react-primitive/dist/index.mjs
3127
+ var Primitive = [
3128
+ "a",
3129
+ "button",
3130
+ "div",
3131
+ "form",
3132
+ "h2",
3133
+ "h3",
3134
+ "img",
3135
+ "input",
3136
+ "label",
3137
+ "li",
3138
+ "nav",
3139
+ "ol",
3140
+ "p",
3141
+ "select",
3142
+ "span",
3143
+ "svg",
3144
+ "ul"
3145
+ ].reduce((primitive, node) => {
3146
+ const Slot = /* @__PURE__ */ createSlot(`Primitive.${node}`);
3147
+ const Node = React$1.forwardRef((props, forwardedRef) => {
3148
+ const { asChild, ...primitiveProps } = props;
3149
+ const Comp = asChild ? Slot : node;
3150
+ if (typeof window !== "undefined") window[Symbol.for("radix-ui")] = true;
3151
+ return /* @__PURE__ */ jsx(Comp, {
3152
+ ...primitiveProps,
3153
+ ref: forwardedRef
3154
+ });
3155
+ });
3156
+ Node.displayName = `Primitive.${node}`;
3157
+ return {
3158
+ ...primitive,
3159
+ [node]: Node
3160
+ };
3161
+ }, {});
3162
+ //#endregion
3163
+ //#region ../../node_modules/.pnpm/@radix-ui+react-label@2.1.8_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react@_8d35ec453e0b59eefe06771bb1432577/node_modules/@radix-ui/react-label/dist/index.mjs
3164
+ var NAME = "Label";
3165
+ var Label$1 = React$1.forwardRef((props, forwardedRef) => {
3166
+ return /* @__PURE__ */ jsx(Primitive.label, {
3167
+ ...props,
3168
+ ref: forwardedRef,
3169
+ onMouseDown: (event) => {
3170
+ if (event.target.closest("button, input, select, textarea")) return;
3171
+ props.onMouseDown?.(event);
3172
+ if (!event.defaultPrevented && event.detail > 1) event.preventDefault();
3173
+ }
3174
+ });
3175
+ });
3176
+ Label$1.displayName = NAME;
3177
+ var Root = Label$1;
3178
+ //#endregion
3179
+ //#region ../../node_modules/.pnpm/clsx@2.0.0/node_modules/clsx/dist/clsx.mjs
3180
+ function r(e) {
3181
+ var t, f, n = "";
3182
+ if ("string" == typeof e || "number" == typeof e) n += e;
3183
+ else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
3184
+ else for (t in e) e[t] && (n && (n += " "), n += t);
3185
+ return n;
3186
+ }
3187
+ function clsx() {
3188
+ for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t);
3189
+ return n;
3190
+ }
3191
+ //#endregion
3192
+ //#region ../../node_modules/.pnpm/class-variance-authority@0.7.0/node_modules/class-variance-authority/dist/index.mjs
3193
+ const falsyToString = (value) => typeof value === "boolean" ? "".concat(value) : value === 0 ? "0" : value;
3194
+ const cx = clsx;
3195
+ const cva = (base, config) => {
3196
+ return (props) => {
3197
+ var ref;
3198
+ if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
3199
+ const { variants, defaultVariants } = config;
3200
+ const getVariantClassNames = Object.keys(variants).map((variant) => {
3201
+ const variantProp = props === null || props === void 0 ? void 0 : props[variant];
3202
+ const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
3203
+ if (variantProp === null) return null;
3204
+ const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
3205
+ return variants[variant][variantKey];
3206
+ });
3207
+ const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => {
3208
+ let [key, value] = param;
3209
+ if (value === void 0) return acc;
3210
+ acc[key] = value;
3211
+ return acc;
3212
+ }, {});
3213
+ const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (ref = config.compoundVariants) === null || ref === void 0 ? void 0 : ref.reduce((acc, param1) => {
3214
+ let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param1;
3215
+ return Object.entries(compoundVariantOptions).every((param) => {
3216
+ let [key, value] = param;
3217
+ return Array.isArray(value) ? value.includes({
3218
+ ...defaultVariants,
3219
+ ...propsWithoutUndefined
3220
+ }[key]) : {
3221
+ ...defaultVariants,
3222
+ ...propsWithoutUndefined
3223
+ }[key] === value;
3224
+ }) ? [
3225
+ ...acc,
3226
+ cvClass,
3227
+ cvClassName
3228
+ ] : acc;
3229
+ }, []);
3230
+ return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
3231
+ };
3232
+ };
3233
+ //#endregion
3234
+ //#region editors/document-model-editor/components/label.tsx
3235
+ const labelVariants = cva("text-sm leading-none font-medium peer-disabled:disabled-effect");
3236
+ const Label = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Root, {
3237
+ ref,
3238
+ className: twMerge(labelVariants(), className),
3239
+ ...props
3240
+ }));
3241
+ Label.displayName = Root.displayName;
3242
+ //#endregion
3243
+ //#region editors/document-model-editor/components/form.tsx
3244
+ const Form = FormProvider;
3245
+ const FormField = ({ ...props }) => {
3246
+ return /* @__PURE__ */ jsx(FormFieldContext.Provider, {
3247
+ value: { name: props.name },
3248
+ children: /* @__PURE__ */ jsx(Controller, { ...props })
3249
+ });
3250
+ };
3251
+ const FormItem = React$1.forwardRef(({ className, ...props }, ref) => {
3252
+ const id = React$1.useId();
3253
+ return /* @__PURE__ */ jsx(FormItemContext.Provider, {
3254
+ value: { id },
3255
+ children: /* @__PURE__ */ jsx("div", {
3256
+ ref,
3257
+ className,
3258
+ ...props
3259
+ })
3260
+ });
3261
+ });
3262
+ FormItem.displayName = "FormItem";
3263
+ const FormLabel = React$1.forwardRef(({ className, ...props }, ref) => {
3264
+ const { error, formItemId } = useFormField();
3265
+ return /* @__PURE__ */ jsx(Label, {
3266
+ ref,
3267
+ className: twMerge(error && "text-destructive", className),
3268
+ htmlFor: formItemId,
3269
+ ...props
3270
+ });
3271
+ });
3272
+ FormLabel.displayName = "FormLabel";
3273
+ const FormControl = React$1.forwardRef(({ ...props }, ref) => {
3274
+ const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
3275
+ return /* @__PURE__ */ jsx(Slot, {
3276
+ ref,
3277
+ id: formItemId,
3278
+ "aria-describedby": !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`,
3279
+ "aria-invalid": !!error,
3280
+ ...props
3281
+ });
3282
+ });
3283
+ FormControl.displayName = "FormControl";
3284
+ const FormDescription = React$1.forwardRef(({ className, ...props }, ref) => {
3285
+ const { formDescriptionId } = useFormField();
3286
+ return /* @__PURE__ */ jsx("p", {
3287
+ ref,
3288
+ id: formDescriptionId,
3289
+ className: twMerge("text-sm text-foreground", className),
3290
+ ...props
3291
+ });
3292
+ });
3293
+ FormDescription.displayName = "FormDescription";
3294
+ const FormMessage = React$1.forwardRef(({ className, children, ...props }, ref) => {
3295
+ const { error, formMessageId } = useFormField();
3296
+ const body = error ? String(error.message) : children;
3297
+ if (!body) return null;
3298
+ return /* @__PURE__ */ jsx("p", {
3299
+ ref,
3300
+ id: formMessageId,
3301
+ className: twMerge("text-sm font-medium text-destructive", className),
3302
+ ...props,
3303
+ children: body
3304
+ });
3305
+ });
3306
+ FormMessage.displayName = "FormMessage";
3307
+ //#endregion
3308
+ //#region editors/document-model-editor/components/text-area.tsx
3309
+ const Textarea = forwardRef(({ className, ...props }, ref) => {
3310
+ const textareaRef = useRef(null);
3311
+ const adjustHeight = useCallback((textarea) => {
3312
+ textarea.style.height = "auto";
3313
+ const newHeight = Math.max(textarea.scrollHeight, textarea.offsetHeight);
3314
+ textarea.style.height = `${newHeight}px`;
3315
+ }, []);
3316
+ const handleInput = useCallback((e) => {
3317
+ adjustHeight(e.currentTarget);
3318
+ }, [adjustHeight]);
3319
+ React$1.useEffect(() => {
3320
+ if (textareaRef.current) adjustHeight(textareaRef.current);
3321
+ }, [adjustHeight]);
3322
+ useImperativeHandle(ref, () => ({
3323
+ focus: () => textareaRef.current?.focus(),
3324
+ element: textareaRef.current
3325
+ }));
3326
+ return /* @__PURE__ */ jsx("textarea", {
3327
+ ...props,
3328
+ className: twMerge("min-h-10 w-full resize-none rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none disabled:disabled-effect", className),
3329
+ ref: textareaRef,
3330
+ onInput: handleInput
3331
+ });
3332
+ });
3333
+ Textarea.displayName = "Textarea";
3334
+ //#endregion
3335
+ //#region editors/document-model-editor/components/text-field.tsx
3336
+ const TextField = forwardRef(({ name, value, onSubmit, label, placeholder, unique, className = "", rows = 1, focusOnMount = false, required = false, allowEmpty = false, shouldReset = false, onChange }, ref) => {
3337
+ const textareaRef = useRef(null);
3338
+ const id = useId();
3339
+ useEffect(() => {
3340
+ if (focusOnMount && textareaRef.current) textareaRef.current.focus();
3341
+ }, [focusOnMount]);
3342
+ const form = useForm({
3343
+ resolver: a(z.object({ [name]: createNameSchema({
3344
+ required,
3345
+ allowEmpty,
3346
+ unique
3347
+ }) })),
3348
+ defaultValues: { [name]: value ?? "" }
3349
+ });
3350
+ const handleSubmit = useCallback((values) => {
3351
+ const newValue = values[name];
3352
+ if (newValue === void 0 || value === newValue) return;
3353
+ onSubmit(newValue);
3354
+ if (shouldReset) form.reset({ [name]: "" });
3355
+ }, [
3356
+ name,
3357
+ value,
3358
+ onSubmit,
3359
+ form,
3360
+ shouldReset
3361
+ ]);
3362
+ const handleBlur = useCallback(async () => {
3363
+ const currentValue = form.getValues()[name] ?? "";
3364
+ if (value === null || value === void 0) {
3365
+ if (!currentValue || currentValue.trim() === "") return;
3366
+ }
3367
+ if (compareStringsWithoutWhitespace(currentValue, value ?? "")) return;
3368
+ try {
3369
+ await form.trigger();
3370
+ if (form.formState.isValid) await form.handleSubmit(handleSubmit)();
3371
+ } catch (_e) {}
3372
+ }, [
3373
+ form,
3374
+ handleSubmit,
3375
+ name,
3376
+ value
3377
+ ]);
3378
+ const onEnterKeyDown = useCallback((e) => {
3379
+ if (e.key === "Enter") {
3380
+ e.preventDefault();
3381
+ e.target.blur();
3382
+ }
3383
+ }, []);
3384
+ const handleChange = useCallback((e) => {
3385
+ const newValue = e.target.value;
3386
+ onChange?.(newValue);
3387
+ }, [onChange]);
3388
+ useImperativeHandle(ref, () => ({ focus: () => textareaRef.current?.focus() }));
3389
+ useEffect(() => {
3390
+ form.reset({ [name]: value ?? "" });
3391
+ }, [
3392
+ form,
3393
+ name,
3394
+ value
3395
+ ]);
3396
+ return /* @__PURE__ */ jsx(Form, {
3397
+ ...form,
3398
+ children: /* @__PURE__ */ jsx(FormField, {
3399
+ control: form.control,
3400
+ name,
3401
+ render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
3402
+ className: "grid h-full grid-rows-[auto,1fr] gap-2 overflow-visible",
3403
+ children: [
3404
+ !!label && /* @__PURE__ */ jsx(FormLabel, {
3405
+ htmlFor: name,
3406
+ className: "text-sm font-medium text-foreground",
3407
+ children: label
3408
+ }),
3409
+ /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Textarea, {
3410
+ ...field,
3411
+ id,
3412
+ name,
3413
+ ref: (node) => {
3414
+ if (node) {
3415
+ field.ref(node.element);
3416
+ textareaRef.current = node;
3417
+ }
3418
+ },
3419
+ placeholder,
3420
+ onBlur: () => void handleBlur(),
3421
+ onChange: (e) => {
3422
+ field.onChange(e);
3423
+ handleChange(e);
3424
+ },
3425
+ onKeyDown: onEnterKeyDown,
3426
+ rows,
3427
+ className
3428
+ }) }),
3429
+ /* @__PURE__ */ jsx(FormMessage, {})
3430
+ ]
3431
+ })
3432
+ })
3433
+ });
3434
+ });
3435
+ TextField.displayName = "TextField";
3436
+ z.object({
3437
+ name: z.string(),
3438
+ documentType: z.string(),
3439
+ extension: z.string().optional().default(""),
3440
+ description: z.string(),
3441
+ authorName: z.string(),
3442
+ authorWebsite: z.string()
3443
+ });
3444
+ function ModelMetadata(props) {
3445
+ return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(ModelNameForm, { ...props }), /* @__PURE__ */ jsx("div", {
3446
+ className: "flex h-full flex-col gap-4",
3447
+ children: /* @__PURE__ */ jsxs("div", {
3448
+ className: "grid flex-1 grid-cols-3 items-start gap-4",
3449
+ children: [/* @__PURE__ */ jsxs("div", {
3450
+ className: "col-span-2 flex h-full flex-col gap-4",
3451
+ children: [/* @__PURE__ */ jsx("div", {
3452
+ className: "shrink-0",
3453
+ children: /* @__PURE__ */ jsx(DocumentTypeForm, { ...props })
3454
+ }), /* @__PURE__ */ jsx("div", {
3455
+ className: "min-h-0 flex-1",
3456
+ children: /* @__PURE__ */ jsx(DescriptionForm, { ...props })
3457
+ })]
3458
+ }), /* @__PURE__ */ jsxs("div", {
3459
+ className: "col-span-1 flex flex-col gap-4",
3460
+ children: [
3461
+ /* @__PURE__ */ jsx(AuthorNameForm, { ...props }),
3462
+ /* @__PURE__ */ jsx(AuthorWebsiteForm, { ...props }),
3463
+ /* @__PURE__ */ jsx(ModelExtensionForm, { ...props })
3464
+ ]
3465
+ })]
3466
+ })
3467
+ })] });
3468
+ }
3469
+ function ModelNameForm(props) {
3470
+ const { name, globalStateSchema, localStateSchema, setModelName, setStateSchema } = props;
3471
+ const onSubmit = useCallback((newName) => {
3472
+ if (name === newName) return;
3473
+ setModelName(newName);
3474
+ if (!!!globalStateSchema) {
3475
+ const initialSchemaDoc = makeInitialSchemaDoc(newName, "global");
3476
+ setStateSchema(initialSchemaDoc, "global");
3477
+ return;
3478
+ }
3479
+ const newSchema = renameSchemaType(globalStateSchema, name, newName, "global");
3480
+ setStateSchema(newSchema, "global");
3481
+ if (localStateSchema) {
3482
+ const newLocalStateSchema = renameSchemaType(localStateSchema, name, newName, "local");
3483
+ setStateSchema(newLocalStateSchema, "local");
3484
+ }
3485
+ handleModelNameChange({
3486
+ oldName: name,
3487
+ newName,
3488
+ globalStateSchema,
3489
+ localStateSchema,
3490
+ setStateSchema
3491
+ });
3492
+ }, [
3493
+ name,
3494
+ globalStateSchema,
3495
+ localStateSchema,
3496
+ setStateSchema,
3497
+ setModelName
3498
+ ]);
3499
+ return /* @__PURE__ */ jsx(TextField, {
3500
+ name: "name",
3501
+ value: name,
3502
+ onSubmit,
3503
+ placeholder: "Model name",
3504
+ className: "border-none pl-0 text-xl font-bold text-foreground",
3505
+ required: true,
3506
+ focusOnMount: true
3507
+ });
3508
+ }
3509
+ function DocumentTypeForm(props) {
3510
+ const { documentType, setModelId } = props;
3511
+ return /* @__PURE__ */ jsx(TextField, {
3512
+ label: "Document Type *",
3513
+ name: "powerhouse/document-model",
3514
+ value: documentType,
3515
+ onSubmit: setModelId,
3516
+ placeholder: "Document Type",
3517
+ required: true
3518
+ });
3519
+ }
3520
+ function ModelExtensionForm(props) {
3521
+ const { extension, setModelExtension } = props;
3522
+ return /* @__PURE__ */ jsx(TextField, {
3523
+ name: "extension",
3524
+ value: extension,
3525
+ onSubmit: setModelExtension,
3526
+ label: "Model Extension",
3527
+ placeholder: "Example .phdm",
3528
+ allowEmpty: true
3529
+ });
3530
+ }
3531
+ function DescriptionForm(props) {
3532
+ const { description, setModelDescription } = props;
3533
+ return /* @__PURE__ */ jsx(TextField, {
3534
+ name: "description",
3535
+ label: "Model Description",
3536
+ value: description,
3537
+ onSubmit: setModelDescription,
3538
+ placeholder: "Describe your document to others",
3539
+ allowEmpty: true,
3540
+ className: "h-full"
3541
+ });
3542
+ }
3543
+ function AuthorNameForm(props) {
3544
+ const { authorName, setAuthorName } = props;
3545
+ return /* @__PURE__ */ jsx(TextField, {
3546
+ name: "authorName",
3547
+ value: authorName,
3548
+ onSubmit: setAuthorName,
3549
+ label: "Author Name",
3550
+ placeholder: "Username or organisation",
3551
+ allowEmpty: true
3552
+ });
3553
+ }
3554
+ function AuthorWebsiteForm(props) {
3555
+ const { authorWebsite, setAuthorWebsite } = props;
3556
+ return /* @__PURE__ */ jsx(TextField, {
3557
+ name: "authorWebsite",
3558
+ value: authorWebsite,
3559
+ label: "Website URL",
3560
+ onSubmit: (newAuthorWebsite) => {
3561
+ if (!!authorWebsite && !newAuthorWebsite) return;
3562
+ setAuthorWebsite(newAuthorWebsite);
3563
+ },
3564
+ placeholder: "https://www.powerhouse.inc/",
3565
+ allowEmpty: true
3566
+ });
3567
+ }
3568
+ //#endregion
3569
+ //#region editors/document-model-editor/components/module-form.tsx
3570
+ function ModuleForm({ module, onAddModule, updateModuleName, modules = [] }) {
3571
+ const isEdit = !!module;
3572
+ const moduleNames = modules.map((m) => m.name);
3573
+ const handleSubmit = async (name) => {
3574
+ const formattedName = toLowercaseSnakeCase(name);
3575
+ if (!formattedName.length) return;
3576
+ if (isEdit) {
3577
+ if (formattedName !== module.name) updateModuleName(module.id, formattedName);
3578
+ } else await onAddModule(formattedName);
3579
+ };
3580
+ return /* @__PURE__ */ jsx(TextField, {
3581
+ name: "name",
3582
+ label: isEdit ? "Module name *" : "Add module *",
3583
+ value: module?.name,
3584
+ onSubmit: (name) => void handleSubmit(name),
3585
+ placeholder: "Add module",
3586
+ unique: moduleNames,
3587
+ shouldReset: !isEdit,
3588
+ required: true
3589
+ }, module?.id ?? "new");
3590
+ }
3591
+ //#endregion
3592
+ //#region editors/document-model-editor/components/operation-form.tsx
3593
+ function OperationForm({ operation, module, focusOnMount, allOperationNames, onAddOperationAndInitialSchema, updateOperationName, deleteOperation }) {
3594
+ const isEdit = !!operation;
3595
+ const handleSubmit = async (name) => {
3596
+ if (isEdit && name === "") {
3597
+ deleteOperation(operation.id);
3598
+ return;
3599
+ }
3600
+ const formattedName = toConstantCase(name);
3601
+ if (isEdit) {
3602
+ if (formattedName !== operation.name) updateOperationName(operation.id, formattedName);
3603
+ } else await onAddOperationAndInitialSchema(module.id, formattedName);
3604
+ };
3605
+ const handleChange = (value) => {
3606
+ if (isEdit && value === "") deleteOperation(operation.id);
3607
+ };
3608
+ return /* @__PURE__ */ jsx(TextField, {
3609
+ name: "name",
3610
+ value: operation?.name,
3611
+ label: isEdit ? "Operation name *" : "Add operation *",
3612
+ onSubmit: (name) => void handleSubmit(name),
3613
+ onChange: handleChange,
3614
+ placeholder: "Add operation",
3615
+ required: !isEdit,
3616
+ allowEmpty: !isEdit,
3617
+ shouldReset: !isEdit,
3618
+ focusOnMount,
3619
+ unique: allOperationNames
3620
+ });
3621
+ }
3622
+ //#endregion
3623
+ //#region editors/document-model-editor/components/operation-description-form.tsx
3624
+ function OperationDescriptionForm({ operation, focusOnMount, setOperationDescription }) {
3625
+ const textFieldRef = useRef(null);
3626
+ useEffect(() => {
3627
+ if (focusOnMount && textFieldRef.current) textFieldRef.current.focus();
3628
+ }, [focusOnMount]);
3629
+ return /* @__PURE__ */ jsx(TextField, {
3630
+ ref: textFieldRef,
3631
+ name: "description",
3632
+ value: operation.description,
3633
+ onSubmit: (newDescription) => setOperationDescription(operation.id, newDescription),
3634
+ label: "Operation description",
3635
+ allowEmpty: true,
3636
+ placeholder: "Operation Description"
3637
+ });
3638
+ }
3639
+ //#endregion
3640
+ //#region editors/document-model-editor/components/operation-error-form.tsx
3641
+ function OperationErrorForm({ operation, error, focusOnMount, onSubmit, onAddOperationError, deleteOperationError, setOperationErrorName }) {
3642
+ const textFieldRef = useRef(null);
3643
+ const isEdit = !!error;
3644
+ const allOperationErrorNames = operation.errors.map((o) => o.name).filter((n) => n !== null);
3645
+ const handleSubmit = (name) => {
3646
+ if (isEdit && name === "") {
3647
+ deleteOperationError(error.id);
3648
+ return;
3649
+ }
3650
+ const formattedName = pascalCase(name);
3651
+ if (isEdit) setOperationErrorName(operation.id, error.id, formattedName);
3652
+ else onAddOperationError(operation.id, formattedName);
3653
+ onSubmit?.();
3654
+ };
3655
+ const handleChange = (value) => {
3656
+ if (isEdit && value === "") deleteOperationError(error.id);
3657
+ };
3658
+ return /* @__PURE__ */ jsx(TextField, {
3659
+ ref: textFieldRef,
3660
+ name: "name",
3661
+ value: error?.name,
3662
+ onSubmit: handleSubmit,
3663
+ onChange: handleChange,
3664
+ placeholder: "Add exception",
3665
+ required: !isEdit,
3666
+ allowEmpty: !isEdit,
3667
+ shouldReset: !isEdit,
3668
+ unique: allOperationErrorNames,
3669
+ focusOnMount
3670
+ });
3671
+ }
3672
+ //#endregion
3673
+ //#region editors/document-model-editor/components/operation-errors.tsx
3674
+ function OperationErrors({ operation, addOperationError, deleteOperationError, setOperationErrorName }) {
3675
+ const addErrorFormId = useId();
3676
+ const [shouldFocusAddForm, setShouldFocusAddForm] = useState(false);
3677
+ const onAddOperationError = useCallback(async (operationId, error) => {
3678
+ const errorId = await addOperationError(operationId, error);
3679
+ if (errorId) setShouldFocusAddForm(true);
3680
+ return errorId;
3681
+ }, [addOperationError, setShouldFocusAddForm]);
3682
+ const onAddOperationErrorSubmit = useCallback(() => setShouldFocusAddForm(false), [setShouldFocusAddForm]);
3683
+ return /* @__PURE__ */ jsxs("ul", {
3684
+ className: "ml-4 list-disc",
3685
+ children: [operation.errors.map((error) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
3686
+ error,
3687
+ operation,
3688
+ onAddOperationError,
3689
+ deleteOperationError,
3690
+ setOperationErrorName
3691
+ }) }, error.id)), /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
3692
+ operation,
3693
+ onAddOperationError,
3694
+ deleteOperationError,
3695
+ setOperationErrorName,
3696
+ focusOnMount: shouldFocusAddForm,
3697
+ onSubmit: onAddOperationErrorSubmit
3698
+ }, `${addErrorFormId}-${shouldFocusAddForm}`) })]
3699
+ });
3700
+ }
3701
+ //#endregion
3702
+ //#region editors/document-model-editor/components/operation.tsx
3703
+ const GraphqlEditor = lazy(() => import("./graphql-editor-v1OXETjM.mjs"));
3704
+ function Operation(props) {
3705
+ const { operation, module, allOperationNames, lastCreatedOperationId, onAddOperationAndInitialSchema, updateOperationName, deleteOperation, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
3706
+ const noInputRequired = isEmptyOperationSchema(operation.schema);
3707
+ const handleToggleNoInput = useCallback((checked) => toggleNoInputRequired(operation.id, checked), [operation.id, toggleNoInputRequired]);
3708
+ const handleUpdateDocument = useCallback((newDoc) => updateOperationSchema(operation.id, newDoc), [operation.id, updateOperationSchema]);
3709
+ const customLinter = useCallback((doc) => operation.name ? ensureValidOperationSchemaInputName(doc, operation.name) : [], [operation.name]);
3710
+ return /* @__PURE__ */ jsxs("div", {
3711
+ className: "mt-4 grid grid-cols-2 gap-x-12",
3712
+ style: {
3713
+ gridTemplateAreas: `
3714
+ "left editor"
3715
+ "errors editor"
3716
+ `,
3717
+ gridTemplateRows: "auto 1fr"
3718
+ },
3719
+ children: [
3720
+ /* @__PURE__ */ jsxs("div", {
3721
+ className: "flex flex-col gap-2",
3722
+ style: { gridArea: "left" },
3723
+ children: [/* @__PURE__ */ jsx(OperationForm, {
3724
+ operation,
3725
+ onAddOperationAndInitialSchema,
3726
+ updateOperationName,
3727
+ deleteOperation,
3728
+ module,
3729
+ allOperationNames
3730
+ }), /* @__PURE__ */ jsx(OperationDescriptionForm, {
3731
+ operation,
3732
+ focusOnMount: operation.id === lastCreatedOperationId,
3733
+ setOperationDescription
3734
+ })]
3735
+ }),
3736
+ /* @__PURE__ */ jsxs("div", {
3737
+ className: "relative top-8",
3738
+ style: { gridArea: "editor" },
3739
+ children: [/* @__PURE__ */ jsxs("label", {
3740
+ className: "mb-2 flex cursor-pointer items-center gap-2",
3741
+ children: [/* @__PURE__ */ jsx("input", {
3742
+ type: "checkbox",
3743
+ checked: noInputRequired,
3744
+ onChange: (e) => handleToggleNoInput(e.target.checked),
3745
+ className: "size-4 rounded-sm border-border"
3746
+ }), /* @__PURE__ */ jsx("span", {
3747
+ className: "text-sm text-foreground",
3748
+ children: "Operation with no inputs"
3749
+ })]
3750
+ }), !noInputRequired && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(GraphqlEditor, {
3751
+ doc: operation.schema ?? "",
3752
+ updateDocumentInModel: handleUpdateDocument,
3753
+ customLinter
3754
+ }) })]
3755
+ }),
3756
+ /* @__PURE__ */ jsxs("div", {
3757
+ style: { gridArea: "errors" },
3758
+ children: [/* @__PURE__ */ jsx("h3", {
3759
+ className: "my-2 text-sm font-medium text-foreground",
3760
+ children: "Reducer Exceptions"
3761
+ }), /* @__PURE__ */ jsx(OperationErrors, {
3762
+ operation,
3763
+ addOperationError,
3764
+ deleteOperationError,
3765
+ setOperationErrorName
3766
+ })]
3767
+ })
3768
+ ]
3769
+ });
3770
+ }
3771
+ //#endregion
3772
+ //#region editors/document-model-editor/components/operations.tsx
3773
+ function Operations({ module, allOperations, shouldFocusNewOperation, updateOperationName, deleteOperation, addOperationAndInitialSchema, addOperationError, deleteOperationError, setOperationErrorName, updateOperationSchema, setOperationDescription, toggleNoInputRequired }) {
3774
+ const [lastCreatedOperationId, setLastCreatedOperationId] = useState(null);
3775
+ const addOperationFormId = useId();
3776
+ const allOperationNames = allOperations.map((o) => o.name).filter((n) => n !== null);
3777
+ const onAddOperationAndInitialSchema = useCallback(async (moduleId, name) => {
3778
+ const operationId = await addOperationAndInitialSchema(moduleId, name);
3779
+ if (operationId) setLastCreatedOperationId(operationId);
3780
+ return operationId;
3781
+ }, [addOperationAndInitialSchema, setLastCreatedOperationId]);
3782
+ return /* @__PURE__ */ jsxs("div", { children: [module.operations.map((operation) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Operation, {
3783
+ operation,
3784
+ module,
3785
+ lastCreatedOperationId,
3786
+ allOperationNames,
3787
+ addOperationError,
3788
+ deleteOperationError,
3789
+ setOperationErrorName,
3790
+ onAddOperationAndInitialSchema,
3791
+ updateOperationName,
3792
+ deleteOperation,
3793
+ updateOperationSchema,
3794
+ setOperationDescription,
3795
+ toggleNoInputRequired
3796
+ }) }, operation.id)), /* @__PURE__ */ jsx("div", {
3797
+ className: "mt-6 w-1/2 pr-6",
3798
+ children: /* @__PURE__ */ jsx(OperationForm, {
3799
+ onAddOperationAndInitialSchema,
3800
+ updateOperationName,
3801
+ deleteOperation,
3802
+ module,
3803
+ allOperationNames,
3804
+ focusOnMount: shouldFocusNewOperation
3805
+ }, addOperationFormId)
3806
+ })] });
3807
+ }
3808
+ //#endregion
3809
+ //#region editors/document-model-editor/components/module.tsx
3810
+ function Module(props) {
3811
+ const { module, modules, allOperations, lastCreatedModuleId, onAddModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
3812
+ return /* @__PURE__ */ jsxs("div", {
3813
+ className: "relative rounded-3xl bg-muted p-6",
3814
+ children: [/* @__PURE__ */ jsxs("div", {
3815
+ className: "mb-2 w-1/2 pr-6",
3816
+ children: [/* @__PURE__ */ jsx(ModuleForm, {
3817
+ modules,
3818
+ module,
3819
+ onAddModule,
3820
+ updateModuleName
3821
+ }), !!module && /* @__PURE__ */ jsx("button", {
3822
+ "aria-label": "Delete module",
3823
+ tabIndex: -1,
3824
+ className: "absolute top-1 right-1 p-2 text-foreground transition-colors hover:hover-effect",
3825
+ onClick: () => {
3826
+ deleteModule(module.id);
3827
+ },
3828
+ children: /* @__PURE__ */ jsx("svg", {
3829
+ className: "size-6",
3830
+ viewBox: "0 0 24 24",
3831
+ fill: "currentcolor",
3832
+ children: /* @__PURE__ */ jsx("path", {
3833
+ fillRule: "evenodd",
3834
+ clipRule: "evenodd",
3835
+ d: "M16.9993 8.51506L15.4844 7L11.9994 10.4852L8.51497 7.00057L7 8.51562L10.4844 12.0003L7.00056 15.4843L8.51552 16.9994L11.9994 13.5153L15.4838 17L16.9988 15.4849L13.5144 12.0003L16.9993 8.51506Z"
3836
+ })
3837
+ })
3838
+ })]
3839
+ }), !!module && /* @__PURE__ */ jsx(Operations, {
3840
+ module,
3841
+ allOperations,
3842
+ shouldFocusNewOperation: module.id === lastCreatedModuleId,
3843
+ updateOperationName,
3844
+ deleteOperation,
3845
+ addOperationAndInitialSchema,
3846
+ updateOperationSchema,
3847
+ setOperationDescription,
3848
+ addOperationError,
3849
+ deleteOperationError,
3850
+ setOperationErrorName,
3851
+ toggleNoInputRequired
3852
+ })]
3853
+ });
3854
+ }
3855
+ //#endregion
3856
+ //#region editors/document-model-editor/components/modules.tsx
3857
+ function Modules({ modules, allOperations, addModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired }) {
3858
+ const [lastCreatedModuleId, setLastCreatedModuleId] = useState(null);
3859
+ const focusTrapRef = useRef(null);
3860
+ const onAddModule = useCallback(async (name) => {
3861
+ const moduleId = await addModule(name);
3862
+ if (moduleId) {
3863
+ setLastCreatedModuleId(moduleId);
3864
+ focusTrapRef.current?.focus();
3865
+ }
3866
+ return moduleId;
3867
+ }, [addModule, setLastCreatedModuleId]);
3868
+ return /* @__PURE__ */ jsxs("div", {
3869
+ className: "flex flex-col gap-2",
3870
+ children: [
3871
+ modules.map((module) => /* @__PURE__ */ jsx(Module, {
3872
+ module,
3873
+ modules,
3874
+ allOperations,
3875
+ lastCreatedModuleId,
3876
+ onAddModule,
3877
+ updateModuleName,
3878
+ deleteModule,
3879
+ updateOperationName,
3880
+ deleteOperation,
3881
+ addOperationAndInitialSchema,
3882
+ updateOperationSchema,
3883
+ setOperationDescription,
3884
+ addOperationError,
3885
+ deleteOperationError,
3886
+ setOperationErrorName,
3887
+ toggleNoInputRequired
3888
+ }, module.id)),
3889
+ /* @__PURE__ */ jsx(Module, {
3890
+ modules,
3891
+ allOperations,
3892
+ lastCreatedModuleId,
3893
+ onAddModule,
3894
+ updateModuleName,
3895
+ deleteModule,
3896
+ updateOperationName,
3897
+ deleteOperation,
3898
+ addOperationAndInitialSchema,
3899
+ updateOperationSchema,
3900
+ setOperationDescription,
3901
+ addOperationError,
3902
+ deleteOperationError,
3903
+ setOperationErrorName,
3904
+ toggleNoInputRequired
3905
+ }, "add-module"),
3906
+ /* @__PURE__ */ jsx("div", {
3907
+ ref: focusTrapRef,
3908
+ tabIndex: 0,
3909
+ className: "size-0 overflow-hidden",
3910
+ "aria-hidden": "true"
3911
+ })
3912
+ ]
3913
+ });
3914
+ }
3915
+ //#endregion
3916
+ //#region editors/document-model-editor/components/version-controls.tsx
3917
+ const compactButtonStyle$1 = "min-h-0 min-w-0 flex-none rounded-lg px-6 py-1.5 text-sm whitespace-nowrap";
3918
+ function VersionControls(props) {
3919
+ const { specifications, viewedVersion, onViewVersion, onReleaseNewVersion } = props;
3920
+ const [showReleaseModal, setShowReleaseModal] = useState(false);
3921
+ const latestVersion = specifications[specifications.length - 1].version;
3922
+ const nextVersion = latestVersion + 1;
3923
+ return /* @__PURE__ */ jsxs("div", {
3924
+ className: "mb-4 flex items-center justify-between gap-4",
3925
+ children: [
3926
+ /* @__PURE__ */ jsxs("div", {
3927
+ className: "flex items-center gap-2",
3928
+ children: [/* @__PURE__ */ jsxs("span", {
3929
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
3930
+ "data-testid": "model-version-badge",
3931
+ children: ["Version ", viewedVersion]
3932
+ }), specifications.length >= 2 && /* @__PURE__ */ jsx("div", {
3933
+ "aria-label": "Document model version",
3934
+ "data-testid": "model-version-switcher",
3935
+ children: /* @__PURE__ */ jsx(ConnectSelect, {
3936
+ absolutePositionMenu: true,
3937
+ containerClassName: "z-10 [&_svg]:size-4",
3938
+ id: "model-version-switcher",
3939
+ itemClassName: "gap-1 px-2 py-1 font-mono text-xs leading-none [&_p:empty]:hidden",
3940
+ items: specifications.map((spec) => ({
3941
+ value: String(spec.version),
3942
+ displayValue: /* @__PURE__ */ jsx("span", {
3943
+ className: "normal-case",
3944
+ children: spec.version === latestVersion ? `v${spec.version} (latest)` : `v${spec.version} (frozen)`
3945
+ })
3946
+ })),
3947
+ listClassName: "border border-t-0 border-border shadow-md",
3948
+ menuClassName: "min-w-0 pr-1.5",
3949
+ onChange: (value) => {
3950
+ const version = Number(value);
3951
+ onViewVersion(version === latestVersion ? "latest" : version);
3952
+ },
3953
+ value: String(viewedVersion)
3954
+ })
3955
+ })]
3956
+ }),
3957
+ /* @__PURE__ */ jsx(Button, {
3958
+ className: "inline-flex h-8 items-center justify-center py-0",
3959
+ "data-testid": "release-new-version-button",
3960
+ onClick: () => setShowReleaseModal(true),
3961
+ type: "button",
3962
+ children: "Release new version"
3963
+ }),
3964
+ /* @__PURE__ */ jsx(Modal, {
3965
+ open: showReleaseModal,
3966
+ onOpenChange: (status) => {
3967
+ if (!status) setShowReleaseModal(false);
3968
+ },
3969
+ children: /* @__PURE__ */ jsxs("div", {
3970
+ className: "w-[440px] p-6",
3971
+ children: [
3972
+ /* @__PURE__ */ jsxs("div", {
3973
+ className: "pb-2 text-2xl font-bold text-foreground",
3974
+ children: ["Release version ", nextVersion]
3975
+ }),
3976
+ /* @__PURE__ */ jsxs("div", {
3977
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
3978
+ children: [/* @__PURE__ */ jsxs("p", { children: [
3979
+ "Version ",
3980
+ latestVersion,
3981
+ " will be frozen as-is. Version",
3982
+ " ",
3983
+ nextVersion,
3984
+ " starts as an identical copy, and all further edits apply to version ",
3985
+ nextVersion,
3986
+ "."
3987
+ ] }), /* @__PURE__ */ jsxs("p", {
3988
+ className: "mt-3",
3989
+ children: [
3990
+ "Existing version ",
3991
+ latestVersion,
3992
+ " documents will be upgradeable once you define the migration."
3993
+ ]
3994
+ })]
3995
+ }),
3996
+ /* @__PURE__ */ jsxs("div", {
3997
+ className: "mt-4 flex justify-between gap-3",
3998
+ children: [/* @__PURE__ */ jsx(ModalButton, {
3999
+ className: compactButtonStyle$1,
4000
+ onClick: () => setShowReleaseModal(false),
4001
+ variant: "cancel",
4002
+ children: "Cancel"
4003
+ }), /* @__PURE__ */ jsxs(ModalButton, {
4004
+ className: compactButtonStyle$1,
4005
+ "data-testid": "confirm-release-button",
4006
+ onClick: () => {
4007
+ setShowReleaseModal(false);
4008
+ onReleaseNewVersion();
4009
+ },
4010
+ variant: "confirm",
4011
+ children: ["Release version ", nextVersion]
4012
+ })]
4013
+ })
4014
+ ]
4015
+ })
4016
+ })
4017
+ ]
4018
+ });
4019
+ }
4020
+ function FrozenVersionBanner(props) {
4021
+ const { viewedVersion, latestVersion } = props;
4022
+ return /* @__PURE__ */ jsxs("div", {
4023
+ className: "mb-4 rounded-md border border-border bg-muted p-3 text-sm text-foreground",
4024
+ "data-testid": "frozen-version-banner",
4025
+ children: [
4026
+ "Version ",
4027
+ viewedVersion,
4028
+ " is frozen. You're viewing it read-only. Edits go to version ",
4029
+ latestVersion,
4030
+ "."
4031
+ ]
4032
+ });
4033
+ }
4034
+ //#endregion
4035
+ //#region editors/document-model-editor/components/version-advisory-modal.tsx
4036
+ const compactButtonStyle = "min-h-0 min-w-0 flex-none rounded-lg px-4 py-1.5 text-sm whitespace-nowrap";
4037
+ function FieldDiffList(props) {
4038
+ const { label, fields } = props;
4039
+ if (fields.length === 0) return null;
4040
+ return /* @__PURE__ */ jsxs("div", {
4041
+ className: "mt-3",
4042
+ children: [/* @__PURE__ */ jsx("p", {
4043
+ className: "mb-1.5",
4044
+ children: label
4045
+ }), /* @__PURE__ */ jsx("div", {
4046
+ className: "flex flex-col items-start gap-1",
4047
+ children: fields.map((field) => /* @__PURE__ */ jsx("span", {
4048
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
4049
+ children: field
4050
+ }, field))
4051
+ })]
4052
+ });
4053
+ }
4054
+ function VersionAdvisoryModal(props) {
4055
+ const { prompt, onReleaseFirst, onKeepEditing, onCancel } = props;
4056
+ if (!prompt) return null;
4057
+ const { version, reason, diff } = prompt;
4058
+ const nextVersion = version + 1;
4059
+ return /* @__PURE__ */ jsx(Modal, {
4060
+ open: true,
4061
+ onOpenChange: (status) => {
4062
+ if (!status) onCancel();
4063
+ },
4064
+ children: /* @__PURE__ */ jsxs("div", {
4065
+ className: "w-[440px] p-6",
4066
+ "data-testid": "version-advisory-modal",
4067
+ children: [
4068
+ /* @__PURE__ */ jsxs("div", {
4069
+ className: "pb-2 text-2xl font-bold text-foreground",
4070
+ children: [
4071
+ "Is version ",
4072
+ version,
4073
+ " of this model already in use?"
4074
+ ]
4075
+ }),
4076
+ /* @__PURE__ */ jsxs("div", {
4077
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
4078
+ children: [
4079
+ /* @__PURE__ */ jsxs("p", { children: [
4080
+ reason,
4081
+ " Documents that were already created with version ",
4082
+ version,
4083
+ " ",
4084
+ "may stop working correctly."
4085
+ ] }),
4086
+ diff && /* @__PURE__ */ jsxs(Fragment, { children: [
4087
+ /* @__PURE__ */ jsx(FieldDiffList, {
4088
+ fields: diff.addedFields,
4089
+ label: "New fields:"
4090
+ }),
4091
+ /* @__PURE__ */ jsx(FieldDiffList, {
4092
+ fields: diff.removedFields,
4093
+ label: "Removed fields:"
4094
+ }),
4095
+ /* @__PURE__ */ jsx(FieldDiffList, {
4096
+ fields: diff.changedFields,
4097
+ label: "Changed fields:"
4098
+ })
4099
+ ] }),
4100
+ /* @__PURE__ */ jsxs("p", {
4101
+ className: "mt-3",
4102
+ children: [
4103
+ "If others are already using version ",
4104
+ version,
4105
+ ", release version",
4106
+ " ",
4107
+ nextVersion,
4108
+ " first. Your change will go into version ",
4109
+ nextVersion,
4110
+ ", and existing documents can be updated safely."
4111
+ ]
4112
+ })
4113
+ ]
4114
+ }),
4115
+ /* @__PURE__ */ jsxs("div", {
4116
+ className: "mt-4 flex flex-col gap-2",
4117
+ children: [/* @__PURE__ */ jsx(ModalButton, {
4118
+ className: compactButtonStyle,
4119
+ "data-testid": "advisory-release-first",
4120
+ onClick: onReleaseFirst,
4121
+ variant: "confirm",
4122
+ children: `It's in use — release v${nextVersion} first`
4123
+ }), /* @__PURE__ */ jsxs(ModalButton, {
4124
+ className: compactButtonStyle,
4125
+ "data-testid": "advisory-keep-editing",
4126
+ onClick: onKeepEditing,
4127
+ variant: "cancel",
4128
+ children: ["Still in development — keep editing v", version]
4129
+ })]
4130
+ })
4131
+ ]
4132
+ })
4133
+ });
4134
+ }
4135
+ //#endregion
4136
+ //#region editors/document-model-editor/config.ts
4137
+ const editorConfig = { isExternalControlsEnabled: false };
4138
+ //#endregion
4139
+ //#region editors/document-model-editor/utils/change-classification.ts
4140
+ function isShapeTypeNode(node) {
4141
+ return node.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION;
4142
+ }
4143
+ function collectTypeFields(doc) {
4144
+ const types = /* @__PURE__ */ new Map();
4145
+ for (const definition of doc.definitions) {
4146
+ if (!isShapeTypeNode(definition)) continue;
4147
+ const fields = /* @__PURE__ */ new Map();
4148
+ if (definition.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION) for (const value of definition.values ?? []) fields.set(value.name.value, "value");
4149
+ else for (const field of definition.fields ?? []) fields.set(field.name.value, (0, import_graphql.print)(field.type));
4150
+ types.set(definition.name.value, fields);
4151
+ }
4152
+ return types;
4153
+ }
4154
+ function escapeRegExp(value) {
4155
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4156
+ }
4157
+ function replaceTypeName(printedType, oldName, newName) {
4158
+ return printedType.replace(new RegExp(`\\b${escapeRegExp(oldName)}\\b`, "g"), newName);
4159
+ }
4160
+ function typeSignature(name, fields) {
4161
+ return [...fields.entries()].map(([field, type]) => `${field}:${replaceTypeName(type, name, "__SELF__")}`).sort().join("|");
4162
+ }
4163
+ function detectTypeRenames(oldTypes, newTypes) {
4164
+ const renames = /* @__PURE__ */ new Map();
4165
+ const removed = [...oldTypes.keys()].filter((name) => !newTypes.has(name));
4166
+ const added = new Set([...newTypes.keys()].filter((name) => !oldTypes.has(name)));
4167
+ for (const oldName of removed) {
4168
+ const oldSignature = typeSignature(oldName, oldTypes.get(oldName));
4169
+ for (const newName of added) if (typeSignature(newName, newTypes.get(newName)) === oldSignature) {
4170
+ renames.set(oldName, newName);
4171
+ added.delete(newName);
4172
+ break;
4173
+ }
4174
+ }
4175
+ return renames;
4176
+ }
4177
+ function flattenFields(types, renames) {
4178
+ const fields = /* @__PURE__ */ new Map();
4179
+ for (const [typeName, typeFields] of types) {
4180
+ const resolvedTypeName = renames.get(typeName) ?? typeName;
4181
+ for (const [fieldName, printedType] of typeFields) {
4182
+ let resolvedType = printedType;
4183
+ for (const [oldName, newName] of renames) resolvedType = replaceTypeName(resolvedType, oldName, newName);
4184
+ fields.set(`${resolvedTypeName}.${fieldName}`, resolvedType);
4185
+ }
4186
+ }
4187
+ return fields;
4188
+ }
4189
+ function hasShapeChange(diff) {
4190
+ return diff.addedFields.length > 0 || diff.removedFields.length > 0 || diff.changedFields.length > 0;
4191
+ }
4192
+ function diffSdlShapes(oldSdl, newSdl) {
4193
+ const empty = {
4194
+ addedFields: [],
4195
+ removedFields: [],
4196
+ changedFields: []
4197
+ };
4198
+ let oldDoc;
4199
+ let newDoc;
4200
+ try {
4201
+ oldDoc = (0, import_graphql.parse)(oldSdl);
4202
+ newDoc = (0, import_graphql.parse)(newSdl);
4203
+ } catch {
4204
+ return empty;
4205
+ }
4206
+ const oldTypes = collectTypeFields(oldDoc);
4207
+ const newTypes = collectTypeFields(newDoc);
4208
+ const oldFields = flattenFields(oldTypes, detectTypeRenames(oldTypes, newTypes));
4209
+ const newFields = flattenFields(newTypes, /* @__PURE__ */ new Map());
4210
+ const diff = {
4211
+ addedFields: [],
4212
+ removedFields: [],
4213
+ changedFields: []
4214
+ };
4215
+ for (const [key, newType] of newFields) {
4216
+ const oldType = oldFields.get(key);
4217
+ if (oldType === void 0) diff.addedFields.push(key);
4218
+ else if (oldType !== newType) diff.changedFields.push(`${key}: ${oldType} → ${newType}`);
4219
+ }
4220
+ for (const key of oldFields.keys()) if (!newFields.has(key)) diff.removedFields.push(key);
4221
+ return diff;
4222
+ }
4223
+ const SAFE = { kind: "safe" };
4224
+ function isBlank(value) {
4225
+ return !value || !value.trim() || value.trim() === "{}";
4226
+ }
4227
+ /**
4228
+ * True for a blank SDL, or an SDL whose types contain nothing but the
4229
+ * `_placeholder` field the editor seeds new state/operation schemas with
4230
+ * (see `makeInitialSchemaDoc` / `makeOperationInitialDoc` in ./helpers.ts).
4231
+ * Replacing a placeholder-only schema with real fields is a user's first
4232
+ * edit on a brand-new model, not a version-relevant change.
4233
+ */
4234
+ function isPlaceholderOnlySchema(sdl) {
4235
+ if (isBlank(sdl)) return true;
4236
+ let doc;
4237
+ try {
4238
+ doc = (0, import_graphql.parse)(sdl);
4239
+ } catch {
4240
+ return false;
4241
+ }
4242
+ return [...collectTypeFields(doc).values()].every((fields) => fields.size === 0 || fields.size === 1 && fields.has("_placeholder"));
4243
+ }
4244
+ function findOperation(spec, operationId) {
4245
+ for (const module of spec.modules) {
4246
+ const operation = module.operations.find((op) => op.id === operationId);
4247
+ if (operation) return operation;
4248
+ }
4249
+ }
4250
+ function addedSinceLastRelease(operationId, previousSpec) {
4251
+ return previousSpec !== void 0 && !findOperation(previousSpec, operationId);
4252
+ }
4253
+ function classifySetStateSchema(input, latestSpec) {
4254
+ const currentSchema = input.scope === "local" ? latestSpec.state.local.schema : latestSpec.state.global.schema;
4255
+ if (isPlaceholderOnlySchema(currentSchema)) return SAFE;
4256
+ const diff = diffSdlShapes(currentSchema, input.schema);
4257
+ if (!hasShapeChange(diff)) return SAFE;
4258
+ return {
4259
+ kind: "version-relevant",
4260
+ reason: input.scope === "local" ? `You're changing the local fields that version ${latestSpec.version} documents store.` : `You're changing the fields that version ${latestSpec.version} documents store.`,
4261
+ diff
4262
+ };
4263
+ }
4264
+ /**
4265
+ * The editor pre-fills a fresh model's initial value from the placeholder
4266
+ * schema, so a value that is blank or carries only the `_placeholder` key is
4267
+ * still being initialized rather than changed.
4268
+ */
4269
+ function isPlaceholderOnlyInitialValue(value) {
4270
+ if (isBlank(value)) return true;
4271
+ let parsed;
4272
+ try {
4273
+ parsed = JSON.parse(value);
4274
+ } catch {
4275
+ return false;
4276
+ }
4277
+ if (typeof parsed !== "object" || parsed === null) return false;
4278
+ return Object.keys(parsed).every((key) => key === "_placeholder");
4279
+ }
4280
+ function classifySetInitialState(input, latestSpec) {
4281
+ const currentValue = input.scope === "local" ? latestSpec.state.local.initialValue : latestSpec.state.global.initialValue;
4282
+ if (isPlaceholderOnlyInitialValue(currentValue)) return SAFE;
4283
+ if (compareStringsWithoutWhitespace(currentValue, input.initialValue)) return SAFE;
4284
+ return {
4285
+ kind: "version-relevant",
4286
+ reason: `You're changing the starting content that version ${latestSpec.version} documents are built on.`
4287
+ };
4288
+ }
4289
+ function classifyOperationChange(action, operationId, latestSpec, previousSpec) {
4290
+ if (addedSinceLastRelease(operationId, previousSpec)) return SAFE;
4291
+ const operation = findOperation(latestSpec, operationId);
4292
+ if (!operation) return SAFE;
4293
+ const operationLabel = operation.name || "an operation";
4294
+ switch (action.type) {
4295
+ case "DELETE_OPERATION": return {
4296
+ kind: "version-relevant",
4297
+ reason: `You're removing the "${operationLabel}" operation from version ${latestSpec.version}.`
4298
+ };
4299
+ case "SET_OPERATION_NAME":
4300
+ if (isBlank(operation.name)) return SAFE;
4301
+ return {
4302
+ kind: "version-relevant",
4303
+ reason: `You're renaming the "${operationLabel}" operation in version ${latestSpec.version}.`
4304
+ };
4305
+ case "SET_OPERATION_SCHEMA": {
4306
+ if (isPlaceholderOnlySchema(operation.schema ?? "")) return SAFE;
4307
+ if (isBlank(action.input.schema)) return {
4308
+ kind: "version-relevant",
4309
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`
4310
+ };
4311
+ const diff = diffSdlShapes(operation.schema ?? "", action.input.schema ?? "");
4312
+ if (!hasShapeChange(diff)) return SAFE;
4313
+ return {
4314
+ kind: "version-relevant",
4315
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`,
4316
+ diff
4317
+ };
4318
+ }
4319
+ default: return SAFE;
4320
+ }
4321
+ }
4322
+ function classifyDeleteModule(moduleId, latestSpec, previousSpec) {
4323
+ const module = latestSpec.modules.find((candidate) => candidate.id === moduleId);
4324
+ if (!module || module.operations.length === 0) return SAFE;
4325
+ if (module.operations.every((operation) => addedSinceLastRelease(operation.id, previousSpec))) return SAFE;
4326
+ return {
4327
+ kind: "version-relevant",
4328
+ reason: `You're removing the "${module.name}" module and all of its operations from version ${latestSpec.version}.`
4329
+ };
4330
+ }
4331
+ /**
4332
+ * Classifies a document-model action as version-relevant (would break
4333
+ * documents created with the current version) or safe. `previousSpec` is the
4334
+ * last released specification, used to exempt operations added since the
4335
+ * release.
4336
+ */
4337
+ function classifyDocumentModelAction(action, latestSpec, previousSpec) {
4338
+ switch (action.type) {
4339
+ case "SET_STATE_SCHEMA": return classifySetStateSchema(action.input, latestSpec);
4340
+ case "SET_INITIAL_STATE": return classifySetInitialState(action.input, latestSpec);
4341
+ case "DELETE_OPERATION":
4342
+ case "SET_OPERATION_NAME":
4343
+ case "SET_OPERATION_SCHEMA": return classifyOperationChange(action, action.input.id, latestSpec, previousSpec);
4344
+ case "DELETE_MODULE": return classifyDeleteModule(action.input.id, latestSpec, previousSpec);
4345
+ default: return SAFE;
4346
+ }
4347
+ }
4348
+ /**
4349
+ * Pure decision core of the version advisory: given the actions about to be
4350
+ * dispatched, decide whether to dispatch immediately or prompt the user.
4351
+ */
4352
+ function decideDispatch(actions, latestSpec, previousSpec, hasSessionChoice) {
4353
+ if (hasSessionChoice) return { kind: "dispatch" };
4354
+ for (const action of actions) {
4355
+ const classification = classifyDocumentModelAction(action, latestSpec, previousSpec);
4356
+ if (classification.kind === "version-relevant") return {
4357
+ kind: "prompt",
4358
+ reason: classification.reason,
4359
+ diff: classification.diff
4360
+ };
4361
+ }
4362
+ return { kind: "dispatch" };
4363
+ }
4364
+ //#endregion
4365
+ //#region editors/document-model-editor/hooks/useVersionAdvisory.ts
4366
+ /**
4367
+ * Versions the user has confirmed as "still in development" (or that were
4368
+ * just created via an explicit release) for this browser session. Keyed by
4369
+ * `${documentId}:${version}`. Deliberately in-memory: a publisher returning
4370
+ * in a later session is asked again, which is when the reminder matters.
4371
+ */
4372
+ const sessionVersionChoices = /* @__PURE__ */ new Set();
4373
+ function useVersionAdvisory(args) {
4374
+ const { documentId, latestSpec, previousSpec, dispatch, onReleaseError } = args;
4375
+ const [prompt, setPrompt] = useState(void 0);
4376
+ const pendingRef = useRef(void 0);
4377
+ const choiceKey = `${documentId}:${latestSpec.version}`;
4378
+ const guardedDispatch = (...dispatchArgs) => {
4379
+ const [action] = dispatchArgs;
4380
+ const decision = decideDispatch((Array.isArray(action) ? action : [action]).filter((candidate) => candidate !== void 0), latestSpec, previousSpec, sessionVersionChoices.has(choiceKey));
4381
+ if (decision.kind === "dispatch") {
4382
+ dispatch(...dispatchArgs);
4383
+ return;
4384
+ }
4385
+ pendingRef.current = dispatchArgs;
4386
+ setPrompt({
4387
+ version: latestSpec.version,
4388
+ reason: decision.reason,
4389
+ diff: decision.diff
4390
+ });
4391
+ };
4392
+ const flushPending = () => {
4393
+ const pending = pendingRef.current;
4394
+ pendingRef.current = void 0;
4395
+ if (pending) dispatch(...pending);
4396
+ };
4397
+ const releaseFirst = () => {
4398
+ setPrompt(void 0);
4399
+ if (!pendingRef.current) return;
4400
+ dispatch(releaseNewVersion(), (errors) => {
4401
+ if (errors.length > 0) {
4402
+ pendingRef.current = void 0;
4403
+ onReleaseError?.(errors[0].message);
4404
+ }
4405
+ }, () => {
4406
+ if (!pendingRef.current) return;
4407
+ sessionVersionChoices.add(`${documentId}:${latestSpec.version + 1}`);
4408
+ flushPending();
4409
+ });
4410
+ };
4411
+ const keepEditing = () => {
4412
+ sessionVersionChoices.add(choiceKey);
4413
+ setPrompt(void 0);
4414
+ flushPending();
4415
+ };
4416
+ const cancelAdvisory = () => {
4417
+ pendingRef.current = void 0;
4418
+ setPrompt(void 0);
4419
+ };
4420
+ const markVersionInDevelopment = (version) => {
4421
+ sessionVersionChoices.add(`${documentId}:${version}`);
4422
+ };
4423
+ return {
4424
+ guardedDispatch,
4425
+ prompt,
4426
+ releaseFirst,
4427
+ keepEditing,
4428
+ cancelAdvisory,
4429
+ markVersionInDevelopment
4430
+ };
4431
+ }
4432
+ //#endregion
4433
+ //#region editors/document-model-editor/editor.tsx
4434
+ var editor_exports = /* @__PURE__ */ __exportAll({ default: () => Editor });
4435
+ const StateSchemas = lazy(() => import("./state-schemas-DXWpf1zO.mjs"));
4436
+ const noopSetStateSchema = () => void 0;
4437
+ const noopSetInitialState = () => void 0;
4438
+ function Editor({ document, dispatch }) {
4439
+ useSetPHDocumentEditorConfig(editorConfig);
4440
+ const toast = usePHToast();
4441
+ const [scope, setScope] = useState("global");
4442
+ const documentNodeName = document.header.name;
4443
+ const { name: modelName, id: documentType, extension, description, author: { name: authorName, website: authorWebsite } } = document.state.global;
4444
+ const specifications = document.state.global.specifications;
4445
+ const latestSpec = specifications[specifications.length - 1];
4446
+ const previousSpec = specifications.length >= 2 ? specifications[specifications.length - 2] : void 0;
4447
+ const [viewedVersion, setViewedVersion] = useState("latest");
4448
+ const viewedSpec = viewedVersion === "latest" ? latestSpec : specifications.find((spec) => spec.version === viewedVersion) ?? latestSpec;
4449
+ const isViewingFrozenVersion = viewedSpec.version !== latestSpec.version;
4450
+ const { state: { global: { schema: globalStateSchema, initialValue: globalStateInitialValue }, local: { schema: localStateSchema, initialValue: localStateInitialValue } }, modules } = viewedSpec;
4451
+ const operations = modules.flatMap((module) => module.operations);
4452
+ const { state: { global: { schema: latestGlobalStateSchema, initialValue: latestGlobalStateInitialValue }, local: { schema: latestLocalStateSchema, initialValue: latestLocalStateInitialValue } }, modules: latestModules } = latestSpec;
4453
+ const latestOperations = latestModules.flatMap((module) => module.operations);
4454
+ const shouldSetInitialName = useRef(!modelName && !!documentNodeName && latestOperations.length === 0);
4455
+ useEffect(() => {
4456
+ if (!shouldSetInitialName.current || !documentNodeName) return;
4457
+ const initialSchemaDoc = initializeModelSchema(documentNodeName);
4458
+ dispatch([setModelName({ name: documentNodeName }), setStateSchema({
4459
+ schema: initialSchemaDoc,
4460
+ scope: "global"
4461
+ })]);
4462
+ shouldSetInitialName.current = false;
4463
+ }, [documentNodeName, dispatch]);
4464
+ const { guardedDispatch, prompt, releaseFirst, keepEditing, cancelAdvisory, markVersionInDevelopment } = useVersionAdvisory({
4465
+ documentId: document.header.id,
4466
+ latestSpec,
4467
+ previousSpec,
4468
+ dispatch,
4469
+ onReleaseError: (message) => {
4470
+ if (toast) toast(message, { type: "connect-warning" });
4471
+ }
4472
+ });
4473
+ const handleReleaseNewVersion = () => {
4474
+ const nextVersion = latestSpec.version + 1;
4475
+ dispatch(releaseNewVersion(), (errors) => {
4476
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
4477
+ }, () => {
4478
+ markVersionInDevelopment(nextVersion);
4479
+ setViewedVersion("latest");
4480
+ });
4481
+ };
4482
+ const operationSchemasSdl = operations.flatMap((operation) => operation.schema ?? []).join("\n");
4483
+ const handleSetModelId = (id) => {
4484
+ if (compareStringsWithoutWhitespace(id, documentType)) return;
4485
+ guardedDispatch([setModelId({ id })]);
4486
+ };
4487
+ const handleSetModelDescription = (newDescription) => {
4488
+ if (compareStringsWithoutWhitespace(newDescription, description)) return;
4489
+ guardedDispatch(setModelDescription({ description: newDescription }));
4490
+ };
4491
+ const handleSetModelExtension = (newExtension) => {
4492
+ if (compareStringsWithoutWhitespace(newExtension, extension)) return;
4493
+ guardedDispatch(setModelExtension({ extension: newExtension }));
4494
+ };
4495
+ const handleSetModelName = (newName) => {
4496
+ if (compareStringsWithoutWhitespace(newName, modelName)) return;
4497
+ guardedDispatch(setModelName({ name: newName }));
4498
+ };
4499
+ const handleSetAuthorName = (newAuthorName) => {
4500
+ if (compareStringsWithoutWhitespace(newAuthorName, authorName)) return;
4501
+ guardedDispatch(setAuthorName({ authorName: newAuthorName }));
4502
+ };
4503
+ const handleSetAuthorWebsite = (newAuthorWebsite) => {
4504
+ if (compareStringsWithoutWhitespace(newAuthorWebsite, authorWebsite ?? "")) return;
4505
+ guardedDispatch(setAuthorWebsite({ authorWebsite: newAuthorWebsite }));
4506
+ };
4507
+ const handleSetStateSchema = (newSchema, scope) => {
4508
+ if (compareStringsWithoutWhitespace(newSchema, scope === "global" ? latestGlobalStateSchema : latestLocalStateSchema)) return;
4509
+ guardedDispatch(setStateSchema({
4510
+ schema: newSchema,
4511
+ scope
4512
+ }));
4513
+ };
4514
+ const handleSetInitialState = (newInitialValue, scope) => {
4515
+ if (compareStringsWithoutWhitespace(newInitialValue, scope === "global" ? latestGlobalStateInitialValue : latestLocalStateInitialValue)) return;
4516
+ guardedDispatch(setInitialState({
4517
+ initialValue: newInitialValue,
4518
+ scope
4519
+ }));
4520
+ };
4521
+ const handleAddModule = (name) => {
4522
+ return new Promise((resolve) => {
4523
+ try {
4524
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) {
4525
+ resolve(void 0);
4526
+ return;
4527
+ }
4528
+ const id = generateId();
4529
+ guardedDispatch(addModule({
4530
+ id,
4531
+ name
4532
+ }));
4533
+ resolve(id);
4534
+ } catch (error) {
4535
+ console.error("Failed to add module:", error);
4536
+ resolve(void 0);
4537
+ }
4538
+ });
4539
+ };
4540
+ const handleSetModuleName = (id, name) => {
4541
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) return;
4542
+ guardedDispatch(setModuleName({
4543
+ id,
4544
+ name
4545
+ }));
4546
+ };
4547
+ const handleDeleteModule = (id) => {
4548
+ guardedDispatch(deleteModule({ id }));
4549
+ };
4550
+ const handleAddOperation = (moduleId, name) => {
4551
+ return new Promise((resolve) => {
4552
+ const id = generateId();
4553
+ guardedDispatch(addOperation({
4554
+ id,
4555
+ moduleId,
4556
+ name,
4557
+ scope
4558
+ }), (errors) => {
4559
+ if (errors.length > 0) {
4560
+ if (toast) toast(errors[0].message, { type: "connect-warning" });
4561
+ resolve(void 0);
4562
+ } else resolve(id);
4563
+ }, () => resolve(id));
4564
+ });
4565
+ };
4566
+ const handleSetOperationName = (id, name) => {
4567
+ guardedDispatch(setOperationName({
4568
+ id,
4569
+ name
4570
+ }), (errors) => {
4571
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
4572
+ });
4573
+ };
4574
+ const handleSetOperationSchema = (id, newSchema) => {
4575
+ const operation = latestOperations.find((operation) => operation.id === id);
4576
+ if (operation?.schema && compareStringsWithoutWhitespace(newSchema, operation.schema)) return;
4577
+ guardedDispatch(setOperationSchema({
4578
+ id,
4579
+ schema: newSchema
4580
+ }));
4581
+ };
4582
+ const handleToggleNoInputRequired = (id, noInputRequired) => {
4583
+ const operation = latestOperations.find((op) => op.id === id);
4584
+ if (!operation?.name) return;
4585
+ if (noInputRequired) guardedDispatch(setOperationSchema({
4586
+ id,
4587
+ schema: makeEmptyOperationSchema(operation.name)
4588
+ }));
4589
+ else guardedDispatch(setOperationSchema({
4590
+ id,
4591
+ schema: makeOperationInitialDoc(operation.name)
4592
+ }));
4593
+ };
4594
+ const handleSetOperationDescription = (id, newDescription) => {
4595
+ if (compareStringsWithoutWhitespace(latestOperations.find((operation) => operation.id === id)?.description ?? "", newDescription)) return;
4596
+ guardedDispatch(setOperationDescription({
4597
+ id,
4598
+ description: newDescription
4599
+ }));
4600
+ };
4601
+ const handleDeleteOperation = (id) => {
4602
+ guardedDispatch(deleteOperation({ id }));
4603
+ };
4604
+ const handleAddOperationError = (operationId, errorName) => {
4605
+ return new Promise((resolve) => {
4606
+ try {
4607
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) {
4608
+ resolve(void 0);
4609
+ return;
4610
+ }
4611
+ const id = generateId();
4612
+ const errorCode = pascalCase(errorName);
4613
+ guardedDispatch(addOperationError({
4614
+ id,
4615
+ operationId,
4616
+ errorName,
4617
+ errorCode
4618
+ }));
4619
+ resolve(id);
4620
+ } catch (error) {
4621
+ console.error("Failed to add operation error:", error);
4622
+ resolve(void 0);
4623
+ }
4624
+ });
4625
+ };
4626
+ const handleDeleteOperationError = (id) => {
4627
+ guardedDispatch(deleteOperationError({ id }));
4628
+ };
4629
+ const handleSetOperationErrorName = (operationId, errorId, errorName) => {
4630
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) return;
4631
+ guardedDispatch(setOperationErrorName({
4632
+ id: errorId,
4633
+ errorName
4634
+ }));
4635
+ };
4636
+ const addOperationAndInitialSchema = async (moduleId, name) => {
4637
+ try {
4638
+ const id = await handleAddOperation(moduleId, name);
4639
+ if (!id) return void 0;
4640
+ try {
4641
+ handleSetOperationSchema(id, makeOperationInitialDoc(name));
4642
+ return id;
4643
+ } catch (error) {
4644
+ console.error("Failed to update operation schema:", error);
4645
+ return;
4646
+ }
4647
+ } catch (error) {
4648
+ console.error("Failed to add operation and schema:", error);
4649
+ return;
4650
+ }
4651
+ };
4652
+ return /* @__PURE__ */ jsxs("main", {
4653
+ className: "min-h-dvh bg-background p-6",
4654
+ children: [
4655
+ /* @__PURE__ */ jsx(DocumentToolbar, { document }),
4656
+ /* @__PURE__ */ jsx(SchemaContextProvider, {
4657
+ globalStateSchemaSdl: globalStateSchema,
4658
+ localStateSchemaSdl: localStateSchema,
4659
+ operationSchemasSdl,
4660
+ children: /* @__PURE__ */ jsxs("div", {
4661
+ className: "mx-auto max-w-6xl px-4 pt-8",
4662
+ children: [
4663
+ /* @__PURE__ */ jsx(VersionControls, {
4664
+ specifications,
4665
+ viewedVersion: viewedSpec.version,
4666
+ onViewVersion: setViewedVersion,
4667
+ onReleaseNewVersion: handleReleaseNewVersion
4668
+ }),
4669
+ /* @__PURE__ */ jsx(ModelMetadata, {
4670
+ name: modelName,
4671
+ documentType,
4672
+ extension,
4673
+ description,
4674
+ authorName,
4675
+ authorWebsite: authorWebsite ?? "",
4676
+ globalStateSchema: latestGlobalStateSchema,
4677
+ localStateSchema: latestLocalStateSchema,
4678
+ setModelId: handleSetModelId,
4679
+ setModelDescription: handleSetModelDescription,
4680
+ setModelExtension: handleSetModelExtension,
4681
+ setModelName: handleSetModelName,
4682
+ setAuthorName: handleSetAuthorName,
4683
+ setAuthorWebsite: handleSetAuthorWebsite,
4684
+ setStateSchema: handleSetStateSchema
4685
+ }),
4686
+ /* @__PURE__ */ jsx(Divider, {}),
4687
+ isViewingFrozenVersion && /* @__PURE__ */ jsx(FrozenVersionBanner, {
4688
+ latestVersion: latestSpec.version,
4689
+ viewedVersion: viewedSpec.version
4690
+ }),
4691
+ /* @__PURE__ */ jsxs("div", {
4692
+ className: isViewingFrozenVersion ? "pointer-events-none opacity-80 select-none" : void 0,
4693
+ inert: isViewingFrozenVersion || void 0,
4694
+ children: [
4695
+ /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(StateSchemas, {
4696
+ modelName,
4697
+ globalStateSchema,
4698
+ globalStateInitialValue,
4699
+ localStateSchema,
4700
+ localStateInitialValue,
4701
+ setStateSchema: isViewingFrozenVersion ? noopSetStateSchema : handleSetStateSchema,
4702
+ setInitialState: isViewingFrozenVersion ? noopSetInitialState : handleSetInitialState,
4703
+ currentScope: scope,
4704
+ onScopeChange: setScope
4705
+ }) }),
4706
+ /* @__PURE__ */ jsx(Divider, {}),
4707
+ /* @__PURE__ */ jsxs("h3", {
4708
+ className: "mb-6 text-lg text-foreground capitalize",
4709
+ children: [scope, " Operations"]
4710
+ }),
4711
+ /* @__PURE__ */ jsx(Modules, {
4712
+ modules: modules.map((module) => ({
4713
+ ...module,
4714
+ operations: module.operations.filter((op) => op.scope === scope)
4715
+ })),
4716
+ allOperations: operations,
4717
+ addModule: handleAddModule,
4718
+ updateModuleName: handleSetModuleName,
4719
+ deleteModule: handleDeleteModule,
4720
+ updateOperationName: handleSetOperationName,
4721
+ updateOperationSchema: handleSetOperationSchema,
4722
+ setOperationDescription: handleSetOperationDescription,
4723
+ deleteOperation: handleDeleteOperation,
4724
+ addOperationError: handleAddOperationError,
4725
+ deleteOperationError: handleDeleteOperationError,
4726
+ setOperationErrorName: handleSetOperationErrorName,
4727
+ addOperationAndInitialSchema,
4728
+ toggleNoInputRequired: handleToggleNoInputRequired
4729
+ })
4730
+ ]
4731
+ })
4732
+ ]
4733
+ })
4734
+ }),
4735
+ /* @__PURE__ */ jsx(VersionAdvisoryModal, {
4736
+ prompt,
4737
+ onReleaseFirst: releaseFirst,
4738
+ onKeepEditing: keepEditing,
4739
+ onCancel: cancelAdvisory
4740
+ })
4741
+ ]
4742
+ });
4743
+ }
4744
+ //#endregion
4745
+ export { ensureValidStateSchemaName as a, makeMinimalObjectForStateType as c, Editor as default, Button as i, makeStateSchemaNameForScope as l, composeRefs$1 as n, StateValidationError as o, useComposedRefs$1 as r, makeInitialSchemaDoc as s, editor_exports as t, validateStateObject as u };
4746
+
4747
+ //# sourceMappingURL=editor-7g9ujMII.mjs.map