@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.1 → 6.2.3-dev.100

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