@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.69 → 6.2.3-dev.70

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 (92) hide show
  1. package/dist/browser/document-models/index.js +1 -1
  2. package/dist/{node/documents-D70S9PZL.mjs → browser/documents-BLZ-QW5b.js} +4 -5
  3. package/dist/browser/documents-BLZ-QW5b.js.map +1 -0
  4. package/dist/browser/{editor-C46DbRGz.js → editor-Dmpkd8pQ.js} +3 -3
  5. package/dist/browser/{editor-C46DbRGz.js.map → editor-Dmpkd8pQ.js.map} +1 -1
  6. package/dist/browser/editor-x1UIfSot.js +2277 -0
  7. package/dist/browser/editor-x1UIfSot.js.map +1 -0
  8. package/dist/browser/editors/document-model-editor/module.js +1 -1
  9. package/dist/browser/editors/document-model-editor/module.js.map +1 -1
  10. package/dist/browser/editors/generic-drive-explorer/index.js +4 -341
  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/folder-view-CwIU4XEe.js +237 -0
  14. package/dist/browser/folder-view-CwIU4XEe.js.map +1 -0
  15. package/dist/browser/graphql-editor-CpcGaYmP.js +103 -0
  16. package/dist/browser/graphql-editor-CpcGaYmP.js.map +1 -0
  17. package/dist/browser/hooks-BmHa-lY2.js +126 -0
  18. package/dist/browser/hooks-BmHa-lY2.js.map +1 -0
  19. package/dist/browser/index.js +5 -805
  20. package/dist/browser/index.js.map +1 -1
  21. package/dist/browser/json-editor-CB1XmZgN.js +55 -0
  22. package/dist/browser/json-editor-CB1XmZgN.js.map +1 -0
  23. package/dist/browser/schema-context-5evhtuMb.js +70 -0
  24. package/dist/browser/schema-context-5evhtuMb.js.map +1 -0
  25. package/dist/browser/state-schemas-DHLAg1w0.js +300 -0
  26. package/dist/browser/state-schemas-DHLAg1w0.js.map +1 -0
  27. package/dist/node/bundle-mjs-Cuu3DEfT.mjs +3140 -0
  28. package/dist/node/bundle-mjs-Cuu3DEfT.mjs.map +1 -0
  29. package/dist/node/{graphql-Dp4j7rmx.mjs → documents-CFiuC6XV.mjs} +16 -3
  30. package/dist/node/documents-CFiuC6XV.mjs.map +1 -0
  31. package/dist/node/{editor-pTt1k9t6.mjs → editor-7g9ujMII.mjs} +2883 -2733
  32. package/dist/node/editor-7g9ujMII.mjs.map +1 -0
  33. package/dist/node/{editor-DXke64og.mjs → editor-NwTlNx8z.mjs} +3 -3
  34. package/dist/node/{editor-DXke64og.mjs.map → editor-NwTlNx8z.mjs.map} +1 -1
  35. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  36. package/dist/node/editors/document-model-editor/module.mjs.map +1 -1
  37. package/dist/node/editors/generic-drive-explorer/index.mjs +3 -4
  38. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  39. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  40. package/dist/node/{folder-view-UO8P7SfT.mjs → folder-view-CkCNU8A_.mjs} +4 -4
  41. package/dist/node/folder-view-CkCNU8A_.mjs.map +1 -0
  42. package/dist/node/{graphql-editor-CBJXEY_C.mjs → graphql-editor-v1OXETjM.mjs} +5079 -26
  43. package/dist/node/graphql-editor-v1OXETjM.mjs.map +1 -0
  44. package/dist/{browser/hooks-eQxBX7g4.js → node/hooks-gEAaW5rF.mjs} +2 -2
  45. package/dist/node/{hooks-C2b46djt.mjs.map → hooks-gEAaW5rF.mjs.map} +1 -1
  46. package/dist/node/index.mjs +3 -178
  47. package/dist/node/index.mjs.map +1 -1
  48. package/dist/{browser/json-editor-DfRD-pfk.js → node/json-editor-8dfjgcaX.mjs} +3 -3
  49. package/dist/node/{json-editor-DaqHARBD.mjs.map → json-editor-8dfjgcaX.mjs.map} +1 -1
  50. package/dist/node/rolldown-runtime-Bl3dcgcQ.mjs +16 -0
  51. package/dist/node/{schema-context-CojjnSE6.mjs → schema-context-DgUu7l_Q.mjs} +2 -3
  52. package/dist/node/{schema-context-CojjnSE6.mjs.map → schema-context-DgUu7l_Q.mjs.map} +1 -1
  53. package/dist/node/{state-schemas-C-3b_V-y.mjs → state-schemas-DXWpf1zO.mjs} +419 -53
  54. package/dist/node/state-schemas-DXWpf1zO.mjs.map +1 -0
  55. package/package.json +19 -17
  56. package/dist/browser/assets/entry-oIniX8Dq.js +0 -418
  57. package/dist/browser/assets/projection-entry-CdlLTrjU.js +0 -482
  58. package/dist/browser/documents-CRzouuNR.js +0 -6067
  59. package/dist/browser/documents-CRzouuNR.js.map +0 -1
  60. package/dist/browser/editor-CHAz7_5H.js +0 -4676
  61. package/dist/browser/editor-CHAz7_5H.js.map +0 -1
  62. package/dist/browser/folder-view-ByndDKAA.js +0 -966
  63. package/dist/browser/folder-view-ByndDKAA.js.map +0 -1
  64. package/dist/browser/graphql-editor-DaeXCZJ2.js +0 -11708
  65. package/dist/browser/graphql-editor-DaeXCZJ2.js.map +0 -1
  66. package/dist/browser/hooks-eQxBX7g4.js.map +0 -1
  67. package/dist/browser/icon-components-CJ4I3Y6Y-63fqUqwJ.js +0 -3188
  68. package/dist/browser/icon-components-CJ4I3Y6Y-63fqUqwJ.js.map +0 -1
  69. package/dist/browser/json-editor-DfRD-pfk.js.map +0 -1
  70. package/dist/browser/parser-DtbeHA3H.js +0 -2554
  71. package/dist/browser/parser-DtbeHA3H.js.map +0 -1
  72. package/dist/browser/rolldown-runtime-DC62tzP2.js +0 -33
  73. package/dist/browser/src-CohvVFnR-DSqs821B.js +0 -5694
  74. package/dist/browser/src-CohvVFnR-DSqs821B.js.map +0 -1
  75. package/dist/browser/state-schemas-CVfWDSOU.js +0 -696
  76. package/dist/browser/state-schemas-CVfWDSOU.js.map +0 -1
  77. package/dist/browser/tslib.es6-Cno80yFJ.js +0 -32
  78. package/dist/browser/tslib.es6-Cno80yFJ.js.map +0 -1
  79. package/dist/node/documents-D70S9PZL.mjs.map +0 -1
  80. package/dist/node/editor-pTt1k9t6.mjs.map +0 -1
  81. package/dist/node/folder-view-UO8P7SfT.mjs.map +0 -1
  82. package/dist/node/graphql-Dp4j7rmx.mjs.map +0 -1
  83. package/dist/node/graphql-editor-CBJXEY_C.mjs.map +0 -1
  84. package/dist/node/hooks-C2b46djt.mjs +0 -24593
  85. package/dist/node/icon-components-CJ4I3Y6Y-BEyG_aKA.mjs +0 -3188
  86. package/dist/node/icon-components-CJ4I3Y6Y-BEyG_aKA.mjs.map +0 -1
  87. package/dist/node/json-editor-DaqHARBD.mjs +0 -153
  88. package/dist/node/src-CohvVFnR-6ubKLBl5.mjs +0 -6375
  89. package/dist/node/src-CohvVFnR-6ubKLBl5.mjs.map +0 -1
  90. package/dist/node/state-schemas-C-3b_V-y.mjs.map +0 -1
  91. package/dist/node/tslib.es6-VORZjfk3.mjs +0 -583
  92. package/dist/node/tslib.es6-VORZjfk3.mjs.map +0 -1
@@ -0,0 +1,2277 @@
1
+ import { n as safeParseSdl, t as SchemaContextProvider } from "./schema-context-5evhtuMb.js";
2
+ 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";
3
+ import * as React$1 from "react";
4
+ import React, { Suspense, forwardRef, lazy, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from "react";
5
+ import { ConnectSelect, DocumentToolbar, Modal, ModalButton } from "@powerhousedao/design-system/connect";
6
+ import { usePHToast, useSetPHDocumentEditorConfig } from "@powerhousedao/reactor-browser";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ import { twMerge } from "tailwind-merge";
9
+ import { GraphQLError, Kind, buildASTSchema, getOperationAST, getVariableValues, parse, print, visit } from "graphql";
10
+ import { getPHCustomScalarByTypeName } from "@powerhousedao/document-engineering/graphql";
11
+ import { constantCase, pascalCase, sentenceCase, snakeCase } from "change-case";
12
+ import { z } from "zod";
13
+ import { zodResolver } from "@hookform/resolvers/zod";
14
+ import { Controller, FormProvider, useForm, useFormContext } from "react-hook-form";
15
+ import { Slot } from "@radix-ui/react-slot";
16
+ import * as LabelPrimitive from "@radix-ui/react-label";
17
+ import { cva } from "class-variance-authority";
18
+ //#region \0rolldown/runtime.js
19
+ var __defProp = Object.defineProperty;
20
+ var __exportAll = (all, no_symbols) => {
21
+ let target = {};
22
+ for (var name in all) __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true
25
+ });
26
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
27
+ return target;
28
+ };
29
+ //#endregion
30
+ //#region editors/document-model-editor/constants/graphql-kinds.ts
31
+ const STRING_GQL_PRIMITIVE_NAME = "String";
32
+ const BOOLEAN_GQL_PRIMITIVE_NAME = "Boolean";
33
+ const FLOAT_GQL_PRIMITIVE_NAME = "Float";
34
+ const gqlPrimitiveNodeNamesList = [
35
+ STRING_GQL_PRIMITIVE_NAME,
36
+ BOOLEAN_GQL_PRIMITIVE_NAME,
37
+ "Int",
38
+ FLOAT_GQL_PRIMITIVE_NAME,
39
+ "ID"
40
+ ];
41
+ //#endregion
42
+ //#region editors/document-model-editor/utils/helpers.ts
43
+ function makeStateSchemaNameForScope(modelName, scope) {
44
+ const modelNamePascalCase = pascalCase(modelName);
45
+ const scopePascalCase = pascalCase(scope);
46
+ return scopePascalCase === "Global" ? `${modelNamePascalCase}State` : `${modelNamePascalCase}${scopePascalCase}State`;
47
+ }
48
+ function makeInitialSchemaDoc(modelName, scope) {
49
+ return `type ${makeStateSchemaNameForScope(modelName, scope)} {
50
+ "Add your ${scope} state fields here"
51
+ _placeholder: String
52
+ }`;
53
+ }
54
+ function makeOperationInitialDoc(name) {
55
+ return `input ${pascalCase(name)}Input {
56
+ "Add your inputs here"
57
+ _placeholder: String
58
+ }`;
59
+ }
60
+ function makeEmptyOperationSchema(operationName) {
61
+ return `input ${pascalCase(operationName)}Input {\n _empty: Boolean\n}`;
62
+ }
63
+ function isEmptyOperationSchema(schema) {
64
+ if (!schema) return false;
65
+ return /_empty:\s*Boolean/.test(schema) && !schema.replace(/_empty:\s*Boolean/, "").match(/\w+:\s*\w+/);
66
+ }
67
+ function safeParseJsonRecord(json) {
68
+ try {
69
+ return JSON.parse(json);
70
+ } catch (_error) {
71
+ return null;
72
+ }
73
+ }
74
+ function makeMinimalObjectForStateType(args) {
75
+ const { sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue } = args;
76
+ const existingValueObject = safeParseJsonRecord(existingValue);
77
+ if (!existingValueObject) return existingValue;
78
+ const stateTypeDefinitionFields = stateTypeDefinitionNode.fields;
79
+ if (!stateTypeDefinitionFields?.length) return existingValue;
80
+ const minimalObject = makeMinimalValuesForObjectFields({
81
+ schemaDocumentNode: sharedSchemaDocumentNode,
82
+ fieldDefinitionNodes: stateTypeDefinitionFields,
83
+ existingValueObject,
84
+ visitedTypes: /* @__PURE__ */ new Set([stateTypeDefinitionNode.name.value])
85
+ });
86
+ return JSON.stringify(minimalObject, null, 2);
87
+ }
88
+ function makeMinimalValuesForObjectFields(args) {
89
+ const { schemaDocumentNode, existingValueObject, fieldDefinitionNodes, visitedTypes } = args;
90
+ const newJson = {};
91
+ for (const astNode of fieldDefinitionNodes) {
92
+ const fieldName = getASTNodeName(astNode);
93
+ if (!fieldName) continue;
94
+ const minimalValue = makeMinimalValueForASTNode({
95
+ fieldName,
96
+ astNode,
97
+ schemaDocumentNode,
98
+ existingValueObject,
99
+ visitedTypes
100
+ });
101
+ newJson[astNode.name.value] = minimalValue;
102
+ }
103
+ return newJson;
104
+ }
105
+ function makeMinimalValueForASTNode(args) {
106
+ const { fieldName, astNode, schemaDocumentNode, existingValueObject, visitedTypes } = args;
107
+ const existingFieldValue = existingValueObject?.[fieldName];
108
+ let node = astNode;
109
+ if (isFieldDefinitionNode(astNode)) node = getASTNodeTypeNode(node);
110
+ const isNonNull = isNonNullNode(node);
111
+ if (isNonNull) node = getASTNodeTypeNode(node);
112
+ if (isListTypeNode(node)) return makeMinimalValueForGqlListNode(node, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes);
113
+ if (isGqlPrimitiveNode(node)) return makeMinimalValueForGQLPrimitiveNode(node, existingFieldValue, isNonNull);
114
+ const namedTypeDefinitionNode = getNamedTypeDefinitionNode(node, schemaDocumentNode);
115
+ if (isEnumTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull);
116
+ if (isScalarTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlScalar(namedTypeDefinitionNode, existingFieldValue, isNonNull);
117
+ if (isUnionTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes);
118
+ if (isObjectTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlObject(namedTypeDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
119
+ return existingFieldValue;
120
+ }
121
+ function isFieldDefinitionNode(astNodeTypeNode) {
122
+ if (!astNodeTypeNode) return false;
123
+ return astNodeTypeNode.kind === Kind.FIELD_DEFINITION;
124
+ }
125
+ function isNonNullNode(astNode) {
126
+ if (!astNode) return false;
127
+ return astNode.kind === Kind.NON_NULL_TYPE;
128
+ }
129
+ function isGqlPrimitiveNode(astNodeTypeNode) {
130
+ if (!astNodeTypeNode) return false;
131
+ const name = getASTNodeName(astNodeTypeNode);
132
+ return gqlPrimitiveNodeNamesList.includes(name);
133
+ }
134
+ function isListTypeNode(astNodeTypeNode) {
135
+ if (!astNodeTypeNode) return false;
136
+ return astNodeTypeNode.kind === Kind.LIST_TYPE;
137
+ }
138
+ function isEnumTypeDefinitionNode(definitionNode) {
139
+ if (!definitionNode) return false;
140
+ return definitionNode.kind === Kind.ENUM_TYPE_DEFINITION;
141
+ }
142
+ function isScalarTypeDefinitionNode(definitionNode) {
143
+ if (!definitionNode) return false;
144
+ return definitionNode.kind === Kind.SCALAR_TYPE_DEFINITION;
145
+ }
146
+ function isUnionTypeDefinitionNode(definitionNode) {
147
+ if (!definitionNode) return false;
148
+ return definitionNode.kind === Kind.UNION_TYPE_DEFINITION;
149
+ }
150
+ function isObjectTypeDefinitionNode(definitionNode) {
151
+ if (!definitionNode) return false;
152
+ return definitionNode.kind === Kind.OBJECT_TYPE_DEFINITION;
153
+ }
154
+ function getASTNodeName(astNode) {
155
+ if (!astNode) return null;
156
+ if (!("name" in astNode)) return null;
157
+ if (!astNode.name) return null;
158
+ if (!("value" in astNode.name)) return null;
159
+ return astNode.name.value;
160
+ }
161
+ function getASTNodeTypeNode(astNode) {
162
+ if (!astNode) return null;
163
+ if (!("type" in astNode)) return null;
164
+ return astNode.type;
165
+ }
166
+ function makeMinimalValueForGQLPrimitiveNode(primitiveTypeNode, existingFieldValue, isNonNull) {
167
+ const name = getASTNodeName(primitiveTypeNode);
168
+ if (!name) return null;
169
+ switch (name) {
170
+ case "ID":
171
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
172
+ return isNonNull ? "placeholder-id" : null;
173
+ case BOOLEAN_GQL_PRIMITIVE_NAME:
174
+ if (z.boolean().safeParse(existingFieldValue).success) return existingFieldValue;
175
+ return isNonNull ? false : null;
176
+ case "Int":
177
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
178
+ return isNonNull ? 0 : null;
179
+ case FLOAT_GQL_PRIMITIVE_NAME:
180
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
181
+ return isNonNull ? 0 : null;
182
+ case STRING_GQL_PRIMITIVE_NAME:
183
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
184
+ return isNonNull ? "" : null;
185
+ }
186
+ return isNonNull ? existingFieldValue : null;
187
+ }
188
+ function makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull) {
189
+ const enumValues = namedTypeDefinitionNode.values?.map((value) => value.name.value) ?? [];
190
+ if (typeof existingFieldValue === "string" && enumValues.includes(existingFieldValue)) return existingFieldValue;
191
+ if (isNonNull) return enumValues[0];
192
+ return null;
193
+ }
194
+ function makeMinimalValueForGqlScalar(scalarTypeDefinitionNode, existingFieldValue, isNonNull) {
195
+ if (!isNonNull && !existingFieldValue) return null;
196
+ const name = getASTNodeName(scalarTypeDefinitionNode);
197
+ if (!name) {
198
+ console.error("No name for scalar type definition node", scalarTypeDefinitionNode);
199
+ return null;
200
+ }
201
+ const scalar = getPHCustomScalarByTypeName(name);
202
+ if (!scalar) return null;
203
+ if (scalar.schema.safeParse(existingFieldValue).success) return existingFieldValue;
204
+ if (!isNonNull) return null;
205
+ const minimalValue = scalar.getDefaultValue?.();
206
+ if (minimalValue) return minimalValue;
207
+ return existingFieldValue;
208
+ }
209
+ function makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes) {
210
+ if (!isNonNull && !existingFieldValue) return null;
211
+ if (!namedTypeDefinitionNode.types?.length) return null;
212
+ const firstNamedTypeDefinitionNode = namedTypeDefinitionNode.types?.at(0);
213
+ if (!firstNamedTypeDefinitionNode) return null;
214
+ const firstNamedTypeObjectDefinitionNode = getNamedTypeDefinitionNode(firstNamedTypeDefinitionNode, schemaDocumentNode);
215
+ if (!isObjectTypeDefinitionNode(firstNamedTypeObjectDefinitionNode)) return null;
216
+ return makeMinimalValueForGqlObject(firstNamedTypeObjectDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
217
+ }
218
+ function makeMinimalValueForGqlListNode(listTypeNode, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes) {
219
+ if (!isNonNull && !Array.isArray(existingFieldValue)) return null;
220
+ if (isNonNull && !Array.isArray(existingFieldValue)) return [];
221
+ return existingFieldValue.map((item, index) => makeMinimalValueForASTNode({
222
+ fieldName: String(index),
223
+ astNode: listTypeNode.type,
224
+ schemaDocumentNode,
225
+ existingValueObject: { [index]: item },
226
+ visitedTypes
227
+ }));
228
+ }
229
+ function makeMinimalValueForGqlObject(objectTypeDefinitionNode, schemaDocumentNode, _existingValueObject, existingFieldValue, isNonNull, visitedTypes) {
230
+ const typeName = objectTypeDefinitionNode.name.value;
231
+ if (visitedTypes?.has(typeName)) return null;
232
+ if (!isNonNull && !existingFieldValue) return null;
233
+ const fields = objectTypeDefinitionNode.fields;
234
+ if (!fields?.length) return {};
235
+ const newVisitedTypes = new Set(visitedTypes);
236
+ newVisitedTypes.add(typeName);
237
+ return makeMinimalValuesForObjectFields({
238
+ schemaDocumentNode,
239
+ existingValueObject: existingFieldValue && typeof existingFieldValue === "object" && !Array.isArray(existingFieldValue) ? existingFieldValue : null,
240
+ fieldDefinitionNodes: fields,
241
+ visitedTypes: newVisitedTypes
242
+ });
243
+ }
244
+ function getNamedTypeDefinitionNode(astNodeTypeNode, schemaDocumentNode) {
245
+ if (!astNodeTypeNode) return null;
246
+ const name = getASTNodeName(astNodeTypeNode);
247
+ if (!name) return null;
248
+ const definitionNode = schemaDocumentNode.definitions.find((def) => "kind" in def && "name" in def && def.name?.value === name);
249
+ if (!definitionNode) return null;
250
+ return definitionNode;
251
+ }
252
+ function removeWhitespace(str) {
253
+ return str.replace(/\s+|\\n|\\t/g, "").toLowerCase();
254
+ }
255
+ function compareStringsWithoutWhitespace(str1, str2) {
256
+ if (str1 === null || str2 === null || str1 === void 0 || str2 === void 0) return false;
257
+ return removeWhitespace(str1) === removeWhitespace(str2);
258
+ }
259
+ function renameSchemaType(sdl, oldName, newName, scope) {
260
+ const typeSuffix = scope === "global" ? "State" : "LocalState";
261
+ const oldTypeName = `${pascalCase(oldName)}${typeSuffix}`;
262
+ const newTypeName = `${pascalCase(newName)}${typeSuffix}`;
263
+ const ast = safeParseSdl(sdl);
264
+ if (!ast) return sdl;
265
+ const updatedAst = visit(ast, { ObjectTypeDefinition: (node) => {
266
+ if (node.name.value === oldTypeName) return {
267
+ ...node,
268
+ name: {
269
+ ...node.name,
270
+ value: newTypeName
271
+ }
272
+ };
273
+ } });
274
+ return print(updatedAst);
275
+ }
276
+ function initializeModelSchema(modelName) {
277
+ return makeInitialSchemaDoc(modelName, "global");
278
+ }
279
+ function updateModelSchemaNames(params) {
280
+ const { oldName, newName, globalStateSchema, localStateSchema, setStateSchema } = params;
281
+ setStateSchema(renameSchemaType(globalStateSchema, oldName, newName, "global"), "global");
282
+ if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, oldName, newName, "local"), "local");
283
+ }
284
+ function handleModelNameChange(params) {
285
+ const { newName, globalStateSchema, setStateSchema } = params;
286
+ if (!!!globalStateSchema) {
287
+ setStateSchema(initializeModelSchema(newName), "global");
288
+ return;
289
+ }
290
+ updateModelSchemaNames(params);
291
+ }
292
+ function validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateValue) {
293
+ let stateObjectJson;
294
+ try {
295
+ stateObjectJson = JSON.parse(stateValue);
296
+ } catch (error) {
297
+ return [new Error("Invalid JSON object", { cause: error })];
298
+ }
299
+ const typeDefByName = indexTypeDefinitions(sharedSchemaDocumentNode);
300
+ const stateTypeName = stateTypeDefinitionNode.name.value;
301
+ if (!typeDefByName.has(stateTypeName)) return [/* @__PURE__ */ new Error(`State type "${stateTypeName}" was not found in sharedSchemaDocumentNode`)];
302
+ const inputSuffix = "Input";
303
+ const generatedInputDefs = generateInputTypesForObjectTree(stateTypeName, typeDefByName, inputSuffix);
304
+ const augmentedDoc = {
305
+ ...sharedSchemaDocumentNode,
306
+ definitions: [...sharedSchemaDocumentNode.definitions, ...generatedInputDefs]
307
+ };
308
+ let schema;
309
+ try {
310
+ schema = buildASTSchema(augmentedDoc, { assumeValidSDL: false });
311
+ } catch (e) {
312
+ return [new Error("Failed to build schema from SDL", { cause: e })];
313
+ }
314
+ const inputTypeName = `${stateTypeName}${inputSuffix}`;
315
+ const opDoc = parse(`query($v: ${inputTypeName}!) { __typename }`);
316
+ const op = getOperationAST(opDoc);
317
+ if (!op) return [/* @__PURE__ */ new Error("Failed to create validation operation AST")];
318
+ const { errors } = getVariableValues(schema, op.variableDefinitions ?? [], { v: stateObjectJson });
319
+ const recursiveTypeErrors = detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName);
320
+ const recursiveFieldNames = new Set(recursiveTypeErrors.map((e) => e.field));
321
+ const validationErrors = errors ? graphQLErrorsToStateValidationErrors(errors).filter((e) => {
322
+ if (e instanceof StateValidationError && e.kind === "NON_NULL") {
323
+ const rootField = e.path[0];
324
+ if (typeof rootField === "string" && recursiveFieldNames.has(rootField)) return false;
325
+ }
326
+ return true;
327
+ }) : [];
328
+ validationErrors.unshift(...recursiveTypeErrors);
329
+ const missingOptionalErrors = detectMissingOptionalFields(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateObjectJson);
330
+ validationErrors.push(...missingOptionalErrors);
331
+ return validationErrors;
332
+ }
333
+ /**
334
+ * Indexes object/input/enum/scalar/interface/union type definition nodes by name.
335
+ * Note: only AST definitions that have a "name" field are indexed.
336
+ */
337
+ function indexTypeDefinitions(doc) {
338
+ const map = /* @__PURE__ */ new Map();
339
+ for (const def of doc.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === Kind.ENUM_TYPE_DEFINITION || def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.INTERFACE_TYPE_DEFINITION || def.kind === Kind.UNION_TYPE_DEFINITION || def.kind === Kind.OBJECT_TYPE_EXTENSION || def.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION || def.kind === Kind.ENUM_TYPE_EXTENSION || def.kind === Kind.INTERFACE_TYPE_EXTENSION || def.kind === Kind.UNION_TYPE_EXTENSION) {
340
+ const name = def.name.value;
341
+ if (!map.has(name)) map.set(name, def);
342
+ }
343
+ return map;
344
+ }
345
+ /**
346
+ * Generates InputObjectTypeDefinitionNode(s) for a root object type and any nested
347
+ * object types reachable via fields, converting object references to their *Input equivalents*.
348
+ */
349
+ function generateInputTypesForObjectTree(rootObjectTypeName, typeDefByName, inputSuffix) {
350
+ const generated = /* @__PURE__ */ new Map();
351
+ const visiting = /* @__PURE__ */ new Set();
352
+ const ensureInputForObject = (objectTypeName) => {
353
+ const inputName = `${objectTypeName}${inputSuffix}`;
354
+ if (generated.has(inputName)) return;
355
+ if (visiting.has(objectTypeName)) return;
356
+ visiting.add(objectTypeName);
357
+ const def = typeDefByName.get(objectTypeName);
358
+ if (!def) throw new GraphQLError(`Unknown referenced type "${objectTypeName}"`);
359
+ if (def.kind !== Kind.OBJECT_TYPE_DEFINITION && def.kind !== Kind.OBJECT_TYPE_EXTENSION) throw new GraphQLError(`Type "${objectTypeName}" is not an object type; cannot generate input from kind "${def.kind}"`);
360
+ const objDef = def;
361
+ const inputFields = objDef.fields?.map((f) => {
362
+ return {
363
+ kind: Kind.INPUT_VALUE_DEFINITION,
364
+ name: f.name,
365
+ description: f.description,
366
+ directives: [],
367
+ type: convertOutputTypeNodeToInputTypeNode(f.type, typeDefByName, inputSuffix, ensureInputForObject),
368
+ defaultValue: void 0
369
+ };
370
+ }) ?? [];
371
+ const inputDef = {
372
+ kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
373
+ name: {
374
+ kind: Kind.NAME,
375
+ value: inputName
376
+ },
377
+ description: objDef.description,
378
+ directives: [],
379
+ fields: inputFields
380
+ };
381
+ generated.set(inputName, inputDef);
382
+ visiting.delete(objectTypeName);
383
+ };
384
+ ensureInputForObject(rootObjectTypeName);
385
+ return Array.from(generated.values());
386
+ }
387
+ function convertOutputTypeNodeToInputTypeNode(typeNode, typeDefByName, inputSuffix, ensureInputForObject) {
388
+ switch (typeNode.kind) {
389
+ case Kind.NON_NULL_TYPE: return {
390
+ kind: Kind.NON_NULL_TYPE,
391
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
392
+ };
393
+ case Kind.LIST_TYPE: return {
394
+ kind: Kind.LIST_TYPE,
395
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
396
+ };
397
+ case Kind.NAMED_TYPE: {
398
+ const named = typeNode;
399
+ const name = named.name.value;
400
+ const def = typeDefByName.get(name);
401
+ if (def?.kind === Kind.OBJECT_TYPE_DEFINITION || def?.kind === Kind.OBJECT_TYPE_EXTENSION) {
402
+ ensureInputForObject(name);
403
+ return {
404
+ kind: Kind.NAMED_TYPE,
405
+ name: {
406
+ kind: Kind.NAME,
407
+ value: `${name}${inputSuffix}`
408
+ }
409
+ };
410
+ }
411
+ if (!def || def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.ENUM_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) return named;
412
+ if (def.kind === Kind.INTERFACE_TYPE_DEFINITION || def.kind === Kind.UNION_TYPE_DEFINITION) throw new GraphQLError(`Type "${name}" (${def.kind}) cannot be used in an input type`);
413
+ throw new GraphQLError(`Unsupported named type "${name}" of kind "${def.kind}"`);
414
+ }
415
+ default: throw new GraphQLError(`Unsupported TypeNode kind: ${JSON.stringify(typeNode)}`);
416
+ }
417
+ }
418
+ var StateValidationError = class extends Error {
419
+ payload;
420
+ originalMessage;
421
+ constructor(payload, originalMessage) {
422
+ super(payload.kind);
423
+ this.name = "StateValidationError";
424
+ this.payload = payload;
425
+ this.originalMessage = originalMessage;
426
+ Object.setPrototypeOf(this, new.target.prototype);
427
+ }
428
+ get kind() {
429
+ return this.payload.kind;
430
+ }
431
+ get path() {
432
+ return this.payload.path;
433
+ }
434
+ get field() {
435
+ return this.payload.field;
436
+ }
437
+ };
438
+ function extractInputPath(message) {
439
+ const match = message.match(/at\s+"([^"]+)"/);
440
+ if (!match) return [];
441
+ const parts = match[1].split(".").filter(Boolean);
442
+ return (parts[0] === "v" ? parts.slice(1) : parts).map((p) => /^\d+$/.test(p) ? Number(p) : p);
443
+ }
444
+ const RE_MISSING_REQUIRED_FIELD = /Field "([^"]+)" of required type "([^"]+)" was not provided\./;
445
+ const RE_UNKNOWN_FIELD = /Field "([^"]+)" is not defined by type "([^"]+)"\.(?: Did you mean "([^"]+)"\?)?/;
446
+ function extractMissingRequiredField(message) {
447
+ const m = message.match(RE_MISSING_REQUIRED_FIELD);
448
+ if (!m) return null;
449
+ return {
450
+ field: m[1],
451
+ expectedType: m[2]
452
+ };
453
+ }
454
+ function extractUnknownField(message) {
455
+ const m = message.match(RE_UNKNOWN_FIELD);
456
+ if (!m) return null;
457
+ return {
458
+ field: m[1],
459
+ typeName: m[2],
460
+ didYouMean: m[3]
461
+ };
462
+ }
463
+ function lastFieldFromPath(path) {
464
+ for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "string") return path[i];
465
+ }
466
+ function extractExpectedType(message) {
467
+ let m = message.match(/Expected non-nullable type "([^"]+)"/);
468
+ if (m?.[1]) return m[1];
469
+ m = message.match(/Expected type "([^"]+)"/);
470
+ if (m?.[1]) return m[1];
471
+ m = message.match(/;\s*([_A-Za-z][_0-9A-Za-z]*)\s+cannot represent/i);
472
+ if (m?.[1]) return m[1];
473
+ }
474
+ function graphQLErrorsToStateValidationErrors(errors) {
475
+ const out = [];
476
+ for (const e of errors) {
477
+ const originalMessage = e.message;
478
+ const missing = extractMissingRequiredField(originalMessage);
479
+ if (missing) {
480
+ out.push(new StateValidationError({
481
+ kind: "MISSING",
482
+ path: [missing.field],
483
+ field: missing.field,
484
+ expectedType: missing.expectedType
485
+ }, originalMessage));
486
+ continue;
487
+ }
488
+ const unknown = extractUnknownField(originalMessage);
489
+ if (unknown) {
490
+ out.push(new StateValidationError({
491
+ kind: "UNKNOWN_FIELD",
492
+ path: [unknown.field],
493
+ field: unknown.field,
494
+ didYouMean: unknown.didYouMean
495
+ }, originalMessage));
496
+ continue;
497
+ }
498
+ const path = extractInputPath(originalMessage);
499
+ const field = lastFieldFromPath(path) ?? "value";
500
+ const expectedType = extractExpectedType(originalMessage);
501
+ if (originalMessage.includes("Expected non-nullable type") && originalMessage.includes("not to be null")) {
502
+ out.push(new StateValidationError({
503
+ kind: "NON_NULL",
504
+ path,
505
+ field,
506
+ expectedType
507
+ }, originalMessage));
508
+ continue;
509
+ }
510
+ if (originalMessage.includes("cannot represent") || originalMessage.includes("Expected type")) {
511
+ out.push(new StateValidationError({
512
+ kind: "TYPE",
513
+ path,
514
+ field,
515
+ expectedType,
516
+ details: originalMessage
517
+ }, originalMessage));
518
+ continue;
519
+ }
520
+ out.push(new StateValidationError({
521
+ kind: "TYPE",
522
+ path,
523
+ field,
524
+ details: originalMessage
525
+ }, originalMessage));
526
+ }
527
+ return out;
528
+ }
529
+ /**
530
+ * Finds all fields defined in the schema that are missing from the state object.
531
+ * Returns information about each missing field including whether it's required.
532
+ */
533
+ function findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value, basePath = []) {
534
+ let stateObjectJson;
535
+ try {
536
+ stateObjectJson = typeof value === "string" ? JSON.parse(value) : value;
537
+ } catch {
538
+ return [];
539
+ }
540
+ const typeByName = indexObjectTypes(sharedSchemaDocumentNode);
541
+ const missingFields = [];
542
+ for (const field of rootTypeNode.fields ?? []) {
543
+ const fieldName = field.name.value;
544
+ const fieldPath = [...basePath, fieldName];
545
+ const isRequired = field.type.kind === Kind.NON_NULL_TYPE;
546
+ const underlyingType = isRequired ? field.type.type : field.type;
547
+ if (!(fieldName in stateObjectJson)) {
548
+ missingFields.push({
549
+ fieldName,
550
+ path: fieldPath,
551
+ isRequired,
552
+ type: underlyingType
553
+ });
554
+ continue;
555
+ }
556
+ const namedType = unwrapNamedType(field.type);
557
+ const childType = namedType ? typeByName.get(namedType) : void 0;
558
+ if (childType && typeof stateObjectJson[fieldName] === "object" && stateObjectJson[fieldName] !== null && !Array.isArray(stateObjectJson[fieldName])) {
559
+ const nestedMissing = findMissingFields(sharedSchemaDocumentNode, childType, stateObjectJson[fieldName], fieldPath);
560
+ missingFields.push(...nestedMissing);
561
+ }
562
+ }
563
+ return missingFields;
564
+ }
565
+ /**
566
+ * Detects optional fields defined in the schema that are missing from the state object.
567
+ * Returns StateValidationError[] for each missing optional field.
568
+ */
569
+ function detectMissingOptionalFields(sharedSchemaDocumentNode, rootTypeNode, value) {
570
+ return findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value).filter((field) => !field.isRequired).map((field) => new StateValidationError({
571
+ kind: "MISSING_OPTIONAL",
572
+ path: field.path,
573
+ field: field.fieldName,
574
+ expectedType: typeNodeToString(field.type)
575
+ }));
576
+ }
577
+ /**
578
+ * Detects fields that have recursive types (types that reference themselves directly or indirectly).
579
+ * Returns a RECURSIVE_TYPE error for each field that contains a recursive type.
580
+ */
581
+ function detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName) {
582
+ const errors = [];
583
+ for (const field of stateTypeDefinitionNode.fields ?? []) {
584
+ const fieldName = field.name.value;
585
+ const namedTypeName = getNamedTypeName(field.type);
586
+ if (!namedTypeName) continue;
587
+ if (isRecursiveType(namedTypeName, typeDefByName, /* @__PURE__ */ new Set())) errors.push(new StateValidationError({
588
+ kind: "RECURSIVE_TYPE",
589
+ path: [fieldName],
590
+ field: fieldName,
591
+ typeName: namedTypeName
592
+ }));
593
+ }
594
+ return errors;
595
+ }
596
+ /**
597
+ * Gets the named type name from a TypeNode, unwrapping NonNull and List types.
598
+ */
599
+ function getNamedTypeName(typeNode) {
600
+ if (typeNode.kind === Kind.NAMED_TYPE) return typeNode.name.value;
601
+ if (typeNode.kind === Kind.NON_NULL_TYPE || typeNode.kind === Kind.LIST_TYPE) return getNamedTypeName(typeNode.type);
602
+ return null;
603
+ }
604
+ /**
605
+ * Checks if a type is recursive (references itself directly or indirectly through required fields).
606
+ */
607
+ function isRecursiveType(typeName, typeDefByName, visitedTypes) {
608
+ if (visitedTypes.has(typeName)) return true;
609
+ const typeDef = typeDefByName.get(typeName);
610
+ if (!typeDef || typeDef.kind !== Kind.OBJECT_TYPE_DEFINITION) return false;
611
+ visitedTypes.add(typeName);
612
+ for (const field of typeDef.fields ?? []) {
613
+ if (field.type.kind !== Kind.NON_NULL_TYPE) continue;
614
+ const innerType = field.type.type;
615
+ let fieldTypeName = null;
616
+ if (innerType.kind === Kind.NAMED_TYPE) fieldTypeName = innerType.name.value;
617
+ else if (innerType.kind === Kind.LIST_TYPE) fieldTypeName = getNamedTypeName(innerType);
618
+ if (fieldTypeName && isRecursiveType(fieldTypeName, typeDefByName, visitedTypes)) return true;
619
+ }
620
+ visitedTypes.delete(typeName);
621
+ return false;
622
+ }
623
+ /**
624
+ * Converts a TypeNode to its string representation (e.g., "String", "Int!", "[String]!")
625
+ */
626
+ function typeNodeToString(typeNode) {
627
+ switch (typeNode.kind) {
628
+ case Kind.NAMED_TYPE: return typeNode.name.value;
629
+ case Kind.NON_NULL_TYPE: return `${typeNodeToString(typeNode.type)}!`;
630
+ case Kind.LIST_TYPE: return `[${typeNodeToString(typeNode.type)}]`;
631
+ }
632
+ }
633
+ function indexObjectTypes(doc) {
634
+ const map = /* @__PURE__ */ new Map();
635
+ for (const def of doc.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) map.set(def.name.value, def);
636
+ return map;
637
+ }
638
+ function unwrapNamedType(typeNode) {
639
+ if (typeNode.kind === Kind.NAMED_TYPE) return typeNode.name.value;
640
+ if (typeNode.kind === Kind.NON_NULL_TYPE) return unwrapNamedType(typeNode.type);
641
+ if (typeNode.kind === Kind.LIST_TYPE) return unwrapNamedType(typeNode.type);
642
+ }
643
+ //#endregion
644
+ //#region editors/document-model-editor/utils/linting.ts
645
+ function ensureDocumentContainsNodeWithNameAndType(doc, nodeName, nodeType) {
646
+ const parsedDoc = safeParseSdl(doc);
647
+ if (!parsedDoc) return true;
648
+ return parsedDoc.definitions.some((def) => {
649
+ return def.kind === Kind[nodeType] && "name" in def && def.name?.value === nodeName;
650
+ });
651
+ }
652
+ function createNodeTypeAndNameDiagnostic(doc, errorMessage) {
653
+ const parsedDoc = safeParseSdl(doc);
654
+ if (!parsedDoc) return void 0;
655
+ const firstNode = parsedDoc.definitions[0];
656
+ const nameNode = "name" in firstNode ? firstNode.name : null;
657
+ return {
658
+ from: nameNode?.loc?.start ?? firstNode.loc?.start ?? 0,
659
+ to: nameNode?.loc?.end ?? firstNode.loc?.end ?? 0,
660
+ severity: "error",
661
+ message: errorMessage
662
+ };
663
+ }
664
+ function ensureValidStateSchemaName(doc, modelName, scope) {
665
+ if (!safeParseSdl(doc)) return [];
666
+ const requiredTypeName = makeStateSchemaNameForScope(modelName, scope);
667
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `${sentenceCase(scope)} state schema must be named ${requiredTypeName}`)].filter((d) => d !== void 0);
668
+ return [];
669
+ }
670
+ function ensureValidOperationSchemaInputName(doc, operationName) {
671
+ if (!doc || !safeParseSdl(doc)) return [];
672
+ const requiredTypeName = `${pascalCase(operationName)}Input`;
673
+ 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);
674
+ return [];
675
+ }
676
+ //#endregion
677
+ //#region editors/document-model-editor/components/button.tsx
678
+ const Button = forwardRef((props, ref) => {
679
+ const { className, ...rest } = props;
680
+ return /* @__PURE__ */ jsx("button", {
681
+ ref,
682
+ ...rest,
683
+ 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)
684
+ });
685
+ });
686
+ //#endregion
687
+ //#region editors/document-model-editor/components/divider.tsx
688
+ function Divider({ className, size = "sm", margin = "md" }) {
689
+ function getSize() {
690
+ if (size === "sm") return "h-px";
691
+ if (size === "md") return "h-1";
692
+ return "h-1.5";
693
+ }
694
+ function getMargin() {
695
+ if (margin === "sm") return "my-4";
696
+ if (margin === "md") return "my-6";
697
+ return "my-8";
698
+ }
699
+ const sizeClass = getSize();
700
+ const marginClass = getMargin();
701
+ return /* @__PURE__ */ jsx("div", { className: twMerge("bg-secondary", sizeClass, marginClass, className) });
702
+ }
703
+ //#endregion
704
+ //#region editors/document-model-editor/schemas/inputs.ts
705
+ const isUppercase = (value) => !/\p{Ll}/u.test(value);
706
+ const isLowercase = (value) => !/\p{Lu}/u.test(value);
707
+ function createNameSchema(options = {}) {
708
+ const { required = false, allowEmpty = false, unique = [] } = options;
709
+ const baseSchema = allowEmpty ? z.string() : z.string().min(1);
710
+ const uniqueRefinement = baseSchema.refine((value) => {
711
+ if (!value && allowEmpty) return true;
712
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
713
+ }, { message: "Item with this name already exists" });
714
+ if (!required) return unique.length > 0 ? z.string().optional().refine((value) => {
715
+ if (value === void 0) return true;
716
+ if (!value && allowEmpty) return true;
717
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
718
+ }, { message: "Item with this name already exists" }) : z.string().optional();
719
+ return unique.length > 0 ? uniqueRefinement : baseSchema;
720
+ }
721
+ function createConstantCaseSchema(options = {}) {
722
+ return createNameSchema(options).transform((value) => value ? value.toUpperCase() : value).refine((value) => !value || isUppercase(value), { message: "Must be uppercase" });
723
+ }
724
+ function createLowercaseSnakeCaseSchema(options = {}) {
725
+ return createNameSchema(options).transform((value) => value ? value.toLowerCase() : value).refine((value) => !value || isLowercase(value), { message: "Must be lowercase" });
726
+ }
727
+ function toLowercaseSnakeCase(value, options = {}) {
728
+ return createLowercaseSnakeCaseSchema(options).parse(snakeCase(value));
729
+ }
730
+ function toConstantCase(value, options = {}) {
731
+ return createConstantCaseSchema(options).parse(constantCase(value));
732
+ }
733
+ z.object({
734
+ name: createNameSchema({ allowEmpty: true }),
735
+ website: z.union([z.url(), z.literal("")]).optional().default("")
736
+ }).default({
737
+ name: "",
738
+ website: ""
739
+ });
740
+ //#endregion
741
+ //#region editors/document-model-editor/context/form-context.ts
742
+ const FormFieldContext = React.createContext({});
743
+ const FormItemContext = React.createContext({});
744
+ //#endregion
745
+ //#region editors/document-model-editor/hooks/useFormField.ts
746
+ const useFormField = () => {
747
+ const fieldContext = React.useContext(FormFieldContext);
748
+ const itemContext = React.useContext(FormItemContext);
749
+ const { getFieldState, formState } = useFormContext();
750
+ const fieldState = getFieldState(fieldContext.name, formState);
751
+ if (!fieldContext) throw new Error("useFormField should be used within <FormField>");
752
+ const { id } = itemContext;
753
+ return {
754
+ id,
755
+ name: fieldContext.name,
756
+ formItemId: `${id}-form-item`,
757
+ formDescriptionId: `${id}-form-item-description`,
758
+ formMessageId: `${id}-form-item-message`,
759
+ ...fieldState
760
+ };
761
+ };
762
+ //#endregion
763
+ //#region editors/document-model-editor/components/label.tsx
764
+ const labelVariants = cva("text-sm leading-none font-medium peer-disabled:disabled-effect");
765
+ const Label = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(LabelPrimitive.Root, {
766
+ ref,
767
+ className: twMerge(labelVariants(), className),
768
+ ...props
769
+ }));
770
+ Label.displayName = LabelPrimitive.Root.displayName;
771
+ //#endregion
772
+ //#region editors/document-model-editor/components/form.tsx
773
+ const Form = FormProvider;
774
+ const FormField = ({ ...props }) => {
775
+ return /* @__PURE__ */ jsx(FormFieldContext.Provider, {
776
+ value: { name: props.name },
777
+ children: /* @__PURE__ */ jsx(Controller, { ...props })
778
+ });
779
+ };
780
+ const FormItem = React$1.forwardRef(({ className, ...props }, ref) => {
781
+ const id = React$1.useId();
782
+ return /* @__PURE__ */ jsx(FormItemContext.Provider, {
783
+ value: { id },
784
+ children: /* @__PURE__ */ jsx("div", {
785
+ ref,
786
+ className,
787
+ ...props
788
+ })
789
+ });
790
+ });
791
+ FormItem.displayName = "FormItem";
792
+ const FormLabel = React$1.forwardRef(({ className, ...props }, ref) => {
793
+ const { error, formItemId } = useFormField();
794
+ return /* @__PURE__ */ jsx(Label, {
795
+ ref,
796
+ className: twMerge(error && "text-destructive", className),
797
+ htmlFor: formItemId,
798
+ ...props
799
+ });
800
+ });
801
+ FormLabel.displayName = "FormLabel";
802
+ const FormControl = React$1.forwardRef(({ ...props }, ref) => {
803
+ const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
804
+ return /* @__PURE__ */ jsx(Slot, {
805
+ ref,
806
+ id: formItemId,
807
+ "aria-describedby": !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`,
808
+ "aria-invalid": !!error,
809
+ ...props
810
+ });
811
+ });
812
+ FormControl.displayName = "FormControl";
813
+ const FormDescription = React$1.forwardRef(({ className, ...props }, ref) => {
814
+ const { formDescriptionId } = useFormField();
815
+ return /* @__PURE__ */ jsx("p", {
816
+ ref,
817
+ id: formDescriptionId,
818
+ className: twMerge("text-sm text-foreground", className),
819
+ ...props
820
+ });
821
+ });
822
+ FormDescription.displayName = "FormDescription";
823
+ const FormMessage = React$1.forwardRef(({ className, children, ...props }, ref) => {
824
+ const { error, formMessageId } = useFormField();
825
+ const body = error ? String(error.message) : children;
826
+ if (!body) return null;
827
+ return /* @__PURE__ */ jsx("p", {
828
+ ref,
829
+ id: formMessageId,
830
+ className: twMerge("text-sm font-medium text-destructive", className),
831
+ ...props,
832
+ children: body
833
+ });
834
+ });
835
+ FormMessage.displayName = "FormMessage";
836
+ //#endregion
837
+ //#region editors/document-model-editor/components/text-area.tsx
838
+ const Textarea = forwardRef(({ className, ...props }, ref) => {
839
+ const textareaRef = useRef(null);
840
+ const adjustHeight = useCallback((textarea) => {
841
+ textarea.style.height = "auto";
842
+ const newHeight = Math.max(textarea.scrollHeight, textarea.offsetHeight);
843
+ textarea.style.height = `${newHeight}px`;
844
+ }, []);
845
+ const handleInput = useCallback((e) => {
846
+ adjustHeight(e.currentTarget);
847
+ }, [adjustHeight]);
848
+ React$1.useEffect(() => {
849
+ if (textareaRef.current) adjustHeight(textareaRef.current);
850
+ }, [adjustHeight]);
851
+ useImperativeHandle(ref, () => ({
852
+ focus: () => textareaRef.current?.focus(),
853
+ element: textareaRef.current
854
+ }));
855
+ return /* @__PURE__ */ jsx("textarea", {
856
+ ...props,
857
+ 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),
858
+ ref: textareaRef,
859
+ onInput: handleInput
860
+ });
861
+ });
862
+ Textarea.displayName = "Textarea";
863
+ //#endregion
864
+ //#region editors/document-model-editor/components/text-field.tsx
865
+ const TextField = forwardRef(({ name, value, onSubmit, label, placeholder, unique, className = "", rows = 1, focusOnMount = false, required = false, allowEmpty = false, shouldReset = false, onChange }, ref) => {
866
+ const textareaRef = useRef(null);
867
+ const id = useId();
868
+ useEffect(() => {
869
+ if (focusOnMount && textareaRef.current) textareaRef.current.focus();
870
+ }, [focusOnMount]);
871
+ const fieldSchema = z.object({ [name]: createNameSchema({
872
+ required,
873
+ allowEmpty,
874
+ unique
875
+ }) });
876
+ const form = useForm({
877
+ resolver: zodResolver(fieldSchema),
878
+ defaultValues: { [name]: value ?? "" }
879
+ });
880
+ const handleSubmit = useCallback((values) => {
881
+ const newValue = values[name];
882
+ if (newValue === void 0 || value === newValue) return;
883
+ onSubmit(newValue);
884
+ if (shouldReset) form.reset({ [name]: "" });
885
+ }, [
886
+ name,
887
+ value,
888
+ onSubmit,
889
+ form,
890
+ shouldReset
891
+ ]);
892
+ const handleBlur = useCallback(async () => {
893
+ const currentValue = form.getValues()[name] ?? "";
894
+ if (value === null || value === void 0) {
895
+ if (!currentValue || currentValue.trim() === "") return;
896
+ }
897
+ if (compareStringsWithoutWhitespace(currentValue, value ?? "")) return;
898
+ try {
899
+ await form.trigger();
900
+ if (form.formState.isValid) await form.handleSubmit(handleSubmit)();
901
+ } catch (_e) {}
902
+ }, [
903
+ form,
904
+ handleSubmit,
905
+ name,
906
+ value
907
+ ]);
908
+ const onEnterKeyDown = useCallback((e) => {
909
+ if (e.key === "Enter") {
910
+ e.preventDefault();
911
+ e.target.blur();
912
+ }
913
+ }, []);
914
+ const handleChange = useCallback((e) => {
915
+ const newValue = e.target.value;
916
+ onChange?.(newValue);
917
+ }, [onChange]);
918
+ useImperativeHandle(ref, () => ({ focus: () => textareaRef.current?.focus() }));
919
+ useEffect(() => {
920
+ form.reset({ [name]: value ?? "" });
921
+ }, [
922
+ form,
923
+ name,
924
+ value
925
+ ]);
926
+ return /* @__PURE__ */ jsx(Form, {
927
+ ...form,
928
+ children: /* @__PURE__ */ jsx(FormField, {
929
+ control: form.control,
930
+ name,
931
+ render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
932
+ className: "grid h-full grid-rows-[auto,1fr] gap-2 overflow-visible",
933
+ children: [
934
+ !!label && /* @__PURE__ */ jsx(FormLabel, {
935
+ htmlFor: name,
936
+ className: "text-sm font-medium text-foreground",
937
+ children: label
938
+ }),
939
+ /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Textarea, {
940
+ ...field,
941
+ id,
942
+ name,
943
+ ref: (node) => {
944
+ if (node) {
945
+ field.ref(node.element);
946
+ textareaRef.current = node;
947
+ }
948
+ },
949
+ placeholder,
950
+ onBlur: () => void handleBlur(),
951
+ onChange: (e) => {
952
+ field.onChange(e);
953
+ handleChange(e);
954
+ },
955
+ onKeyDown: onEnterKeyDown,
956
+ rows,
957
+ className
958
+ }) }),
959
+ /* @__PURE__ */ jsx(FormMessage, {})
960
+ ]
961
+ })
962
+ })
963
+ });
964
+ });
965
+ TextField.displayName = "TextField";
966
+ z.object({
967
+ name: z.string(),
968
+ documentType: z.string(),
969
+ extension: z.string().optional().default(""),
970
+ description: z.string(),
971
+ authorName: z.string(),
972
+ authorWebsite: z.string()
973
+ });
974
+ function ModelMetadata(props) {
975
+ return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(ModelNameForm, { ...props }), /* @__PURE__ */ jsx("div", {
976
+ className: "flex h-full flex-col gap-4",
977
+ children: /* @__PURE__ */ jsxs("div", {
978
+ className: "grid flex-1 grid-cols-3 items-start gap-4",
979
+ children: [/* @__PURE__ */ jsxs("div", {
980
+ className: "col-span-2 flex h-full flex-col gap-4",
981
+ children: [/* @__PURE__ */ jsx("div", {
982
+ className: "shrink-0",
983
+ children: /* @__PURE__ */ jsx(DocumentTypeForm, { ...props })
984
+ }), /* @__PURE__ */ jsx("div", {
985
+ className: "min-h-0 flex-1",
986
+ children: /* @__PURE__ */ jsx(DescriptionForm, { ...props })
987
+ })]
988
+ }), /* @__PURE__ */ jsxs("div", {
989
+ className: "col-span-1 flex flex-col gap-4",
990
+ children: [
991
+ /* @__PURE__ */ jsx(AuthorNameForm, { ...props }),
992
+ /* @__PURE__ */ jsx(AuthorWebsiteForm, { ...props }),
993
+ /* @__PURE__ */ jsx(ModelExtensionForm, { ...props })
994
+ ]
995
+ })]
996
+ })
997
+ })] });
998
+ }
999
+ function ModelNameForm(props) {
1000
+ const { name, globalStateSchema, localStateSchema, setModelName, setStateSchema } = props;
1001
+ const onSubmit = useCallback((newName) => {
1002
+ if (name === newName) return;
1003
+ setModelName(newName);
1004
+ if (!!!globalStateSchema) {
1005
+ const initialSchemaDoc = makeInitialSchemaDoc(newName, "global");
1006
+ setStateSchema(initialSchemaDoc, "global");
1007
+ return;
1008
+ }
1009
+ const newSchema = renameSchemaType(globalStateSchema, name, newName, "global");
1010
+ setStateSchema(newSchema, "global");
1011
+ if (localStateSchema) {
1012
+ const newLocalStateSchema = renameSchemaType(localStateSchema, name, newName, "local");
1013
+ setStateSchema(newLocalStateSchema, "local");
1014
+ }
1015
+ handleModelNameChange({
1016
+ oldName: name,
1017
+ newName,
1018
+ globalStateSchema,
1019
+ localStateSchema,
1020
+ setStateSchema
1021
+ });
1022
+ }, [
1023
+ name,
1024
+ globalStateSchema,
1025
+ localStateSchema,
1026
+ setStateSchema,
1027
+ setModelName
1028
+ ]);
1029
+ return /* @__PURE__ */ jsx(TextField, {
1030
+ name: "name",
1031
+ value: name,
1032
+ onSubmit,
1033
+ placeholder: "Model name",
1034
+ className: "border-none pl-0 text-xl font-bold text-foreground",
1035
+ required: true,
1036
+ focusOnMount: true
1037
+ });
1038
+ }
1039
+ function DocumentTypeForm(props) {
1040
+ const { documentType, setModelId } = props;
1041
+ return /* @__PURE__ */ jsx(TextField, {
1042
+ label: "Document Type *",
1043
+ name: "powerhouse/document-model",
1044
+ value: documentType,
1045
+ onSubmit: setModelId,
1046
+ placeholder: "Document Type",
1047
+ required: true
1048
+ });
1049
+ }
1050
+ function ModelExtensionForm(props) {
1051
+ const { extension, setModelExtension } = props;
1052
+ return /* @__PURE__ */ jsx(TextField, {
1053
+ name: "extension",
1054
+ value: extension,
1055
+ onSubmit: setModelExtension,
1056
+ label: "Model Extension",
1057
+ placeholder: "Example .phdm",
1058
+ allowEmpty: true
1059
+ });
1060
+ }
1061
+ function DescriptionForm(props) {
1062
+ const { description, setModelDescription } = props;
1063
+ return /* @__PURE__ */ jsx(TextField, {
1064
+ name: "description",
1065
+ label: "Model Description",
1066
+ value: description,
1067
+ onSubmit: setModelDescription,
1068
+ placeholder: "Describe your document to others",
1069
+ allowEmpty: true,
1070
+ className: "h-full"
1071
+ });
1072
+ }
1073
+ function AuthorNameForm(props) {
1074
+ const { authorName, setAuthorName } = props;
1075
+ return /* @__PURE__ */ jsx(TextField, {
1076
+ name: "authorName",
1077
+ value: authorName,
1078
+ onSubmit: setAuthorName,
1079
+ label: "Author Name",
1080
+ placeholder: "Username or organisation",
1081
+ allowEmpty: true
1082
+ });
1083
+ }
1084
+ function AuthorWebsiteForm(props) {
1085
+ const { authorWebsite, setAuthorWebsite } = props;
1086
+ return /* @__PURE__ */ jsx(TextField, {
1087
+ name: "authorWebsite",
1088
+ value: authorWebsite,
1089
+ label: "Website URL",
1090
+ onSubmit: (newAuthorWebsite) => {
1091
+ if (!!authorWebsite && !newAuthorWebsite) return;
1092
+ setAuthorWebsite(newAuthorWebsite);
1093
+ },
1094
+ placeholder: "https://www.powerhouse.inc/",
1095
+ allowEmpty: true
1096
+ });
1097
+ }
1098
+ //#endregion
1099
+ //#region editors/document-model-editor/components/module-form.tsx
1100
+ function ModuleForm({ module, onAddModule, updateModuleName, modules = [] }) {
1101
+ const isEdit = !!module;
1102
+ const moduleNames = modules.map((m) => m.name);
1103
+ const handleSubmit = async (name) => {
1104
+ const formattedName = toLowercaseSnakeCase(name);
1105
+ if (!formattedName.length) return;
1106
+ if (isEdit) {
1107
+ if (formattedName !== module.name) updateModuleName(module.id, formattedName);
1108
+ } else await onAddModule(formattedName);
1109
+ };
1110
+ return /* @__PURE__ */ jsx(TextField, {
1111
+ name: "name",
1112
+ label: isEdit ? "Module name *" : "Add module *",
1113
+ value: module?.name,
1114
+ onSubmit: (name) => void handleSubmit(name),
1115
+ placeholder: "Add module",
1116
+ unique: moduleNames,
1117
+ shouldReset: !isEdit,
1118
+ required: true
1119
+ }, module?.id ?? "new");
1120
+ }
1121
+ //#endregion
1122
+ //#region editors/document-model-editor/components/operation-form.tsx
1123
+ function OperationForm({ operation, module, focusOnMount, allOperationNames, onAddOperationAndInitialSchema, updateOperationName, deleteOperation }) {
1124
+ const isEdit = !!operation;
1125
+ const handleSubmit = async (name) => {
1126
+ if (isEdit && name === "") {
1127
+ deleteOperation(operation.id);
1128
+ return;
1129
+ }
1130
+ const formattedName = toConstantCase(name);
1131
+ if (isEdit) {
1132
+ if (formattedName !== operation.name) updateOperationName(operation.id, formattedName);
1133
+ } else await onAddOperationAndInitialSchema(module.id, formattedName);
1134
+ };
1135
+ const handleChange = (value) => {
1136
+ if (isEdit && value === "") deleteOperation(operation.id);
1137
+ };
1138
+ return /* @__PURE__ */ jsx(TextField, {
1139
+ name: "name",
1140
+ value: operation?.name,
1141
+ label: isEdit ? "Operation name *" : "Add operation *",
1142
+ onSubmit: (name) => void handleSubmit(name),
1143
+ onChange: handleChange,
1144
+ placeholder: "Add operation",
1145
+ required: !isEdit,
1146
+ allowEmpty: !isEdit,
1147
+ shouldReset: !isEdit,
1148
+ focusOnMount,
1149
+ unique: allOperationNames
1150
+ });
1151
+ }
1152
+ //#endregion
1153
+ //#region editors/document-model-editor/components/operation-description-form.tsx
1154
+ function OperationDescriptionForm({ operation, focusOnMount, setOperationDescription }) {
1155
+ const textFieldRef = useRef(null);
1156
+ useEffect(() => {
1157
+ if (focusOnMount && textFieldRef.current) textFieldRef.current.focus();
1158
+ }, [focusOnMount]);
1159
+ return /* @__PURE__ */ jsx(TextField, {
1160
+ ref: textFieldRef,
1161
+ name: "description",
1162
+ value: operation.description,
1163
+ onSubmit: (newDescription) => setOperationDescription(operation.id, newDescription),
1164
+ label: "Operation description",
1165
+ allowEmpty: true,
1166
+ placeholder: "Operation Description"
1167
+ });
1168
+ }
1169
+ //#endregion
1170
+ //#region editors/document-model-editor/components/operation-error-form.tsx
1171
+ function OperationErrorForm({ operation, error, focusOnMount, onSubmit, onAddOperationError, deleteOperationError, setOperationErrorName }) {
1172
+ const textFieldRef = useRef(null);
1173
+ const isEdit = !!error;
1174
+ const allOperationErrorNames = operation.errors.map((o) => o.name).filter((n) => n !== null);
1175
+ const handleSubmit = (name) => {
1176
+ if (isEdit && name === "") {
1177
+ deleteOperationError(error.id);
1178
+ return;
1179
+ }
1180
+ const formattedName = pascalCase(name);
1181
+ if (isEdit) setOperationErrorName(operation.id, error.id, formattedName);
1182
+ else onAddOperationError(operation.id, formattedName);
1183
+ onSubmit?.();
1184
+ };
1185
+ const handleChange = (value) => {
1186
+ if (isEdit && value === "") deleteOperationError(error.id);
1187
+ };
1188
+ return /* @__PURE__ */ jsx(TextField, {
1189
+ ref: textFieldRef,
1190
+ name: "name",
1191
+ value: error?.name,
1192
+ onSubmit: handleSubmit,
1193
+ onChange: handleChange,
1194
+ placeholder: "Add exception",
1195
+ required: !isEdit,
1196
+ allowEmpty: !isEdit,
1197
+ shouldReset: !isEdit,
1198
+ unique: allOperationErrorNames,
1199
+ focusOnMount
1200
+ });
1201
+ }
1202
+ //#endregion
1203
+ //#region editors/document-model-editor/components/operation-errors.tsx
1204
+ function OperationErrors({ operation, addOperationError, deleteOperationError, setOperationErrorName }) {
1205
+ const addErrorFormId = useId();
1206
+ const [shouldFocusAddForm, setShouldFocusAddForm] = useState(false);
1207
+ const onAddOperationError = useCallback(async (operationId, error) => {
1208
+ const errorId = await addOperationError(operationId, error);
1209
+ if (errorId) setShouldFocusAddForm(true);
1210
+ return errorId;
1211
+ }, [addOperationError, setShouldFocusAddForm]);
1212
+ const onAddOperationErrorSubmit = useCallback(() => setShouldFocusAddForm(false), [setShouldFocusAddForm]);
1213
+ return /* @__PURE__ */ jsxs("ul", {
1214
+ className: "ml-4 list-disc",
1215
+ children: [operation.errors.map((error) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
1216
+ error,
1217
+ operation,
1218
+ onAddOperationError,
1219
+ deleteOperationError,
1220
+ setOperationErrorName
1221
+ }) }, error.id)), /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
1222
+ operation,
1223
+ onAddOperationError,
1224
+ deleteOperationError,
1225
+ setOperationErrorName,
1226
+ focusOnMount: shouldFocusAddForm,
1227
+ onSubmit: onAddOperationErrorSubmit
1228
+ }, `${addErrorFormId}-${shouldFocusAddForm}`) })]
1229
+ });
1230
+ }
1231
+ //#endregion
1232
+ //#region editors/document-model-editor/components/operation.tsx
1233
+ const GraphqlEditor = lazy(() => import("./graphql-editor-CpcGaYmP.js"));
1234
+ function Operation(props) {
1235
+ const { operation, module, allOperationNames, lastCreatedOperationId, onAddOperationAndInitialSchema, updateOperationName, deleteOperation, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
1236
+ const noInputRequired = isEmptyOperationSchema(operation.schema);
1237
+ const handleToggleNoInput = useCallback((checked) => toggleNoInputRequired(operation.id, checked), [operation.id, toggleNoInputRequired]);
1238
+ const handleUpdateDocument = useCallback((newDoc) => updateOperationSchema(operation.id, newDoc), [operation.id, updateOperationSchema]);
1239
+ const customLinter = useCallback((doc) => operation.name ? ensureValidOperationSchemaInputName(doc, operation.name) : [], [operation.name]);
1240
+ return /* @__PURE__ */ jsxs("div", {
1241
+ className: "mt-4 grid grid-cols-2 gap-x-12",
1242
+ style: {
1243
+ gridTemplateAreas: `
1244
+ "left editor"
1245
+ "errors editor"
1246
+ `,
1247
+ gridTemplateRows: "auto 1fr"
1248
+ },
1249
+ children: [
1250
+ /* @__PURE__ */ jsxs("div", {
1251
+ className: "flex flex-col gap-2",
1252
+ style: { gridArea: "left" },
1253
+ children: [/* @__PURE__ */ jsx(OperationForm, {
1254
+ operation,
1255
+ onAddOperationAndInitialSchema,
1256
+ updateOperationName,
1257
+ deleteOperation,
1258
+ module,
1259
+ allOperationNames
1260
+ }), /* @__PURE__ */ jsx(OperationDescriptionForm, {
1261
+ operation,
1262
+ focusOnMount: operation.id === lastCreatedOperationId,
1263
+ setOperationDescription
1264
+ })]
1265
+ }),
1266
+ /* @__PURE__ */ jsxs("div", {
1267
+ className: "relative top-8",
1268
+ style: { gridArea: "editor" },
1269
+ children: [/* @__PURE__ */ jsxs("label", {
1270
+ className: "mb-2 flex cursor-pointer items-center gap-2",
1271
+ children: [/* @__PURE__ */ jsx("input", {
1272
+ type: "checkbox",
1273
+ checked: noInputRequired,
1274
+ onChange: (e) => handleToggleNoInput(e.target.checked),
1275
+ className: "size-4 rounded-sm border-border"
1276
+ }), /* @__PURE__ */ jsx("span", {
1277
+ className: "text-sm text-foreground",
1278
+ children: "Operation with no inputs"
1279
+ })]
1280
+ }), !noInputRequired && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(GraphqlEditor, {
1281
+ doc: operation.schema ?? "",
1282
+ updateDocumentInModel: handleUpdateDocument,
1283
+ customLinter
1284
+ }) })]
1285
+ }),
1286
+ /* @__PURE__ */ jsxs("div", {
1287
+ style: { gridArea: "errors" },
1288
+ children: [/* @__PURE__ */ jsx("h3", {
1289
+ className: "my-2 text-sm font-medium text-foreground",
1290
+ children: "Reducer Exceptions"
1291
+ }), /* @__PURE__ */ jsx(OperationErrors, {
1292
+ operation,
1293
+ addOperationError,
1294
+ deleteOperationError,
1295
+ setOperationErrorName
1296
+ })]
1297
+ })
1298
+ ]
1299
+ });
1300
+ }
1301
+ //#endregion
1302
+ //#region editors/document-model-editor/components/operations.tsx
1303
+ function Operations({ module, allOperations, shouldFocusNewOperation, updateOperationName, deleteOperation, addOperationAndInitialSchema, addOperationError, deleteOperationError, setOperationErrorName, updateOperationSchema, setOperationDescription, toggleNoInputRequired }) {
1304
+ const [lastCreatedOperationId, setLastCreatedOperationId] = useState(null);
1305
+ const addOperationFormId = useId();
1306
+ const allOperationNames = allOperations.map((o) => o.name).filter((n) => n !== null);
1307
+ const onAddOperationAndInitialSchema = useCallback(async (moduleId, name) => {
1308
+ const operationId = await addOperationAndInitialSchema(moduleId, name);
1309
+ if (operationId) setLastCreatedOperationId(operationId);
1310
+ return operationId;
1311
+ }, [addOperationAndInitialSchema, setLastCreatedOperationId]);
1312
+ return /* @__PURE__ */ jsxs("div", { children: [module.operations.map((operation) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Operation, {
1313
+ operation,
1314
+ module,
1315
+ lastCreatedOperationId,
1316
+ allOperationNames,
1317
+ addOperationError,
1318
+ deleteOperationError,
1319
+ setOperationErrorName,
1320
+ onAddOperationAndInitialSchema,
1321
+ updateOperationName,
1322
+ deleteOperation,
1323
+ updateOperationSchema,
1324
+ setOperationDescription,
1325
+ toggleNoInputRequired
1326
+ }) }, operation.id)), /* @__PURE__ */ jsx("div", {
1327
+ className: "mt-6 w-1/2 pr-6",
1328
+ children: /* @__PURE__ */ jsx(OperationForm, {
1329
+ onAddOperationAndInitialSchema,
1330
+ updateOperationName,
1331
+ deleteOperation,
1332
+ module,
1333
+ allOperationNames,
1334
+ focusOnMount: shouldFocusNewOperation
1335
+ }, addOperationFormId)
1336
+ })] });
1337
+ }
1338
+ //#endregion
1339
+ //#region editors/document-model-editor/components/module.tsx
1340
+ function Module(props) {
1341
+ const { module, modules, allOperations, lastCreatedModuleId, onAddModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
1342
+ return /* @__PURE__ */ jsxs("div", {
1343
+ className: "relative rounded-3xl bg-muted p-6",
1344
+ children: [/* @__PURE__ */ jsxs("div", {
1345
+ className: "mb-2 w-1/2 pr-6",
1346
+ children: [/* @__PURE__ */ jsx(ModuleForm, {
1347
+ modules,
1348
+ module,
1349
+ onAddModule,
1350
+ updateModuleName
1351
+ }), !!module && /* @__PURE__ */ jsx("button", {
1352
+ "aria-label": "Delete module",
1353
+ tabIndex: -1,
1354
+ className: "absolute top-1 right-1 p-2 text-foreground transition-colors hover:hover-effect",
1355
+ onClick: () => {
1356
+ deleteModule(module.id);
1357
+ },
1358
+ children: /* @__PURE__ */ jsx("svg", {
1359
+ className: "size-6",
1360
+ viewBox: "0 0 24 24",
1361
+ fill: "currentcolor",
1362
+ children: /* @__PURE__ */ jsx("path", {
1363
+ fillRule: "evenodd",
1364
+ clipRule: "evenodd",
1365
+ 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"
1366
+ })
1367
+ })
1368
+ })]
1369
+ }), !!module && /* @__PURE__ */ jsx(Operations, {
1370
+ module,
1371
+ allOperations,
1372
+ shouldFocusNewOperation: module.id === lastCreatedModuleId,
1373
+ updateOperationName,
1374
+ deleteOperation,
1375
+ addOperationAndInitialSchema,
1376
+ updateOperationSchema,
1377
+ setOperationDescription,
1378
+ addOperationError,
1379
+ deleteOperationError,
1380
+ setOperationErrorName,
1381
+ toggleNoInputRequired
1382
+ })]
1383
+ });
1384
+ }
1385
+ //#endregion
1386
+ //#region editors/document-model-editor/components/modules.tsx
1387
+ function Modules({ modules, allOperations, addModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired }) {
1388
+ const [lastCreatedModuleId, setLastCreatedModuleId] = useState(null);
1389
+ const focusTrapRef = useRef(null);
1390
+ const onAddModule = useCallback(async (name) => {
1391
+ const moduleId = await addModule(name);
1392
+ if (moduleId) {
1393
+ setLastCreatedModuleId(moduleId);
1394
+ focusTrapRef.current?.focus();
1395
+ }
1396
+ return moduleId;
1397
+ }, [addModule, setLastCreatedModuleId]);
1398
+ return /* @__PURE__ */ jsxs("div", {
1399
+ className: "flex flex-col gap-2",
1400
+ children: [
1401
+ modules.map((module) => /* @__PURE__ */ jsx(Module, {
1402
+ module,
1403
+ modules,
1404
+ allOperations,
1405
+ lastCreatedModuleId,
1406
+ onAddModule,
1407
+ updateModuleName,
1408
+ deleteModule,
1409
+ updateOperationName,
1410
+ deleteOperation,
1411
+ addOperationAndInitialSchema,
1412
+ updateOperationSchema,
1413
+ setOperationDescription,
1414
+ addOperationError,
1415
+ deleteOperationError,
1416
+ setOperationErrorName,
1417
+ toggleNoInputRequired
1418
+ }, module.id)),
1419
+ /* @__PURE__ */ jsx(Module, {
1420
+ modules,
1421
+ allOperations,
1422
+ lastCreatedModuleId,
1423
+ onAddModule,
1424
+ updateModuleName,
1425
+ deleteModule,
1426
+ updateOperationName,
1427
+ deleteOperation,
1428
+ addOperationAndInitialSchema,
1429
+ updateOperationSchema,
1430
+ setOperationDescription,
1431
+ addOperationError,
1432
+ deleteOperationError,
1433
+ setOperationErrorName,
1434
+ toggleNoInputRequired
1435
+ }, "add-module"),
1436
+ /* @__PURE__ */ jsx("div", {
1437
+ ref: focusTrapRef,
1438
+ tabIndex: 0,
1439
+ className: "size-0 overflow-hidden",
1440
+ "aria-hidden": "true"
1441
+ })
1442
+ ]
1443
+ });
1444
+ }
1445
+ //#endregion
1446
+ //#region editors/document-model-editor/components/version-controls.tsx
1447
+ const compactButtonStyle$1 = "min-h-0 min-w-0 flex-none rounded-lg px-6 py-1.5 text-sm whitespace-nowrap";
1448
+ function VersionControls(props) {
1449
+ const { specifications, viewedVersion, onViewVersion, onReleaseNewVersion } = props;
1450
+ const [showReleaseModal, setShowReleaseModal] = useState(false);
1451
+ const latestVersion = specifications[specifications.length - 1].version;
1452
+ const nextVersion = latestVersion + 1;
1453
+ return /* @__PURE__ */ jsxs("div", {
1454
+ className: "mb-4 flex items-center justify-between gap-4",
1455
+ children: [
1456
+ /* @__PURE__ */ jsxs("div", {
1457
+ className: "flex items-center gap-2",
1458
+ children: [/* @__PURE__ */ jsxs("span", {
1459
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
1460
+ "data-testid": "model-version-badge",
1461
+ children: ["Version ", viewedVersion]
1462
+ }), specifications.length >= 2 && /* @__PURE__ */ jsx("div", {
1463
+ "aria-label": "Document model version",
1464
+ "data-testid": "model-version-switcher",
1465
+ children: /* @__PURE__ */ jsx(ConnectSelect, {
1466
+ absolutePositionMenu: true,
1467
+ containerClassName: "z-10 [&_svg]:size-4",
1468
+ id: "model-version-switcher",
1469
+ itemClassName: "gap-1 px-2 py-1 font-mono text-xs leading-none [&_p:empty]:hidden",
1470
+ items: specifications.map((spec) => ({
1471
+ value: String(spec.version),
1472
+ displayValue: /* @__PURE__ */ jsx("span", {
1473
+ className: "normal-case",
1474
+ children: spec.version === latestVersion ? `v${spec.version} (latest)` : `v${spec.version} (frozen)`
1475
+ })
1476
+ })),
1477
+ listClassName: "border border-t-0 border-border shadow-md",
1478
+ menuClassName: "min-w-0 pr-1.5",
1479
+ onChange: (value) => {
1480
+ const version = Number(value);
1481
+ onViewVersion(version === latestVersion ? "latest" : version);
1482
+ },
1483
+ value: String(viewedVersion)
1484
+ })
1485
+ })]
1486
+ }),
1487
+ /* @__PURE__ */ jsx(Button, {
1488
+ className: "inline-flex h-8 items-center justify-center py-0",
1489
+ "data-testid": "release-new-version-button",
1490
+ onClick: () => setShowReleaseModal(true),
1491
+ type: "button",
1492
+ children: "Release new version"
1493
+ }),
1494
+ /* @__PURE__ */ jsx(Modal, {
1495
+ open: showReleaseModal,
1496
+ onOpenChange: (status) => {
1497
+ if (!status) setShowReleaseModal(false);
1498
+ },
1499
+ children: /* @__PURE__ */ jsxs("div", {
1500
+ className: "w-[440px] p-6",
1501
+ children: [
1502
+ /* @__PURE__ */ jsxs("div", {
1503
+ className: "pb-2 text-2xl font-bold text-foreground",
1504
+ children: ["Release version ", nextVersion]
1505
+ }),
1506
+ /* @__PURE__ */ jsxs("div", {
1507
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
1508
+ children: [/* @__PURE__ */ jsxs("p", { children: [
1509
+ "Version ",
1510
+ latestVersion,
1511
+ " will be frozen as-is. Version",
1512
+ " ",
1513
+ nextVersion,
1514
+ " starts as an identical copy, and all further edits apply to version ",
1515
+ nextVersion,
1516
+ "."
1517
+ ] }), /* @__PURE__ */ jsxs("p", {
1518
+ className: "mt-3",
1519
+ children: [
1520
+ "Existing version ",
1521
+ latestVersion,
1522
+ " documents will be upgradeable once you define the migration."
1523
+ ]
1524
+ })]
1525
+ }),
1526
+ /* @__PURE__ */ jsxs("div", {
1527
+ className: "mt-4 flex justify-between gap-3",
1528
+ children: [/* @__PURE__ */ jsx(ModalButton, {
1529
+ className: compactButtonStyle$1,
1530
+ onClick: () => setShowReleaseModal(false),
1531
+ variant: "cancel",
1532
+ children: "Cancel"
1533
+ }), /* @__PURE__ */ jsxs(ModalButton, {
1534
+ className: compactButtonStyle$1,
1535
+ "data-testid": "confirm-release-button",
1536
+ onClick: () => {
1537
+ setShowReleaseModal(false);
1538
+ onReleaseNewVersion();
1539
+ },
1540
+ variant: "confirm",
1541
+ children: ["Release version ", nextVersion]
1542
+ })]
1543
+ })
1544
+ ]
1545
+ })
1546
+ })
1547
+ ]
1548
+ });
1549
+ }
1550
+ function FrozenVersionBanner(props) {
1551
+ const { viewedVersion, latestVersion } = props;
1552
+ return /* @__PURE__ */ jsxs("div", {
1553
+ className: "mb-4 rounded-md border border-border bg-muted p-3 text-sm text-foreground",
1554
+ "data-testid": "frozen-version-banner",
1555
+ children: [
1556
+ "Version ",
1557
+ viewedVersion,
1558
+ " is frozen. You're viewing it read-only. Edits go to version ",
1559
+ latestVersion,
1560
+ "."
1561
+ ]
1562
+ });
1563
+ }
1564
+ //#endregion
1565
+ //#region editors/document-model-editor/components/version-advisory-modal.tsx
1566
+ const compactButtonStyle = "min-h-0 min-w-0 flex-none rounded-lg px-4 py-1.5 text-sm whitespace-nowrap";
1567
+ function FieldDiffList(props) {
1568
+ const { label, fields } = props;
1569
+ if (fields.length === 0) return null;
1570
+ return /* @__PURE__ */ jsxs("div", {
1571
+ className: "mt-3",
1572
+ children: [/* @__PURE__ */ jsx("p", {
1573
+ className: "mb-1.5",
1574
+ children: label
1575
+ }), /* @__PURE__ */ jsx("div", {
1576
+ className: "flex flex-col items-start gap-1",
1577
+ children: fields.map((field) => /* @__PURE__ */ jsx("span", {
1578
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
1579
+ children: field
1580
+ }, field))
1581
+ })]
1582
+ });
1583
+ }
1584
+ function VersionAdvisoryModal(props) {
1585
+ const { prompt, onReleaseFirst, onKeepEditing, onCancel } = props;
1586
+ if (!prompt) return null;
1587
+ const { version, reason, diff } = prompt;
1588
+ const nextVersion = version + 1;
1589
+ return /* @__PURE__ */ jsx(Modal, {
1590
+ open: true,
1591
+ onOpenChange: (status) => {
1592
+ if (!status) onCancel();
1593
+ },
1594
+ children: /* @__PURE__ */ jsxs("div", {
1595
+ className: "w-[440px] p-6",
1596
+ "data-testid": "version-advisory-modal",
1597
+ children: [
1598
+ /* @__PURE__ */ jsxs("div", {
1599
+ className: "pb-2 text-2xl font-bold text-foreground",
1600
+ children: [
1601
+ "Is version ",
1602
+ version,
1603
+ " of this model already in use?"
1604
+ ]
1605
+ }),
1606
+ /* @__PURE__ */ jsxs("div", {
1607
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
1608
+ children: [
1609
+ /* @__PURE__ */ jsxs("p", { children: [
1610
+ reason,
1611
+ " Documents that were already created with version ",
1612
+ version,
1613
+ " ",
1614
+ "may stop working correctly."
1615
+ ] }),
1616
+ diff && /* @__PURE__ */ jsxs(Fragment, { children: [
1617
+ /* @__PURE__ */ jsx(FieldDiffList, {
1618
+ fields: diff.addedFields,
1619
+ label: "New fields:"
1620
+ }),
1621
+ /* @__PURE__ */ jsx(FieldDiffList, {
1622
+ fields: diff.removedFields,
1623
+ label: "Removed fields:"
1624
+ }),
1625
+ /* @__PURE__ */ jsx(FieldDiffList, {
1626
+ fields: diff.changedFields,
1627
+ label: "Changed fields:"
1628
+ })
1629
+ ] }),
1630
+ /* @__PURE__ */ jsxs("p", {
1631
+ className: "mt-3",
1632
+ children: [
1633
+ "If others are already using version ",
1634
+ version,
1635
+ ", release version",
1636
+ " ",
1637
+ nextVersion,
1638
+ " first. Your change will go into version ",
1639
+ nextVersion,
1640
+ ", and existing documents can be updated safely."
1641
+ ]
1642
+ })
1643
+ ]
1644
+ }),
1645
+ /* @__PURE__ */ jsxs("div", {
1646
+ className: "mt-4 flex flex-col gap-2",
1647
+ children: [/* @__PURE__ */ jsx(ModalButton, {
1648
+ className: compactButtonStyle,
1649
+ "data-testid": "advisory-release-first",
1650
+ onClick: onReleaseFirst,
1651
+ variant: "confirm",
1652
+ children: `It's in use — release v${nextVersion} first`
1653
+ }), /* @__PURE__ */ jsxs(ModalButton, {
1654
+ className: compactButtonStyle,
1655
+ "data-testid": "advisory-keep-editing",
1656
+ onClick: onKeepEditing,
1657
+ variant: "cancel",
1658
+ children: ["Still in development — keep editing v", version]
1659
+ })]
1660
+ })
1661
+ ]
1662
+ })
1663
+ });
1664
+ }
1665
+ //#endregion
1666
+ //#region editors/document-model-editor/config.ts
1667
+ const editorConfig = { isExternalControlsEnabled: false };
1668
+ //#endregion
1669
+ //#region editors/document-model-editor/utils/change-classification.ts
1670
+ function isShapeTypeNode(node) {
1671
+ return node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION;
1672
+ }
1673
+ function collectTypeFields(doc) {
1674
+ const types = /* @__PURE__ */ new Map();
1675
+ for (const definition of doc.definitions) {
1676
+ if (!isShapeTypeNode(definition)) continue;
1677
+ const fields = /* @__PURE__ */ new Map();
1678
+ if (definition.kind === Kind.ENUM_TYPE_DEFINITION) for (const value of definition.values ?? []) fields.set(value.name.value, "value");
1679
+ else for (const field of definition.fields ?? []) fields.set(field.name.value, print(field.type));
1680
+ types.set(definition.name.value, fields);
1681
+ }
1682
+ return types;
1683
+ }
1684
+ function escapeRegExp(value) {
1685
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1686
+ }
1687
+ function replaceTypeName(printedType, oldName, newName) {
1688
+ return printedType.replace(new RegExp(`\\b${escapeRegExp(oldName)}\\b`, "g"), newName);
1689
+ }
1690
+ function typeSignature(name, fields) {
1691
+ return [...fields.entries()].map(([field, type]) => `${field}:${replaceTypeName(type, name, "__SELF__")}`).sort().join("|");
1692
+ }
1693
+ function detectTypeRenames(oldTypes, newTypes) {
1694
+ const renames = /* @__PURE__ */ new Map();
1695
+ const removed = [...oldTypes.keys()].filter((name) => !newTypes.has(name));
1696
+ const added = new Set([...newTypes.keys()].filter((name) => !oldTypes.has(name)));
1697
+ for (const oldName of removed) {
1698
+ const oldSignature = typeSignature(oldName, oldTypes.get(oldName));
1699
+ for (const newName of added) if (typeSignature(newName, newTypes.get(newName)) === oldSignature) {
1700
+ renames.set(oldName, newName);
1701
+ added.delete(newName);
1702
+ break;
1703
+ }
1704
+ }
1705
+ return renames;
1706
+ }
1707
+ function flattenFields(types, renames) {
1708
+ const fields = /* @__PURE__ */ new Map();
1709
+ for (const [typeName, typeFields] of types) {
1710
+ const resolvedTypeName = renames.get(typeName) ?? typeName;
1711
+ for (const [fieldName, printedType] of typeFields) {
1712
+ let resolvedType = printedType;
1713
+ for (const [oldName, newName] of renames) resolvedType = replaceTypeName(resolvedType, oldName, newName);
1714
+ fields.set(`${resolvedTypeName}.${fieldName}`, resolvedType);
1715
+ }
1716
+ }
1717
+ return fields;
1718
+ }
1719
+ function hasShapeChange(diff) {
1720
+ return diff.addedFields.length > 0 || diff.removedFields.length > 0 || diff.changedFields.length > 0;
1721
+ }
1722
+ function diffSdlShapes(oldSdl, newSdl) {
1723
+ const empty = {
1724
+ addedFields: [],
1725
+ removedFields: [],
1726
+ changedFields: []
1727
+ };
1728
+ let oldDoc;
1729
+ let newDoc;
1730
+ try {
1731
+ oldDoc = parse(oldSdl);
1732
+ newDoc = parse(newSdl);
1733
+ } catch {
1734
+ return empty;
1735
+ }
1736
+ const oldTypes = collectTypeFields(oldDoc);
1737
+ const newTypes = collectTypeFields(newDoc);
1738
+ const oldFields = flattenFields(oldTypes, detectTypeRenames(oldTypes, newTypes));
1739
+ const newFields = flattenFields(newTypes, /* @__PURE__ */ new Map());
1740
+ const diff = {
1741
+ addedFields: [],
1742
+ removedFields: [],
1743
+ changedFields: []
1744
+ };
1745
+ for (const [key, newType] of newFields) {
1746
+ const oldType = oldFields.get(key);
1747
+ if (oldType === void 0) diff.addedFields.push(key);
1748
+ else if (oldType !== newType) diff.changedFields.push(`${key}: ${oldType} → ${newType}`);
1749
+ }
1750
+ for (const key of oldFields.keys()) if (!newFields.has(key)) diff.removedFields.push(key);
1751
+ return diff;
1752
+ }
1753
+ const SAFE = { kind: "safe" };
1754
+ function isBlank(value) {
1755
+ return !value || !value.trim() || value.trim() === "{}";
1756
+ }
1757
+ /**
1758
+ * True for a blank SDL, or an SDL whose types contain nothing but the
1759
+ * `_placeholder` field the editor seeds new state/operation schemas with
1760
+ * (see `makeInitialSchemaDoc` / `makeOperationInitialDoc` in ./helpers.ts).
1761
+ * Replacing a placeholder-only schema with real fields is a user's first
1762
+ * edit on a brand-new model, not a version-relevant change.
1763
+ */
1764
+ function isPlaceholderOnlySchema(sdl) {
1765
+ if (isBlank(sdl)) return true;
1766
+ let doc;
1767
+ try {
1768
+ doc = parse(sdl);
1769
+ } catch {
1770
+ return false;
1771
+ }
1772
+ return [...collectTypeFields(doc).values()].every((fields) => fields.size === 0 || fields.size === 1 && fields.has("_placeholder"));
1773
+ }
1774
+ function findOperation(spec, operationId) {
1775
+ for (const module of spec.modules) {
1776
+ const operation = module.operations.find((op) => op.id === operationId);
1777
+ if (operation) return operation;
1778
+ }
1779
+ }
1780
+ function addedSinceLastRelease(operationId, previousSpec) {
1781
+ return previousSpec !== void 0 && !findOperation(previousSpec, operationId);
1782
+ }
1783
+ function classifySetStateSchema(input, latestSpec) {
1784
+ const currentSchema = input.scope === "local" ? latestSpec.state.local.schema : latestSpec.state.global.schema;
1785
+ if (isPlaceholderOnlySchema(currentSchema)) return SAFE;
1786
+ const diff = diffSdlShapes(currentSchema, input.schema);
1787
+ if (!hasShapeChange(diff)) return SAFE;
1788
+ return {
1789
+ kind: "version-relevant",
1790
+ 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.`,
1791
+ diff
1792
+ };
1793
+ }
1794
+ /**
1795
+ * The editor pre-fills a fresh model's initial value from the placeholder
1796
+ * schema, so a value that is blank or carries only the `_placeholder` key is
1797
+ * still being initialized rather than changed.
1798
+ */
1799
+ function isPlaceholderOnlyInitialValue(value) {
1800
+ if (isBlank(value)) return true;
1801
+ let parsed;
1802
+ try {
1803
+ parsed = JSON.parse(value);
1804
+ } catch {
1805
+ return false;
1806
+ }
1807
+ if (typeof parsed !== "object" || parsed === null) return false;
1808
+ return Object.keys(parsed).every((key) => key === "_placeholder");
1809
+ }
1810
+ function classifySetInitialState(input, latestSpec) {
1811
+ const currentValue = input.scope === "local" ? latestSpec.state.local.initialValue : latestSpec.state.global.initialValue;
1812
+ if (isPlaceholderOnlyInitialValue(currentValue)) return SAFE;
1813
+ if (compareStringsWithoutWhitespace(currentValue, input.initialValue)) return SAFE;
1814
+ return {
1815
+ kind: "version-relevant",
1816
+ reason: `You're changing the starting content that version ${latestSpec.version} documents are built on.`
1817
+ };
1818
+ }
1819
+ function classifyOperationChange(action, operationId, latestSpec, previousSpec) {
1820
+ if (addedSinceLastRelease(operationId, previousSpec)) return SAFE;
1821
+ const operation = findOperation(latestSpec, operationId);
1822
+ if (!operation) return SAFE;
1823
+ const operationLabel = operation.name || "an operation";
1824
+ switch (action.type) {
1825
+ case "DELETE_OPERATION": return {
1826
+ kind: "version-relevant",
1827
+ reason: `You're removing the "${operationLabel}" operation from version ${latestSpec.version}.`
1828
+ };
1829
+ case "SET_OPERATION_NAME":
1830
+ if (isBlank(operation.name)) return SAFE;
1831
+ return {
1832
+ kind: "version-relevant",
1833
+ reason: `You're renaming the "${operationLabel}" operation in version ${latestSpec.version}.`
1834
+ };
1835
+ case "SET_OPERATION_SCHEMA": {
1836
+ if (isPlaceholderOnlySchema(operation.schema ?? "")) return SAFE;
1837
+ if (isBlank(action.input.schema)) return {
1838
+ kind: "version-relevant",
1839
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`
1840
+ };
1841
+ const diff = diffSdlShapes(operation.schema ?? "", action.input.schema ?? "");
1842
+ if (!hasShapeChange(diff)) return SAFE;
1843
+ return {
1844
+ kind: "version-relevant",
1845
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`,
1846
+ diff
1847
+ };
1848
+ }
1849
+ default: return SAFE;
1850
+ }
1851
+ }
1852
+ function classifyDeleteModule(moduleId, latestSpec, previousSpec) {
1853
+ const module = latestSpec.modules.find((candidate) => candidate.id === moduleId);
1854
+ if (!module || module.operations.length === 0) return SAFE;
1855
+ if (module.operations.every((operation) => addedSinceLastRelease(operation.id, previousSpec))) return SAFE;
1856
+ return {
1857
+ kind: "version-relevant",
1858
+ reason: `You're removing the "${module.name}" module and all of its operations from version ${latestSpec.version}.`
1859
+ };
1860
+ }
1861
+ /**
1862
+ * Classifies a document-model action as version-relevant (would break
1863
+ * documents created with the current version) or safe. `previousSpec` is the
1864
+ * last released specification, used to exempt operations added since the
1865
+ * release.
1866
+ */
1867
+ function classifyDocumentModelAction(action, latestSpec, previousSpec) {
1868
+ switch (action.type) {
1869
+ case "SET_STATE_SCHEMA": return classifySetStateSchema(action.input, latestSpec);
1870
+ case "SET_INITIAL_STATE": return classifySetInitialState(action.input, latestSpec);
1871
+ case "DELETE_OPERATION":
1872
+ case "SET_OPERATION_NAME":
1873
+ case "SET_OPERATION_SCHEMA": return classifyOperationChange(action, action.input.id, latestSpec, previousSpec);
1874
+ case "DELETE_MODULE": return classifyDeleteModule(action.input.id, latestSpec, previousSpec);
1875
+ default: return SAFE;
1876
+ }
1877
+ }
1878
+ /**
1879
+ * Pure decision core of the version advisory: given the actions about to be
1880
+ * dispatched, decide whether to dispatch immediately or prompt the user.
1881
+ */
1882
+ function decideDispatch(actions, latestSpec, previousSpec, hasSessionChoice) {
1883
+ if (hasSessionChoice) return { kind: "dispatch" };
1884
+ for (const action of actions) {
1885
+ const classification = classifyDocumentModelAction(action, latestSpec, previousSpec);
1886
+ if (classification.kind === "version-relevant") return {
1887
+ kind: "prompt",
1888
+ reason: classification.reason,
1889
+ diff: classification.diff
1890
+ };
1891
+ }
1892
+ return { kind: "dispatch" };
1893
+ }
1894
+ //#endregion
1895
+ //#region editors/document-model-editor/hooks/useVersionAdvisory.ts
1896
+ /**
1897
+ * Versions the user has confirmed as "still in development" (or that were
1898
+ * just created via an explicit release) for this browser session. Keyed by
1899
+ * `${documentId}:${version}`. Deliberately in-memory: a publisher returning
1900
+ * in a later session is asked again, which is when the reminder matters.
1901
+ */
1902
+ const sessionVersionChoices = /* @__PURE__ */ new Set();
1903
+ function useVersionAdvisory(args) {
1904
+ const { documentId, latestSpec, previousSpec, dispatch, onReleaseError } = args;
1905
+ const [prompt, setPrompt] = useState(void 0);
1906
+ const pendingRef = useRef(void 0);
1907
+ const choiceKey = `${documentId}:${latestSpec.version}`;
1908
+ const guardedDispatch = (...dispatchArgs) => {
1909
+ const [action] = dispatchArgs;
1910
+ const decision = decideDispatch((Array.isArray(action) ? action : [action]).filter((candidate) => candidate !== void 0), latestSpec, previousSpec, sessionVersionChoices.has(choiceKey));
1911
+ if (decision.kind === "dispatch") {
1912
+ dispatch(...dispatchArgs);
1913
+ return;
1914
+ }
1915
+ pendingRef.current = dispatchArgs;
1916
+ setPrompt({
1917
+ version: latestSpec.version,
1918
+ reason: decision.reason,
1919
+ diff: decision.diff
1920
+ });
1921
+ };
1922
+ const flushPending = () => {
1923
+ const pending = pendingRef.current;
1924
+ pendingRef.current = void 0;
1925
+ if (pending) dispatch(...pending);
1926
+ };
1927
+ const releaseFirst = () => {
1928
+ setPrompt(void 0);
1929
+ if (!pendingRef.current) return;
1930
+ dispatch(releaseNewVersion(), (errors) => {
1931
+ if (errors.length > 0) {
1932
+ pendingRef.current = void 0;
1933
+ onReleaseError?.(errors[0].message);
1934
+ }
1935
+ }, () => {
1936
+ if (!pendingRef.current) return;
1937
+ sessionVersionChoices.add(`${documentId}:${latestSpec.version + 1}`);
1938
+ flushPending();
1939
+ });
1940
+ };
1941
+ const keepEditing = () => {
1942
+ sessionVersionChoices.add(choiceKey);
1943
+ setPrompt(void 0);
1944
+ flushPending();
1945
+ };
1946
+ const cancelAdvisory = () => {
1947
+ pendingRef.current = void 0;
1948
+ setPrompt(void 0);
1949
+ };
1950
+ const markVersionInDevelopment = (version) => {
1951
+ sessionVersionChoices.add(`${documentId}:${version}`);
1952
+ };
1953
+ return {
1954
+ guardedDispatch,
1955
+ prompt,
1956
+ releaseFirst,
1957
+ keepEditing,
1958
+ cancelAdvisory,
1959
+ markVersionInDevelopment
1960
+ };
1961
+ }
1962
+ //#endregion
1963
+ //#region editors/document-model-editor/editor.tsx
1964
+ var editor_exports = /* @__PURE__ */ __exportAll({ default: () => Editor });
1965
+ const StateSchemas = lazy(() => import("./state-schemas-DHLAg1w0.js"));
1966
+ const noopSetStateSchema = () => void 0;
1967
+ const noopSetInitialState = () => void 0;
1968
+ function Editor({ document, dispatch }) {
1969
+ useSetPHDocumentEditorConfig(editorConfig);
1970
+ const toast = usePHToast();
1971
+ const [scope, setScope] = useState("global");
1972
+ const documentNodeName = document.header.name;
1973
+ const { name: modelName, id: documentType, extension, description, author: { name: authorName, website: authorWebsite } } = document.state.global;
1974
+ const specifications = document.state.global.specifications;
1975
+ const latestSpec = specifications[specifications.length - 1];
1976
+ const previousSpec = specifications.length >= 2 ? specifications[specifications.length - 2] : void 0;
1977
+ const [viewedVersion, setViewedVersion] = useState("latest");
1978
+ const viewedSpec = viewedVersion === "latest" ? latestSpec : specifications.find((spec) => spec.version === viewedVersion) ?? latestSpec;
1979
+ const isViewingFrozenVersion = viewedSpec.version !== latestSpec.version;
1980
+ const { state: { global: { schema: globalStateSchema, initialValue: globalStateInitialValue }, local: { schema: localStateSchema, initialValue: localStateInitialValue } }, modules } = viewedSpec;
1981
+ const operations = modules.flatMap((module) => module.operations);
1982
+ const { state: { global: { schema: latestGlobalStateSchema, initialValue: latestGlobalStateInitialValue }, local: { schema: latestLocalStateSchema, initialValue: latestLocalStateInitialValue } }, modules: latestModules } = latestSpec;
1983
+ const latestOperations = latestModules.flatMap((module) => module.operations);
1984
+ const shouldSetInitialName = useRef(!modelName && !!documentNodeName && latestOperations.length === 0);
1985
+ useEffect(() => {
1986
+ if (!shouldSetInitialName.current || !documentNodeName) return;
1987
+ const initialSchemaDoc = initializeModelSchema(documentNodeName);
1988
+ dispatch([setModelName({ name: documentNodeName }), setStateSchema({
1989
+ schema: initialSchemaDoc,
1990
+ scope: "global"
1991
+ })]);
1992
+ shouldSetInitialName.current = false;
1993
+ }, [documentNodeName, dispatch]);
1994
+ const { guardedDispatch, prompt, releaseFirst, keepEditing, cancelAdvisory, markVersionInDevelopment } = useVersionAdvisory({
1995
+ documentId: document.header.id,
1996
+ latestSpec,
1997
+ previousSpec,
1998
+ dispatch,
1999
+ onReleaseError: (message) => {
2000
+ if (toast) toast(message, { type: "connect-warning" });
2001
+ }
2002
+ });
2003
+ const handleReleaseNewVersion = () => {
2004
+ const nextVersion = latestSpec.version + 1;
2005
+ dispatch(releaseNewVersion(), (errors) => {
2006
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
2007
+ }, () => {
2008
+ markVersionInDevelopment(nextVersion);
2009
+ setViewedVersion("latest");
2010
+ });
2011
+ };
2012
+ const operationSchemasSdl = operations.flatMap((operation) => operation.schema ?? []).join("\n");
2013
+ const handleSetModelId = (id) => {
2014
+ if (compareStringsWithoutWhitespace(id, documentType)) return;
2015
+ guardedDispatch([setModelId({ id })]);
2016
+ };
2017
+ const handleSetModelDescription = (newDescription) => {
2018
+ if (compareStringsWithoutWhitespace(newDescription, description)) return;
2019
+ guardedDispatch(setModelDescription({ description: newDescription }));
2020
+ };
2021
+ const handleSetModelExtension = (newExtension) => {
2022
+ if (compareStringsWithoutWhitespace(newExtension, extension)) return;
2023
+ guardedDispatch(setModelExtension({ extension: newExtension }));
2024
+ };
2025
+ const handleSetModelName = (newName) => {
2026
+ if (compareStringsWithoutWhitespace(newName, modelName)) return;
2027
+ guardedDispatch(setModelName({ name: newName }));
2028
+ };
2029
+ const handleSetAuthorName = (newAuthorName) => {
2030
+ if (compareStringsWithoutWhitespace(newAuthorName, authorName)) return;
2031
+ guardedDispatch(setAuthorName({ authorName: newAuthorName }));
2032
+ };
2033
+ const handleSetAuthorWebsite = (newAuthorWebsite) => {
2034
+ if (compareStringsWithoutWhitespace(newAuthorWebsite, authorWebsite ?? "")) return;
2035
+ guardedDispatch(setAuthorWebsite({ authorWebsite: newAuthorWebsite }));
2036
+ };
2037
+ const handleSetStateSchema = (newSchema, scope) => {
2038
+ if (compareStringsWithoutWhitespace(newSchema, scope === "global" ? latestGlobalStateSchema : latestLocalStateSchema)) return;
2039
+ guardedDispatch(setStateSchema({
2040
+ schema: newSchema,
2041
+ scope
2042
+ }));
2043
+ };
2044
+ const handleSetInitialState = (newInitialValue, scope) => {
2045
+ if (compareStringsWithoutWhitespace(newInitialValue, scope === "global" ? latestGlobalStateInitialValue : latestLocalStateInitialValue)) return;
2046
+ guardedDispatch(setInitialState({
2047
+ initialValue: newInitialValue,
2048
+ scope
2049
+ }));
2050
+ };
2051
+ const handleAddModule = (name) => {
2052
+ return new Promise((resolve) => {
2053
+ try {
2054
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) {
2055
+ resolve(void 0);
2056
+ return;
2057
+ }
2058
+ const id = generateId();
2059
+ guardedDispatch(addModule({
2060
+ id,
2061
+ name
2062
+ }));
2063
+ resolve(id);
2064
+ } catch (error) {
2065
+ console.error("Failed to add module:", error);
2066
+ resolve(void 0);
2067
+ }
2068
+ });
2069
+ };
2070
+ const handleSetModuleName = (id, name) => {
2071
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) return;
2072
+ guardedDispatch(setModuleName({
2073
+ id,
2074
+ name
2075
+ }));
2076
+ };
2077
+ const handleDeleteModule = (id) => {
2078
+ guardedDispatch(deleteModule({ id }));
2079
+ };
2080
+ const handleAddOperation = (moduleId, name) => {
2081
+ return new Promise((resolve) => {
2082
+ const id = generateId();
2083
+ guardedDispatch(addOperation({
2084
+ id,
2085
+ moduleId,
2086
+ name,
2087
+ scope
2088
+ }), (errors) => {
2089
+ if (errors.length > 0) {
2090
+ if (toast) toast(errors[0].message, { type: "connect-warning" });
2091
+ resolve(void 0);
2092
+ } else resolve(id);
2093
+ }, () => resolve(id));
2094
+ });
2095
+ };
2096
+ const handleSetOperationName = (id, name) => {
2097
+ guardedDispatch(setOperationName({
2098
+ id,
2099
+ name
2100
+ }), (errors) => {
2101
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
2102
+ });
2103
+ };
2104
+ const handleSetOperationSchema = (id, newSchema) => {
2105
+ const operation = latestOperations.find((operation) => operation.id === id);
2106
+ if (operation?.schema && compareStringsWithoutWhitespace(newSchema, operation.schema)) return;
2107
+ guardedDispatch(setOperationSchema({
2108
+ id,
2109
+ schema: newSchema
2110
+ }));
2111
+ };
2112
+ const handleToggleNoInputRequired = (id, noInputRequired) => {
2113
+ const operation = latestOperations.find((op) => op.id === id);
2114
+ if (!operation?.name) return;
2115
+ if (noInputRequired) guardedDispatch(setOperationSchema({
2116
+ id,
2117
+ schema: makeEmptyOperationSchema(operation.name)
2118
+ }));
2119
+ else guardedDispatch(setOperationSchema({
2120
+ id,
2121
+ schema: makeOperationInitialDoc(operation.name)
2122
+ }));
2123
+ };
2124
+ const handleSetOperationDescription = (id, newDescription) => {
2125
+ if (compareStringsWithoutWhitespace(latestOperations.find((operation) => operation.id === id)?.description ?? "", newDescription)) return;
2126
+ guardedDispatch(setOperationDescription({
2127
+ id,
2128
+ description: newDescription
2129
+ }));
2130
+ };
2131
+ const handleDeleteOperation = (id) => {
2132
+ guardedDispatch(deleteOperation({ id }));
2133
+ };
2134
+ const handleAddOperationError = (operationId, errorName) => {
2135
+ return new Promise((resolve) => {
2136
+ try {
2137
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) {
2138
+ resolve(void 0);
2139
+ return;
2140
+ }
2141
+ const id = generateId();
2142
+ const errorCode = pascalCase(errorName);
2143
+ guardedDispatch(addOperationError({
2144
+ id,
2145
+ operationId,
2146
+ errorName,
2147
+ errorCode
2148
+ }));
2149
+ resolve(id);
2150
+ } catch (error) {
2151
+ console.error("Failed to add operation error:", error);
2152
+ resolve(void 0);
2153
+ }
2154
+ });
2155
+ };
2156
+ const handleDeleteOperationError = (id) => {
2157
+ guardedDispatch(deleteOperationError({ id }));
2158
+ };
2159
+ const handleSetOperationErrorName = (operationId, errorId, errorName) => {
2160
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) return;
2161
+ guardedDispatch(setOperationErrorName({
2162
+ id: errorId,
2163
+ errorName
2164
+ }));
2165
+ };
2166
+ const addOperationAndInitialSchema = async (moduleId, name) => {
2167
+ try {
2168
+ const id = await handleAddOperation(moduleId, name);
2169
+ if (!id) return void 0;
2170
+ try {
2171
+ handleSetOperationSchema(id, makeOperationInitialDoc(name));
2172
+ return id;
2173
+ } catch (error) {
2174
+ console.error("Failed to update operation schema:", error);
2175
+ return;
2176
+ }
2177
+ } catch (error) {
2178
+ console.error("Failed to add operation and schema:", error);
2179
+ return;
2180
+ }
2181
+ };
2182
+ return /* @__PURE__ */ jsxs("main", {
2183
+ className: "min-h-dvh bg-background p-6",
2184
+ children: [
2185
+ /* @__PURE__ */ jsx(DocumentToolbar, { document }),
2186
+ /* @__PURE__ */ jsx(SchemaContextProvider, {
2187
+ globalStateSchemaSdl: globalStateSchema,
2188
+ localStateSchemaSdl: localStateSchema,
2189
+ operationSchemasSdl,
2190
+ children: /* @__PURE__ */ jsxs("div", {
2191
+ className: "mx-auto max-w-6xl px-4 pt-8",
2192
+ children: [
2193
+ /* @__PURE__ */ jsx(VersionControls, {
2194
+ specifications,
2195
+ viewedVersion: viewedSpec.version,
2196
+ onViewVersion: setViewedVersion,
2197
+ onReleaseNewVersion: handleReleaseNewVersion
2198
+ }),
2199
+ /* @__PURE__ */ jsx(ModelMetadata, {
2200
+ name: modelName,
2201
+ documentType,
2202
+ extension,
2203
+ description,
2204
+ authorName,
2205
+ authorWebsite: authorWebsite ?? "",
2206
+ globalStateSchema: latestGlobalStateSchema,
2207
+ localStateSchema: latestLocalStateSchema,
2208
+ setModelId: handleSetModelId,
2209
+ setModelDescription: handleSetModelDescription,
2210
+ setModelExtension: handleSetModelExtension,
2211
+ setModelName: handleSetModelName,
2212
+ setAuthorName: handleSetAuthorName,
2213
+ setAuthorWebsite: handleSetAuthorWebsite,
2214
+ setStateSchema: handleSetStateSchema
2215
+ }),
2216
+ /* @__PURE__ */ jsx(Divider, {}),
2217
+ isViewingFrozenVersion && /* @__PURE__ */ jsx(FrozenVersionBanner, {
2218
+ latestVersion: latestSpec.version,
2219
+ viewedVersion: viewedSpec.version
2220
+ }),
2221
+ /* @__PURE__ */ jsxs("div", {
2222
+ className: isViewingFrozenVersion ? "pointer-events-none opacity-80 select-none" : void 0,
2223
+ inert: isViewingFrozenVersion || void 0,
2224
+ children: [
2225
+ /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(StateSchemas, {
2226
+ modelName,
2227
+ globalStateSchema,
2228
+ globalStateInitialValue,
2229
+ localStateSchema,
2230
+ localStateInitialValue,
2231
+ setStateSchema: isViewingFrozenVersion ? noopSetStateSchema : handleSetStateSchema,
2232
+ setInitialState: isViewingFrozenVersion ? noopSetInitialState : handleSetInitialState,
2233
+ currentScope: scope,
2234
+ onScopeChange: setScope
2235
+ }) }),
2236
+ /* @__PURE__ */ jsx(Divider, {}),
2237
+ /* @__PURE__ */ jsxs("h3", {
2238
+ className: "mb-6 text-lg text-foreground capitalize",
2239
+ children: [scope, " Operations"]
2240
+ }),
2241
+ /* @__PURE__ */ jsx(Modules, {
2242
+ modules: modules.map((module) => ({
2243
+ ...module,
2244
+ operations: module.operations.filter((op) => op.scope === scope)
2245
+ })),
2246
+ allOperations: operations,
2247
+ addModule: handleAddModule,
2248
+ updateModuleName: handleSetModuleName,
2249
+ deleteModule: handleDeleteModule,
2250
+ updateOperationName: handleSetOperationName,
2251
+ updateOperationSchema: handleSetOperationSchema,
2252
+ setOperationDescription: handleSetOperationDescription,
2253
+ deleteOperation: handleDeleteOperation,
2254
+ addOperationError: handleAddOperationError,
2255
+ deleteOperationError: handleDeleteOperationError,
2256
+ setOperationErrorName: handleSetOperationErrorName,
2257
+ addOperationAndInitialSchema,
2258
+ toggleNoInputRequired: handleToggleNoInputRequired
2259
+ })
2260
+ ]
2261
+ })
2262
+ ]
2263
+ })
2264
+ }),
2265
+ /* @__PURE__ */ jsx(VersionAdvisoryModal, {
2266
+ prompt,
2267
+ onReleaseFirst: releaseFirst,
2268
+ onKeepEditing: keepEditing,
2269
+ onCancel: cancelAdvisory
2270
+ })
2271
+ ]
2272
+ });
2273
+ }
2274
+ //#endregion
2275
+ export { makeInitialSchemaDoc as a, validateStateObject as c, Editor as default, StateValidationError as i, Button as n, makeMinimalObjectForStateType as o, ensureValidStateSchemaName as r, makeStateSchemaNameForScope as s, editor_exports as t };
2276
+
2277
+ //# sourceMappingURL=editor-x1UIfSot.js.map