@sanity/assist 1.2.15 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +551 -30
  3. package/dist/index.cjs.mjs +1 -0
  4. package/dist/index.d.ts +253 -11
  5. package/dist/index.esm.js +2405 -392
  6. package/dist/index.esm.js.map +1 -1
  7. package/dist/index.js +2399 -385
  8. package/dist/index.js.map +1 -1
  9. package/package.json +15 -14
  10. package/src/_lib/form/DocumentForm.tsx +3 -2
  11. package/src/_lib/form/constants.ts +1 -0
  12. package/src/assistDocument/AssistDocumentInput.tsx +24 -4
  13. package/src/assistDocument/RequestRunInstructionProvider.tsx +37 -21
  14. package/src/assistDocument/components/instruction/InstructionInput.tsx +5 -4
  15. package/src/assistDocument/components/instruction/InstructionOutputField.tsx +45 -0
  16. package/src/assistDocument/components/instruction/InstructionOutputInput.tsx +205 -0
  17. package/src/assistDocument/hooks/useStudioAssistDocument.ts +5 -32
  18. package/src/assistFormComponents/AssistField.tsx +11 -5
  19. package/src/assistFormComponents/AssistFormBlock.tsx +2 -3
  20. package/src/assistFormComponents/validation/listItem.tsx +2 -2
  21. package/src/assistInspector/AssistInspector.tsx +6 -0
  22. package/src/assistInspector/FieldAutocomplete.tsx +1 -0
  23. package/src/assistInspector/InstructionTaskHistoryButton.tsx +2 -3
  24. package/src/assistInspector/helpers.ts +9 -11
  25. package/src/assistLayout/AssistLayout.tsx +9 -9
  26. package/src/components/ImageContext.tsx +19 -9
  27. package/src/components/SafeValueInput.tsx +4 -1
  28. package/src/fieldActions/assistFieldActions.tsx +42 -13
  29. package/src/fieldActions/generateCaptionActions.tsx +2 -2
  30. package/src/fieldActions/generateImageActions.tsx +57 -0
  31. package/src/helpers/assistSupported.ts +10 -16
  32. package/src/helpers/conditionalMembers.test.ts +200 -0
  33. package/src/helpers/conditionalMembers.ts +127 -0
  34. package/src/helpers/typeUtils.ts +19 -5
  35. package/src/index.ts +3 -0
  36. package/src/plugin.tsx +14 -5
  37. package/src/presence/AssistAvatar.tsx +1 -1
  38. package/src/schemas/assistDocumentSchema.tsx +40 -1
  39. package/src/schemas/serialize/serializeSchema.test.ts +239 -8
  40. package/src/schemas/serialize/serializeSchema.ts +77 -10
  41. package/src/schemas/typeDefExtensions.ts +89 -5
  42. package/src/translate/FieldTranslationProvider.tsx +360 -0
  43. package/src/translate/getLanguageParams.ts +26 -0
  44. package/src/translate/languageStore.ts +18 -0
  45. package/src/translate/paths.test.ts +133 -0
  46. package/src/translate/paths.ts +175 -0
  47. package/src/translate/translateActions.tsx +188 -0
  48. package/src/translate/types.ts +160 -0
  49. package/src/types.ts +33 -12
  50. package/src/useApiClient.ts +130 -2
  51. package/src/assistLayout/AlphaMigration.tsx +0 -310
  52. package/src/legacy-types.ts +0 -72
package/dist/index.js CHANGED
@@ -12,8 +12,8 @@ var operators = require('rxjs/operators');
12
12
  var isEqual = require('react-fast-compare');
13
13
  var rxjs = require('rxjs');
14
14
  var rxjsExhaustmapWithTrailing = require('rxjs-exhaustmap-with-trailing');
15
- var desk = require('sanity/desk');
16
15
  var mutator = require('@sanity/mutator');
16
+ var desk = require('sanity/desk');
17
17
  var styled = require('styled-components');
18
18
  var dateFns = require('date-fns');
19
19
  var formatDistanceToNow = require('date-fns/formatDistanceToNow');
@@ -41,6 +41,8 @@ const instructionTaskTypeName = "sanity.assist.instructionTask";
41
41
  const fieldPresenceTypeName = "sanity.assist.instructionTask.presence";
42
42
  const assistSerializedTypeName = "sanity.assist.serialized.type";
43
43
  const assistSerializedFieldTypeName = "sanity.assist.serialized.field";
44
+ const outputFieldTypeName = "sanity.assist.output.field";
45
+ const outputTypeTypeName = "sanity.assist.output.type";
44
46
  const fieldPathParam = "pathKey";
45
47
  const instructionParam = "instruction";
46
48
  const documentRootKey = "<document>";
@@ -137,49 +139,59 @@ function isType(schemaType, typeName) {
137
139
  function isImage(schemaType) {
138
140
  return isType(schemaType, "image");
139
141
  }
140
- function getCaptionFieldOption(schemaType) {
141
- var _a;
142
+ function getDescriptionFieldOption(schemaType) {
143
+ var _a, _b;
144
+ if (!schemaType) {
145
+ return void 0;
146
+ }
147
+ const descriptionField = (_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageDescriptionField;
148
+ if (descriptionField) {
149
+ return descriptionField;
150
+ }
151
+ return getDescriptionFieldOption(schemaType.type);
152
+ }
153
+ function getImageInstructionFieldOption(schemaType) {
154
+ var _a, _b;
142
155
  if (!schemaType) {
143
156
  return void 0;
144
157
  }
145
- const captionField = (_a = schemaType.options) == null ? void 0 : _a.captionField;
146
- if (captionField) {
147
- return captionField;
158
+ const imageInstructionField = (_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField;
159
+ if (imageInstructionField) {
160
+ return imageInstructionField;
148
161
  }
149
- return getCaptionFieldOption(schemaType.type);
162
+ return getImageInstructionFieldOption(schemaType.type);
150
163
  }
151
164
  function isSchemaAssistEnabled(type) {
152
165
  var _a, _b;
153
- return !((_b = (_a = type.options) == null ? void 0 : _a.aiWritingAssistance) == null ? void 0 : _b.exclude);
166
+ return !((_b = (_a = type.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.exclude);
154
167
  }
155
168
  function isAssistSupported(type) {
156
- let allowReadonlyHidden = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
157
169
  if (!isSchemaAssistEnabled(type)) {
158
170
  return false;
159
171
  }
160
- if (isDisabled(type, allowReadonlyHidden)) {
172
+ if (isDisabled(type)) {
161
173
  return false;
162
174
  }
163
175
  if (type.jsonType === "array") {
164
- const unsupportedArray = type.of.every(t => isDisabled(t, allowReadonlyHidden));
176
+ const unsupportedArray = type.of.every(t => isDisabled(t));
165
177
  return !unsupportedArray;
166
178
  }
167
179
  if (type.jsonType === "object") {
168
- const unsupportedObject = type.fields.every(field => isDisabled(field.type, allowReadonlyHidden));
180
+ const unsupportedObject = type.fields.every(field => isDisabled(field.type));
169
181
  return !unsupportedObject;
170
182
  }
171
183
  return true;
172
184
  }
173
- function isDisabled(type, allowReadonlyHidden) {
174
- const readonlyHidden = !!type.readOnly || !!type.hidden;
175
- return !isSchemaAssistEnabled(type) || isUnsupportedType(type) || !allowReadonlyHidden && readonlyHidden;
185
+ function isDisabled(type) {
186
+ return !isSchemaAssistEnabled(type) || isUnsupportedType(type);
176
187
  }
177
188
  function isUnsupportedType(type) {
178
- return type.jsonType === "number" || type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "reference") || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
189
+ var _a, _b;
190
+ return type.jsonType === "number" || type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "reference") && !((_b = (_a = type == null ? void 0 : type.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.embeddingsIndex) || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
179
191
  }
180
192
  const inlineTypes = ["document", "object", "image", "file"];
181
193
  function serializeSchema(schema, options) {
182
- const list = schema.getTypeNames().filter(t => !(hiddenTypes.includes(t) || t.startsWith("sanity."))).map(t => schema.get(t)).filter(t => !!t).filter(t => !t.hidden && !t.readOnly).map(t => getSchemaStub(t, schema, options)).filter(t => {
194
+ const list = schema.getTypeNames().filter(t => !(hiddenTypes.includes(t) || t.startsWith("sanity."))).map(t => schema.get(t)).filter(t => !!t).map(t => getSchemaStub(t, schema, options)).filter(t => {
183
195
  if ("to" in t && t.to && !t.to.length) {
184
196
  return false;
185
197
  }
@@ -217,26 +229,41 @@ function getSchemaStub(schemaType, schema, options) {
217
229
  return removeUndef(baseSchema);
218
230
  }
219
231
  function getBaseFields(schema, type, typeName, options) {
220
- var _a, _b, _c;
221
- const imagePromptField = (_a = type.options) == null ? void 0 : _a.imagePromptField;
232
+ var _a, _b, _c, _d, _e, _f;
233
+ const schemaOptions = removeUndef({
234
+ imagePromptField: (_b = (_a = type.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField,
235
+ embeddingsIndex: (_d = (_c = type.options) == null ? void 0 : _c.aiAssist) == null ? void 0 : _d.embeddingsIndex
236
+ });
222
237
  return removeUndef({
223
- options: imagePromptField ? {
224
- imagePromptField
225
- } : void 0,
226
- values: Array.isArray((_b = type == null ? void 0 : type.options) == null ? void 0 : _b.list) ? (_c = type == null ? void 0 : type.options) == null ? void 0 : _c.list.map(v => {
238
+ options: Object.keys(schemaOptions).length ? schemaOptions : void 0,
239
+ values: Array.isArray((_e = type == null ? void 0 : type.options) == null ? void 0 : _e.list) ? (_f = type == null ? void 0 : type.options) == null ? void 0 : _f.list.map(v => {
227
240
  var _a2;
228
241
  return typeof v === "string" ? v : (_a2 = v.value) != null ? _a2 : "".concat(v.title);
229
242
  }) : void 0,
230
243
  of: "of" in type && typeName === "array" ? arrayOf(type, schema, options) : void 0,
231
244
  to: "to" in type && typeName === "reference" ? refToTypeNames(type) : void 0,
232
- fields: "fields" in type && inlineTypes.includes(typeName) ? serializeFields(schema, type, options) : void 0
245
+ fields: "fields" in type && inlineTypes.includes(typeName) ? serializeFields(schema, type, options) : void 0,
246
+ annotations: typeName === "block" && "fields" in type ? serializeAnnotations(type, schema, options) : void 0,
247
+ inlineOf: typeName === "block" && "fields" in type ? serializeInlineOf(type, schema, options) : void 0,
248
+ hidden: typeof type.hidden === "function" ? "function" : type.hidden ? true : void 0,
249
+ readOnly: typeof type.readOnly === "function" ? "function" : type.readOnly ? true : void 0
233
250
  });
234
251
  }
235
252
  function serializeFields(schema, schemaType, options) {
236
- return schemaType.fields.filter(f => {
253
+ const fields = schemaType.fieldsets ? schemaType.fieldsets.flatMap(fs => fs.single ? fs.field : fs.fields.map(f => ({
254
+ ...f,
255
+ type: {
256
+ ...f.type,
257
+ // if fieldset is (conditionally) hidden, the field must be considered the same way
258
+ // ie, if the field does not show up in conditionalMembers, it is hidden
259
+ // regardless of weather or not it is the field function or the fieldset function that hides it
260
+ hidden: typeof fs.hidden === "function" ? fs.hidden : fs.hidden ? true : f.type.hidden
261
+ }
262
+ }))) : schemaType.fields;
263
+ return fields.filter(f => {
237
264
  var _a, _b;
238
265
  return !["sanity.imageHotspot", "sanity.imageCrop"].includes((_b = (_a = f.type) == null ? void 0 : _a.name) != null ? _b : "");
239
- }).filter(f => isAssistSupported(f.type)).filter(f => !f.type.hidden && !f.type.readOnly).map(field => serializeMember(schema, field.type, field.name, options));
266
+ }).filter(f => isAssistSupported(f.type)).map(field => serializeMember(schema, field.type, field.name, options));
240
267
  }
241
268
  function serializeMember(schema, type, name, options) {
242
269
  var _a, _b;
@@ -252,6 +279,25 @@ function serializeMember(schema, type, name, options) {
252
279
  ...getBaseFields(schema, type, typeName, options)
253
280
  });
254
281
  }
282
+ function serializeInlineOf(blockSchemaType, schema, options) {
283
+ const childrenField = blockSchemaType.fields.find(f => f.name === "children");
284
+ const childrenType = childrenField == null ? void 0 : childrenField.type;
285
+ if (!childrenType || !sanity.isArraySchemaType(childrenType)) {
286
+ return void 0;
287
+ }
288
+ return arrayOf({
289
+ ...childrenType,
290
+ of: childrenType.of.filter(t => !isType(t, "span"))
291
+ }, schema, options);
292
+ }
293
+ function serializeAnnotations(blockSchemaType, schema, options) {
294
+ const markDefs = blockSchemaType.fields.find(f => f.name === "markDefs");
295
+ const marksType = markDefs == null ? void 0 : markDefs.type;
296
+ if (!marksType || !sanity.isArraySchemaType(marksType)) {
297
+ return void 0;
298
+ }
299
+ return arrayOf(marksType, schema, options);
300
+ }
255
301
  function arrayOf(arrayType, schema, options) {
256
302
  return arrayType.of.filter(type => isAssistSupported(type)).map(t => {
257
303
  return serializeMember(schema, t, t.name, options);
@@ -370,7 +416,111 @@ function SchemaEntry(_ref) {
370
416
  children: out
371
417
  });
372
418
  }
419
+ const MAX_DEPTH$1 = 6;
420
+ function getDocumentMembersFlat(doc, schemaType) {
421
+ if (!sanity.isDocumentSchemaType(schemaType)) {
422
+ console.error("Schema type is not a document");
423
+ return [];
424
+ }
425
+ return extractPaths(doc, schemaType, [], MAX_DEPTH$1);
426
+ }
427
+ function extractPaths(doc, schemaType, path, maxDepth) {
428
+ if (path.length >= maxDepth) {
429
+ return [];
430
+ }
431
+ return schemaType.fields.reduce((acc, field) => {
432
+ var _a, _b;
433
+ const fieldPath = [...path, field.name];
434
+ const fieldSchema = field.type;
435
+ const {
436
+ value
437
+ } = (_a = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _a : {};
438
+ if (!value) {
439
+ return acc;
440
+ }
441
+ const thisFieldWithPath = {
442
+ path: fieldPath,
443
+ name: field.name,
444
+ schemaType: fieldSchema,
445
+ value
446
+ };
447
+ if (fieldSchema.jsonType === "object") {
448
+ const innerFields = extractPaths(doc, fieldSchema, fieldPath, maxDepth);
449
+ return [...acc, thisFieldWithPath, ...innerFields];
450
+ } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some(item => "fields" in item)) {
451
+ const {
452
+ value: arrayValue
453
+ } = (_b = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _b : {};
454
+ let arrayPaths = [];
455
+ if (arrayValue == null ? void 0 : arrayValue.length) {
456
+ for (const item of arrayValue) {
457
+ const itemPath = [...fieldPath, {
458
+ _key: item._key
459
+ }];
460
+ let itemSchema = fieldSchema.of.find(t => t.name === item._type);
461
+ if (!item._type) {
462
+ itemSchema = fieldSchema.of[0];
463
+ console.warn("Array item is missing _type - using the first defined type in the array.of schema", {
464
+ itemPath,
465
+ item,
466
+ itemSchema
467
+ });
468
+ }
469
+ if (item._key && itemSchema) {
470
+ const innerFields = extractPaths(doc, itemSchema, itemPath, maxDepth);
471
+ const arrayMember = {
472
+ path: itemPath,
473
+ name: item._key,
474
+ schemaType: itemSchema,
475
+ value: item
476
+ };
477
+ arrayPaths = [...arrayPaths, arrayMember, ...innerFields];
478
+ }
479
+ }
480
+ }
481
+ return [...acc, thisFieldWithPath, ...arrayPaths];
482
+ }
483
+ return [...acc, thisFieldWithPath];
484
+ }, []);
485
+ }
486
+ const defaultLanguageOutputs = function (member, enclosingType, translateFromLanguageId, translateToLanguageIds) {
487
+ if (member.schemaType.jsonType === "object" && member.schemaType.name.startsWith("internationalizedArray")) {
488
+ const pathEnd = member.path.slice(-1);
489
+ const language = sanity.isKeySegment(pathEnd[0]) ? pathEnd[0]._key : null;
490
+ return language === translateFromLanguageId ? translateToLanguageIds.map(translateToId => ({
491
+ id: translateToId,
492
+ outputPath: [...member.path.slice(0, -1), {
493
+ _key: translateToId
494
+ }]
495
+ })) : void 0;
496
+ }
497
+ if (enclosingType.jsonType === "object" && enclosingType.name.startsWith("locale")) {
498
+ return translateFromLanguageId === member.name ? translateToLanguageIds.map(translateToId => ({
499
+ id: translateToId,
500
+ outputPath: [...member.path.slice(0, -1), translateToId]
501
+ })) : void 0;
502
+ }
503
+ return void 0;
504
+ };
505
+ function getFieldLanguageMap(documentSchema, documentMembers, translateFromLanguageId, outputLanguageIds, langFn) {
506
+ var _a, _b, _c;
507
+ const translationMaps = [];
508
+ for (const member of documentMembers) {
509
+ const parentPath = member.path.slice(0, -1);
510
+ const enclosingType = (_b = (_a = documentMembers.find(m => sanity.pathToString(m.path) === sanity.pathToString(parentPath))) == null ? void 0 : _a.schemaType) != null ? _b : documentSchema;
511
+ const translations = (_c = langFn(member, enclosingType, translateFromLanguageId, outputLanguageIds)) == null ? void 0 : _c.filter(translation => translation.id !== translateFromLanguageId);
512
+ if (translations) {
513
+ translationMaps.push({
514
+ inputLanguageId: translateFromLanguageId,
515
+ inputPath: member.path,
516
+ outputs: translations
517
+ });
518
+ }
519
+ }
520
+ return translationMaps;
521
+ }
373
522
  const aiInspectorId = "ai-assistance";
523
+ const assistFormId = "assist";
374
524
  const preventDefault = ev => ev.preventDefault();
375
525
  function DocumentForm(props) {
376
526
  var _a;
@@ -466,7 +616,7 @@ function DocumentForm(props) {
466
616
  changed: formState.changed,
467
617
  focused: formState.focused,
468
618
  groups: formState.groups,
469
- id: "root",
619
+ id: assistFormId,
470
620
  members: formState.members,
471
621
  onChange,
472
622
  onFieldGroupSelect: onSetActiveFieldGroup,
@@ -564,7 +714,7 @@ function getFieldRefs(schemaType, parent) {
564
714
  };
565
715
  const fields = field.type.jsonType === "object" ? getFieldRefs(field.type, fieldRef, depth + 1) : [];
566
716
  const syntheticFields = field.type.jsonType === "array" ? getSyntheticFields(field.type, fieldRef, depth + 1) : [];
567
- if (!isAssistSupported(field.type, true)) {
717
+ if (!isAssistSupported(field.type)) {
568
718
  return [...fields, ...syntheticFields];
569
719
  }
570
720
  return [fieldRef, ...fields, ...syntheticFields];
@@ -591,7 +741,7 @@ function getSyntheticFields(schemaType, parent) {
591
741
  synthetic: true
592
742
  };
593
743
  const fields = itemType.jsonType === "object" ? getFieldRefs(itemType, fieldRef, depth + 1) : [];
594
- if (!isAssistSupported(itemType, true)) {
744
+ if (!isAssistSupported(itemType)) {
595
745
  return fields;
596
746
  }
597
747
  return [fieldRef, ...fields];
@@ -680,7 +830,6 @@ function useStudioAssistDocument(_ref2) {
680
830
  } = _ref2;
681
831
  const documentTypeName = schemaType.name;
682
832
  const currentUser = sanity.useCurrentUser();
683
- const validation = sanity.useValidationStatus(publicId(documentId), schemaType.name).validation;
684
833
  const assistDocument = useDocumentState(assistDocumentId(documentTypeName), assistDocumentTypeName);
685
834
  const assistTasksStatus = useDocumentState(assistTasksStatusId(documentId != null ? documentId : ""), assistTasksStatusTypeName);
686
835
  const client = sanity.useClient({
@@ -705,7 +854,7 @@ function useStudioAssistDocument(_ref2) {
705
854
  return {
706
855
  ...assistField,
707
856
  tasks: tasks.filter(task => task.path === assistField.path),
708
- instructions: (_a2 = assistField.instructions) == null ? void 0 : _a2.filter(p => !p.userId || p.userId === (currentUser == null ? void 0 : currentUser.id)).map(instruction => asStudioInstruction(instruction, tasks, validation))
857
+ instructions: (_a2 = assistField.instructions) == null ? void 0 : _a2.filter(p => !p.userId || p.userId === (currentUser == null ? void 0 : currentUser.id)).map(instruction => asStudioInstruction(instruction, tasks))
709
858
  };
710
859
  });
711
860
  return sanity.typed({
@@ -720,21 +869,12 @@ function useStudioAssistDocument(_ref2) {
720
869
  }),
721
870
  fields
722
871
  });
723
- }, [assistDocument, assistTasksStatus, currentUser, validation]);
872
+ }, [assistDocument, assistTasksStatus, currentUser]);
724
873
  }
725
- function asStudioInstruction(instruction, run, validation) {
726
- var _a;
727
- const errors = validation.filter(marker => marker.level === "error");
728
- const fieldRefs = ((_a = instruction == null ? void 0 : instruction.prompt) != null ? _a : []).flatMap(block => {
729
- if (block._type === "block") {
730
- return block.children.filter(c => c._type === fieldReferenceTypeName);
731
- }
732
- return [];
733
- });
874
+ function asStudioInstruction(instruction, run) {
734
875
  return {
735
876
  ...instruction,
736
- tasks: run.filter(task => task.instructionKey === instruction._key).filter(task => task.started && /* @__PURE__ */new Date().getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs),
737
- validation: errors.filter(marker => fieldRefs.map(r => r.path).filter(p => !!p).find(path => sanity.pathToString(marker.path) === path))
877
+ tasks: run.filter(task => task.instructionKey === instruction._key).filter(task => task.started && ( /* @__PURE__ */new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs)
738
878
  };
739
879
  }
740
880
  function useInterval(ms) {
@@ -815,13 +955,13 @@ function InstructionTaskHistoryButton(props) {
815
955
  const statusDocId = assistTasksStatusId(documentId);
816
956
  const basePath = "".concat(sanity.typed("tasks"), '[_key=="').concat(taskKey, '"]');
817
957
  client.patch(statusDocId).set({
818
- ["".concat(basePath, ".").concat(sanity.typed("ended"))]: /* @__PURE__ */new Date().toISOString(),
958
+ ["".concat(basePath, ".").concat(sanity.typed("ended"))]: ( /* @__PURE__ */new Date()).toISOString(),
819
959
  ["".concat(basePath, ".").concat(sanity.typed("reason"))]: sanity.typed("aborted")
820
960
  }).commit().catch(console.error);
821
961
  }, [client, documentId]);
822
962
  const titledTasks = react.useMemo(() => {
823
963
  var _a2;
824
- const t = (_a2 = tasks == null ? void 0 : tasks.filter(task => task.started && /* @__PURE__ */new Date().getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs).map(task => {
964
+ const t = (_a2 = tasks == null ? void 0 : tasks.filter(task => task.started && ( /* @__PURE__ */new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs).map(task => {
825
965
  var _a3;
826
966
  const instruction = instructions == null ? void 0 : instructions.find(i => i._key === task.instructionKey);
827
967
  return {
@@ -888,11 +1028,10 @@ const TaskStatusButton = react.forwardRef(function TaskStatusButton2(props, ref)
888
1028
  mode: "bleed",
889
1029
  onClick,
890
1030
  tone: hasErrors ? "critical" : void 0,
891
- fontSize: 1,
892
1031
  disabled,
893
1032
  ref,
894
1033
  selected,
895
- tooltip: TASK_STATUS_BUTTON_TOOLTIP_PROPS
1034
+ tooltipProps: TASK_STATUS_BUTTON_TOOLTIP_PROPS
896
1035
  });
897
1036
  });
898
1037
  function TaskList(props) {
@@ -979,6 +1118,54 @@ function useApiClient(customApiClient) {
979
1118
  });
980
1119
  return react.useMemo(() => customApiClient ? customApiClient(client) : client, [client, customApiClient]);
981
1120
  }
1121
+ function useTranslate(apiClient) {
1122
+ const [loading, setLoading] = react.useState(false);
1123
+ const user = sanity.useCurrentUser();
1124
+ const schema = sanity.useSchema();
1125
+ const types = react.useMemo(() => serializeSchema(schema, {
1126
+ leanFormat: true
1127
+ }), [schema]);
1128
+ const toast = ui.useToast();
1129
+ const translate = react.useCallback(_ref4 => {
1130
+ let {
1131
+ documentId,
1132
+ languagePath,
1133
+ translatePath,
1134
+ fieldLanguageMap,
1135
+ conditionalMembers
1136
+ } = _ref4;
1137
+ setLoading(true);
1138
+ return apiClient.request({
1139
+ method: "POST",
1140
+ url: "/assist/tasks/translate/".concat(apiClient.config().dataset, "?projectId=").concat(apiClient.config().projectId),
1141
+ body: {
1142
+ documentId,
1143
+ types,
1144
+ languagePath,
1145
+ fieldLanguageMap,
1146
+ conditionalMembers,
1147
+ translatePath: translatePath.length === 0 ? documentRootKey : sanity.pathToString(translatePath),
1148
+ userId: user == null ? void 0 : user.id
1149
+ }
1150
+ }).catch(e => {
1151
+ toast.push({
1152
+ status: "error",
1153
+ title: "Translate failed",
1154
+ description: e.message
1155
+ });
1156
+ setLoading(false);
1157
+ throw e;
1158
+ }).finally(() => {
1159
+ setTimeout(() => {
1160
+ setLoading(false);
1161
+ }, 2e3);
1162
+ });
1163
+ }, [setLoading, apiClient, toast, user, types]);
1164
+ return react.useMemo(() => ({
1165
+ translate,
1166
+ loading
1167
+ }), [translate, loading]);
1168
+ }
982
1169
  function useGenerateCaption(apiClient) {
983
1170
  const [loading, setLoading] = react.useState(false);
984
1171
  const user = sanity.useCurrentUser();
@@ -987,11 +1174,11 @@ function useGenerateCaption(apiClient) {
987
1174
  leanFormat: true
988
1175
  }), [schema]);
989
1176
  const toast = ui.useToast();
990
- const generateCaption = react.useCallback(_ref4 => {
1177
+ const generateCaption = react.useCallback(_ref5 => {
991
1178
  let {
992
1179
  path,
993
1180
  documentId
994
- } = _ref4;
1181
+ } = _ref5;
995
1182
  setLoading(true);
996
1183
  return apiClient.request({
997
1184
  method: "POST",
@@ -1005,7 +1192,7 @@ function useGenerateCaption(apiClient) {
1005
1192
  }).catch(e => {
1006
1193
  toast.push({
1007
1194
  status: "error",
1008
- title: "Generate caption failed",
1195
+ title: "Generate image description failed",
1009
1196
  description: e.message
1010
1197
  });
1011
1198
  setLoading(false);
@@ -1021,6 +1208,48 @@ function useGenerateCaption(apiClient) {
1021
1208
  loading
1022
1209
  }), [generateCaption, loading]);
1023
1210
  }
1211
+ function useGenerateImage(apiClient) {
1212
+ const [loading, setLoading] = react.useState(false);
1213
+ const user = sanity.useCurrentUser();
1214
+ const schema = sanity.useSchema();
1215
+ const types = react.useMemo(() => serializeSchema(schema, {
1216
+ leanFormat: true
1217
+ }), [schema]);
1218
+ const toast = ui.useToast();
1219
+ const generateImage = react.useCallback(_ref6 => {
1220
+ let {
1221
+ path,
1222
+ documentId
1223
+ } = _ref6;
1224
+ setLoading(true);
1225
+ return apiClient.request({
1226
+ method: "POST",
1227
+ url: "/assist/tasks/generate-image/".concat(apiClient.config().dataset, "?projectId=").concat(apiClient.config().projectId),
1228
+ body: {
1229
+ path,
1230
+ documentId,
1231
+ types,
1232
+ userId: user == null ? void 0 : user.id
1233
+ }
1234
+ }).catch(e => {
1235
+ toast.push({
1236
+ status: "error",
1237
+ title: "Generate image from prompt failed",
1238
+ description: e.message
1239
+ });
1240
+ setLoading(false);
1241
+ throw e;
1242
+ }).finally(() => {
1243
+ setTimeout(() => {
1244
+ setLoading(false);
1245
+ }, 2e3);
1246
+ });
1247
+ }, [setLoading, apiClient, toast, user, types]);
1248
+ return react.useMemo(() => ({
1249
+ generateImage,
1250
+ loading
1251
+ }), [generateImage, loading]);
1252
+ }
1024
1253
  function useGetInstructStatus(apiClient) {
1025
1254
  const [loading, setLoading] = react.useState(true);
1026
1255
  const getInstructStatus = react.useCallback(async () => {
@@ -1210,8 +1439,8 @@ function RunInstructionProvider(props) {
1210
1439
  runInstructionRequest({
1211
1440
  ...request,
1212
1441
  instructionKey: instruction._key,
1213
- userTexts: Object.entries(inputs).map(_ref5 => {
1214
- let [key, value] = _ref5;
1442
+ userTexts: Object.entries(inputs).map(_ref7 => {
1443
+ let [key, value] = _ref7;
1215
1444
  return {
1216
1445
  blockKey: key,
1217
1446
  userInput: value
@@ -1224,8 +1453,8 @@ function RunInstructionProvider(props) {
1224
1453
  const open = !!runRequest;
1225
1454
  const runDisabled = react.useMemo(() => {
1226
1455
  var _a2, _b;
1227
- return ((_b = (_a2 = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a2.length) != null ? _b : 0) > Object.entries(inputs).filter(_ref6 => {
1228
- let [, value] = _ref6;
1456
+ return ((_b = (_a2 = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a2.length) != null ? _b : 0) > Object.entries(inputs).filter(_ref8 => {
1457
+ let [, value] = _ref8;
1229
1458
  return !!value;
1230
1459
  }).length;
1231
1460
  }, [runRequest == null ? void 0 : runRequest.userInputBlocks, inputs]);
@@ -1336,29 +1565,37 @@ function getAssistableDocId(documentSchemaType, documentId) {
1336
1565
  return documentSchemaType.liveEdit ? baseId : "drafts.".concat(baseId);
1337
1566
  }
1338
1567
  function useRequestRunInstruction(args) {
1339
- const {
1340
- documentOnChange,
1341
- isDocAssistable: isDocAssistable2
1342
- } = args;
1343
1568
  const {
1344
1569
  runInstruction,
1345
1570
  instructionLoading
1346
1571
  } = useRunInstruction();
1347
- const [queuedTask, setQueuedTask] = react.useState(void 0);
1348
- react.useEffect(() => {
1349
- if (queuedTask && isDocAssistable2) {
1350
- runInstruction(queuedTask);
1351
- setQueuedTask(void 0);
1352
- }
1353
- }, [queuedTask, isDocAssistable2, runInstruction]);
1572
+ const requestRunInstruction = useDraftDelayedTask({
1573
+ ...args,
1574
+ task: runInstruction
1575
+ });
1354
1576
  return {
1355
1577
  instructionLoading,
1356
- requestRunInstruction: react.useCallback(task => {
1357
- documentOnChange(sanity.PatchEvent.from([sanity.unset(["_force_document_creation"])]));
1358
- setQueuedTask(task);
1359
- }, [setQueuedTask, documentOnChange])
1578
+ requestRunInstruction
1360
1579
  };
1361
1580
  }
1581
+ function useDraftDelayedTask(args) {
1582
+ const {
1583
+ documentOnChange,
1584
+ isDocAssistable: isDocAssistable2,
1585
+ task
1586
+ } = args;
1587
+ const [queuedArgs, setQueuedArgs] = react.useState(void 0);
1588
+ react.useEffect(() => {
1589
+ if (queuedArgs && isDocAssistable2) {
1590
+ task(queuedArgs);
1591
+ setQueuedArgs(void 0);
1592
+ }
1593
+ }, [queuedArgs, isDocAssistable2, task]);
1594
+ return react.useCallback(taskArgs => {
1595
+ documentOnChange(sanity.PatchEvent.from([sanity.unset(["_force_document_creation"])]));
1596
+ setQueuedArgs(taskArgs);
1597
+ }, [setQueuedArgs, documentOnChange]);
1598
+ }
1362
1599
  const SparklesIllustration = styled__default.default(icons.SparklesIcon)({
1363
1600
  fontSize: "3.125em",
1364
1601
  "& path": {
@@ -1609,13 +1846,13 @@ function useSelectedSchema(fieldPath, documentSchema) {
1609
1846
  return currentSchema;
1610
1847
  }, [documentSchema, fieldPath]);
1611
1848
  }
1612
- function FieldsInitializer(_ref7) {
1849
+ function FieldsInitializer(_ref9) {
1613
1850
  let {
1614
1851
  pathKey,
1615
1852
  activePath,
1616
1853
  fieldExists,
1617
1854
  onChange
1618
- } = _ref7;
1855
+ } = _ref9;
1619
1856
  const initialized = react.useRef(false);
1620
1857
  react.useEffect(() => {
1621
1858
  if (initialized.current || fieldExists || activePath || !pathKey) {
@@ -1646,7 +1883,7 @@ function FieldAutocomplete(props) {
1646
1883
  return getFieldRefs(schemaType);
1647
1884
  }, [schemaType, includeDocument]);
1648
1885
  const currentField = react.useMemo(() => fieldRefs.find(f => f.key === fieldPath), [fieldPath, fieldRefs]);
1649
- const autocompleteOptions = react.useMemo(() => fieldRefs.filter(field => filter ? filter(field) : true).map(field => ({
1886
+ const autocompleteOptions = react.useMemo(() => fieldRefs.filter(field => filter ? filter(field) : true).filter(f => !isType(f.schemaType, "reference")).map(field => ({
1650
1887
  value: field.key,
1651
1888
  field
1652
1889
  })), [fieldRefs, filter]);
@@ -1759,6 +1996,78 @@ function FieldTitle(props) {
1759
1996
  })
1760
1997
  });
1761
1998
  }
1999
+ const MAX_DEPTH = 8;
2000
+ function getConditionalMembers(docState) {
2001
+ const doc = {
2002
+ path: "",
2003
+ hidden: false,
2004
+ readOnly: !!docState.readOnly,
2005
+ conditional: typeof docState.schemaType.hidden === "function"
2006
+ };
2007
+ return [doc, ...extractConditionalPaths(docState, MAX_DEPTH)].filter(v => v.conditional).map(_ref10 => {
2008
+ let {
2009
+ conditional,
2010
+ ...state
2011
+ } = _ref10;
2012
+ return {
2013
+ ...state
2014
+ };
2015
+ });
2016
+ }
2017
+ function isConditional(schemaType) {
2018
+ return typeof schemaType.hidden === "function" || typeof schemaType.readOnly === "function";
2019
+ }
2020
+ function conditionalState(memberState) {
2021
+ return {
2022
+ path: sanity.pathToString(memberState.path),
2023
+ readOnly: !!memberState.readOnly,
2024
+ hidden: false,
2025
+ // if its in members, its not hidden
2026
+ conditional: isConditional(memberState.schemaType)
2027
+ };
2028
+ }
2029
+ function extractConditionalPaths(node, maxDepth) {
2030
+ if (node.path.length >= maxDepth) {
2031
+ return [];
2032
+ }
2033
+ return node.members.reduce((acc, member) => {
2034
+ var _a, _b;
2035
+ if (member.kind === "error") {
2036
+ return acc;
2037
+ }
2038
+ if (member.kind === "field") {
2039
+ const schemaType = member.field.schemaType;
2040
+ if (schemaType.jsonType === "object") {
2041
+ const innerFields = member.field.readOnly ? [] : extractConditionalPaths(member.field, maxDepth);
2042
+ return [...acc, conditionalState(member.field), ...innerFields];
2043
+ } else if (schemaType.jsonType === "array") {
2044
+ const array = member.field;
2045
+ let arrayPaths = [];
2046
+ const isObjectsArray = array.members.some(m => m.kind === "item" && sanity.isObjectSchemaType(m.item.schemaType));
2047
+ if (!array.readOnly) {
2048
+ for (const arrayMember of array.members) {
2049
+ if (arrayMember.kind === "error") {
2050
+ continue;
2051
+ }
2052
+ const innerFields = isObjectsArray && !arrayMember.item.readOnly ? extractConditionalPaths(arrayMember.item, maxDepth) : [];
2053
+ arrayPaths = [...arrayPaths, conditionalState(arrayMember.item), ...innerFields];
2054
+ }
2055
+ }
2056
+ return [...acc, conditionalState(array), ...arrayPaths];
2057
+ }
2058
+ return [...acc, conditionalState(member.field)];
2059
+ } else if (member.kind === "fieldSet") {
2060
+ const conditionalFieldset = !!((_b = (_a = node.schemaType) == null ? void 0 : _a.fieldsets) == null ? void 0 : _b.some(f => !f.single && f.name === member.fieldSet.name && typeof f.hidden === "function"));
2061
+ const innerFields = extractConditionalPaths(member.fieldSet, maxDepth).map(f => ({
2062
+ ...f,
2063
+ // if fieldset is conditional, visible fields must also be considered conditional
2064
+ conditional: conditionalFieldset != null ? conditionalFieldset : f.conditional
2065
+ }));
2066
+ return [...acc, ...innerFields];
2067
+ }
2068
+ return acc;
2069
+ }, []);
2070
+ }
1762
2071
  var __freeze$4 = Object.freeze;
1763
2072
  var __defProp$4 = Object.defineProperty;
1764
2073
  var __template$4 = (cooked, raw) => __freeze$4(__defProp$4(cooked, "raw", {
@@ -1898,12 +2207,15 @@ function AssistInspector(props) {
1898
2207
  documentType,
1899
2208
  value: docValue,
1900
2209
  schemaType,
1901
- onChange: documentOnChange
2210
+ onChange: documentOnChange,
2211
+ formState
1902
2212
  } = documentPane;
1903
2213
  const {
1904
2214
  published,
1905
2215
  draft
1906
2216
  } = sanity.useEditState(documentId, documentType, "low");
2217
+ const formStateRef = react.useRef(formState);
2218
+ formStateRef.current = formState;
1907
2219
  const assistableDocId = getAssistableDocId(schemaType, documentId);
1908
2220
  const {
1909
2221
  instructionLoading,
@@ -1957,7 +2269,8 @@ function AssistInspector(props) {
1957
2269
  path: pathKey,
1958
2270
  typePath,
1959
2271
  assistDocumentId: assistDocumentId(documentType),
1960
- instruction
2272
+ instruction,
2273
+ conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
1961
2274
  }), [pathKey, instruction, typePath, documentType, assistableDocId, requestRunInstruction]);
1962
2275
  const Region = react.useCallback(_props => {
1963
2276
  return /* @__PURE__ */jsxRuntime.jsx("div", {
@@ -2143,10 +2456,10 @@ const assistInspector = {
2143
2456
  showAsAction: false
2144
2457
  }),
2145
2458
  component: AssistInspectorWrapper,
2146
- onClose(_ref8) {
2459
+ onClose(_ref11) {
2147
2460
  let {
2148
2461
  params
2149
- } = _ref8;
2462
+ } = _ref11;
2150
2463
  return {
2151
2464
  params: sanity.typed({
2152
2465
  ...params,
@@ -2174,7 +2487,7 @@ function useAssistPresence(path, showFocusWithin) {
2174
2487
  const activePresence = (_b = (_a = tasks == null ? void 0 : tasks.filter(task => !task.ended)) == null ? void 0 : _a.flatMap(task => {
2175
2488
  var _a2;
2176
2489
  return (_a2 = task.presence) != null ? _a2 : [];
2177
- })) == null ? void 0 : _b.filter(p => p.started && /* @__PURE__ */new Date().getTime() - new Date(p.started).getTime() < maxHistoryVisibilityMs).filter(presence => {
2490
+ })) == null ? void 0 : _b.filter(p => p.started && ( /* @__PURE__ */new Date()).getTime() - new Date(p.started).getTime() < maxHistoryVisibilityMs).filter(presence => {
2178
2491
  if (!presence.path || !path.length) {
2179
2492
  return false;
2180
2493
  }
@@ -2208,7 +2521,7 @@ function aiPresence(presence, path, title) {
2208
2521
  },
2209
2522
  path,
2210
2523
  sessionId: "not-available",
2211
- lastActiveAt: (_a = presence == null ? void 0 : presence.started) != null ? _a : /* @__PURE__ */new Date().toISOString()
2524
+ lastActiveAt: (_a = presence == null ? void 0 : presence.started) != null ? _a : ( /* @__PURE__ */new Date()).toISOString()
2212
2525
  };
2213
2526
  }
2214
2527
  var __freeze$3 = Object.freeze;
@@ -2219,11 +2532,11 @@ var __template$3 = (cooked, raw) => __freeze$3(__defProp$3(cooked, "raw", {
2219
2532
  var _a$3, _b$1;
2220
2533
  const fadeIn = styled.keyframes(_a$3 || (_a$3 = __template$3(["\n 0% {\n opacity: 0;\n transform: scale(0.75);\n }\n 40% {\n opacity: 0;\n transform: scale(0.75);\n }\n 100% {\n opacity: 1;\n transform: scale(1);\n }\n"])));
2221
2534
  const FadeInDiv = styled__default.default.div(_b$1 || (_b$1 = __template$3(["\n animation-name: ", ";\n animation-timing-function: ease-in-out;\n"])), fadeIn);
2222
- const FadeInContent = react.forwardRef(function FadeInContent2(_ref9, ref) {
2535
+ const FadeInContent = react.forwardRef(function FadeInContent2(_ref12, ref) {
2223
2536
  let {
2224
2537
  children,
2225
2538
  durationMs = 250
2226
- } = _ref9;
2539
+ } = _ref12;
2227
2540
  return /* @__PURE__ */jsxRuntime.jsx(FadeInDiv, {
2228
2541
  ref,
2229
2542
  style: {
@@ -2235,47 +2548,47 @@ const FadeInContent = react.forwardRef(function FadeInContent2(_ref9, ref) {
2235
2548
  const purple = {
2236
2549
  "50": {
2237
2550
  title: "Purple 50",
2238
- hex: "#f8e9fe"
2551
+ hex: "#f8f5ff"
2239
2552
  },
2240
2553
  "100": {
2241
2554
  title: "Purple 100",
2242
- hex: "#f2d3fe"
2555
+ hex: "#f1ebff"
2243
2556
  },
2244
2557
  "200": {
2245
2558
  title: "Purple 200",
2246
- hex: "#e6a7fd"
2559
+ hex: "#ece1fe"
2247
2560
  },
2248
2561
  "300": {
2249
2562
  title: "Purple 300",
2250
- hex: "#d97bfd"
2563
+ hex: "#ccb1fc"
2251
2564
  },
2252
2565
  "400": {
2253
2566
  title: "Purple 400",
2254
- hex: "#cd4efc"
2567
+ hex: "#b087f7"
2255
2568
  },
2256
2569
  "500": {
2257
2570
  title: "Purple 500",
2258
- hex: "#c123fc"
2571
+ hex: "#8f57ef"
2259
2572
  },
2260
2573
  "600": {
2261
2574
  title: "Purple 600",
2262
- hex: "#9d1fcd"
2575
+ hex: "#721fe5"
2263
2576
  },
2264
2577
  "700": {
2265
2578
  title: "Purple 700",
2266
- hex: "#7a1b9e"
2579
+ hex: "#4c1a9e"
2267
2580
  },
2268
2581
  "800": {
2269
2582
  title: "Purple 800",
2270
- hex: "#56186f"
2583
+ hex: "#2f1862"
2271
2584
  },
2272
2585
  "900": {
2273
2586
  title: "Purple 900",
2274
- hex: "#331440"
2587
+ hex: "#23173f"
2275
2588
  },
2276
2589
  "950": {
2277
2590
  title: "Purple 950",
2278
- hex: "#211229"
2591
+ hex: "#181128"
2279
2592
  }
2280
2593
  };
2281
2594
  var __freeze$2 = Object.freeze;
@@ -2326,7 +2639,11 @@ function AssistAvatar(props) {
2326
2639
  style: {
2327
2640
  color: "inherit"
2328
2641
  },
2329
- children: /* @__PURE__ */jsxRuntime.jsx(icons.SparklesIcon, {})
2642
+ children: /* @__PURE__ */jsxRuntime.jsx(icons.SparklesIcon, {
2643
+ style: {
2644
+ color: "inherit"
2645
+ }
2646
+ })
2330
2647
  })
2331
2648
  })]
2332
2649
  });
@@ -2472,7 +2789,7 @@ function AssistFieldWrapper(props) {
2472
2789
  if (!isSupported || schemaType.name.startsWith("sanity.") || schemaType.name === contextDocumentTypeName) {
2473
2790
  return props.renderDefault(props);
2474
2791
  }
2475
- if (!isType(props.schemaType, "document") && props.inputId !== "root") {
2792
+ if (!isType(props.schemaType, "document") && props.inputId !== "root" && props.inputId !== assistFormId) {
2476
2793
  return /* @__PURE__ */jsxRuntime.jsx(AssistField, {
2477
2794
  ...props,
2478
2795
  children: props.children
@@ -2492,15 +2809,16 @@ function AssistField(props) {
2492
2809
  showOnboarding,
2493
2810
  dismissOnboarding
2494
2811
  } = useOnboardingFeature(fieldOnboardingKey);
2812
+ const singlePresence = presence[0];
2495
2813
  const actions = /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
2496
2814
  gap: 2,
2497
2815
  align: "center",
2498
2816
  justify: "space-between",
2499
- children: [presence.map(pre => /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
2817
+ children: [singlePresence && /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
2500
2818
  children: /* @__PURE__ */jsxRuntime.jsx(AiFieldPresence, {
2501
- presence: pre
2502
- }, pre.lastActiveAt)
2503
- }, pre.user.id)), isFirstAssisted && showOnboarding && /* @__PURE__ */jsxRuntime.jsx(AssistOnboardingPopover, {
2819
+ presence: singlePresence
2820
+ })
2821
+ }), isFirstAssisted && showOnboarding && /* @__PURE__ */jsxRuntime.jsx(AssistOnboardingPopover, {
2504
2822
  dismiss: dismissOnboarding
2505
2823
  })]
2506
2824
  });
@@ -2972,7 +3290,6 @@ function AssistConnectorsOverlay(props) {
2972
3290
  zIndex: 150
2973
3291
  // zIndex,
2974
3292
  },
2975
-
2976
3293
  children: connectors.map(connector => /* @__PURE__ */jsxRuntime.jsx(ConnectorPath, {
2977
3294
  from: connector.from,
2978
3295
  options,
@@ -2981,253 +3298,1500 @@ function AssistConnectorsOverlay(props) {
2981
3298
  }), DEBUG]
2982
3299
  });
2983
3300
  }
2984
- const legacyAssistDocumentIdPrefix = "sanity.ai.";
2985
- const legacyAssistDocumentTypeName = "sanity.ai.docType";
2986
- const legacyContextDocumentTypeName = "ai.instruction.context";
2987
- const legacyAssistStatusDocumentTypeName = "sanity.ai.instructionStatus";
2988
- const NO_ASSIST_DOCS = [];
2989
- const NO_CONTEXT_DOCS = [];
2990
- const NO_IDS = [];
2991
- function AlphaMigration() {
2992
- const [alphaAssistDocs, setAlphaAssistDocs] = react.useState(NO_ASSIST_DOCS);
2993
- const [contextDocs, setContextDocs] = react.useState(NO_CONTEXT_DOCS);
2994
- const [staleStatusDocIds, setStaleStatusDocs] = react.useState(NO_IDS);
2995
- const [error, setError] = react.useState(void 0);
2996
- const [progress, setProgress] = react.useState(void 0);
2997
- const toast = ui.useToast();
2998
- const client = sanity.useClient({
2999
- apiVersion: "2023-06-01"
3000
- });
3001
- react.useEffect(() => {
3002
- let canUpdate = true;
3003
- client.fetch('\n {\n "assistDocs": *[_type=="'.concat(legacyAssistDocumentTypeName, '"],\n "staleStatusDocIds": *[_type=="').concat(legacyAssistStatusDocumentTypeName, '"]._id,\n "contextDocs": *[_type=="').concat(legacyContextDocumentTypeName, '"],\n }\n ')).then(result => {
3004
- var _a, _b, _c;
3005
- if (!canUpdate || !result) {
3006
- return;
3007
- }
3008
- setAlphaAssistDocs((_a = result == null ? void 0 : result.assistDocs) != null ? _a : NO_ASSIST_DOCS);
3009
- setStaleStatusDocs((_b = result == null ? void 0 : result.staleStatusDocIds) != null ? _b : NO_IDS);
3010
- setContextDocs((_c = result == null ? void 0 : result.contextDocs) != null ? _c : NO_CONTEXT_DOCS);
3011
- });
3012
- return () => {
3013
- canUpdate = false;
3014
- };
3015
- }, [client, setAlphaAssistDocs, setStaleStatusDocs, setContextDocs]);
3016
- const convert = react.useCallback(async () => {
3017
- try {
3018
- setProgress(1e-4);
3019
- const tasks = [() => convertContextDocs(client, contextDocs), subtaskProgress => deleteDocs(client, staleStatusDocIds, subtaskProgress), subtaskProgress => convertDocs(client, alphaAssistDocs, subtaskProgress), subtaskProgress => deleteDocs(client, contextDocs.map(d => d._id), subtaskProgress)];
3020
- const taskSize = 1 / tasks.length;
3021
- for (let i = 0; i < tasks.length; i++) {
3022
- const startProgress = i / tasks.length;
3023
- await tasks[i](subProgress => setProgress(startProgress + subProgress * taskSize));
3024
- setProgress((i + 1) / tasks.length);
3025
- }
3026
- setProgress(1);
3027
- setAlphaAssistDocs(NO_ASSIST_DOCS);
3028
- setContextDocs(NO_CONTEXT_DOCS);
3029
- setStaleStatusDocs(NO_IDS);
3030
- toast.push({
3031
- title: "Converted instructions to new format.",
3032
- status: "success",
3033
- closable: true
3034
- });
3035
- } catch (e) {
3036
- console.error(e);
3037
- toast.push({
3038
- title: "An error occurred",
3039
- status: "error",
3040
- closable: true
3041
- });
3042
- setError(e);
3043
- setProgress(void 0);
3301
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3302
+ function getDefaultExportFromCjs(x) {
3303
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3304
+ }
3305
+
3306
+ /**
3307
+ * Checks if `value` is classified as an `Array` object.
3308
+ *
3309
+ * @static
3310
+ * @memberOf _
3311
+ * @since 0.1.0
3312
+ * @category Lang
3313
+ * @param {*} value The value to check.
3314
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
3315
+ * @example
3316
+ *
3317
+ * _.isArray([1, 2, 3]);
3318
+ * // => true
3319
+ *
3320
+ * _.isArray(document.body.children);
3321
+ * // => false
3322
+ *
3323
+ * _.isArray('abc');
3324
+ * // => false
3325
+ *
3326
+ * _.isArray(_.noop);
3327
+ * // => false
3328
+ */
3329
+
3330
+ var isArray$3 = Array.isArray;
3331
+ var isArray_1 = isArray$3;
3332
+
3333
+ /** Detect free variable `global` from Node.js. */
3334
+
3335
+ var freeGlobal$1 = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
3336
+ var _freeGlobal = freeGlobal$1;
3337
+ var freeGlobal = _freeGlobal;
3338
+
3339
+ /** Detect free variable `self`. */
3340
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
3341
+
3342
+ /** Used as a reference to the global object. */
3343
+ var root$3 = freeGlobal || freeSelf || Function('return this')();
3344
+ var _root = root$3;
3345
+ var root$2 = _root;
3346
+
3347
+ /** Built-in value references. */
3348
+ var Symbol$3 = root$2.Symbol;
3349
+ var _Symbol = Symbol$3;
3350
+ var Symbol$2 = _Symbol;
3351
+
3352
+ /** Used for built-in method references. */
3353
+ var objectProto$4 = Object.prototype;
3354
+
3355
+ /** Used to check objects for own properties. */
3356
+ var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
3357
+
3358
+ /**
3359
+ * Used to resolve the
3360
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3361
+ * of values.
3362
+ */
3363
+ var nativeObjectToString$1 = objectProto$4.toString;
3364
+
3365
+ /** Built-in value references. */
3366
+ var symToStringTag$1 = Symbol$2 ? Symbol$2.toStringTag : undefined;
3367
+
3368
+ /**
3369
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3370
+ *
3371
+ * @private
3372
+ * @param {*} value The value to query.
3373
+ * @returns {string} Returns the raw `toStringTag`.
3374
+ */
3375
+ function getRawTag$1(value) {
3376
+ var isOwn = hasOwnProperty$3.call(value, symToStringTag$1),
3377
+ tag = value[symToStringTag$1];
3378
+ try {
3379
+ value[symToStringTag$1] = undefined;
3380
+ var unmasked = true;
3381
+ } catch (e) {}
3382
+ var result = nativeObjectToString$1.call(value);
3383
+ if (unmasked) {
3384
+ if (isOwn) {
3385
+ value[symToStringTag$1] = tag;
3386
+ } else {
3387
+ delete value[symToStringTag$1];
3044
3388
  }
3045
- }, [contextDocs, client, alphaAssistDocs, staleStatusDocIds, setProgress, toast]);
3046
- if ((alphaAssistDocs.length || staleStatusDocIds.length || contextDocs.length) && (!progress || progress < 1)) {
3047
- return /* @__PURE__ */jsxRuntime.jsx(ui.Dialog, {
3048
- id: "outdated-assist-docs",
3049
- header: pluginTitle,
3050
- children: /* @__PURE__ */jsxRuntime.jsx(ui.Card, {
3051
- padding: 3,
3052
- children: /* @__PURE__ */jsxRuntime.jsxs(ui.Stack, {
3053
- space: 4,
3054
- style: {
3055
- maxWidth: 500
3056
- },
3057
- children: [/* @__PURE__ */jsxRuntime.jsxs(ui.Text, {
3058
- size: 1,
3059
- children: ["It seems like this workspace contains documents from an", " ", /* @__PURE__ */jsxRuntime.jsxs("strong", {
3060
- children: ["older version of ", pluginTitle]
3061
- }), "."]
3062
- }), /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
3063
- size: 1,
3064
- children: "Cleanup is required."
3065
- }), error ? /* @__PURE__ */jsxRuntime.jsxs(ui.Card, {
3066
- padding: 2,
3067
- tone: "critical",
3068
- border: true,
3069
- children: [/* @__PURE__ */jsxRuntime.jsx(ui.Text, {
3070
- size: 1,
3071
- children: "An error occurred. See console for details."
3072
- }), " "]
3073
- }) : null, /* @__PURE__ */jsxRuntime.jsx(ui.Button, {
3074
- icon: progress ? /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
3075
- style: {
3076
- marginTop: 5
3077
- },
3078
- children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {})
3079
- }) : icons.CheckmarkIcon,
3080
- disabled: !!progress,
3081
- text: progress ? "".concat(Math.floor(progress * 100), "%") : "Ok, convert to new format!",
3082
- tone: "primary",
3083
- onClick: convert
3084
- })]
3085
- })
3086
- })
3087
- });
3088
3389
  }
3089
- return null;
3390
+ return result;
3090
3391
  }
3091
- async function deleteDocs(client, ids, updateProgress) {
3092
- const chunkSize = 50;
3093
- for (let i = 0; i < ids.length; i += chunkSize) {
3094
- const progressCount = Math.min(ids.length, i + chunkSize);
3095
- const chunk = ids.slice(i, progressCount);
3096
- const trans = client.transaction();
3097
- chunk.forEach(id => trans.delete(id));
3098
- await trans.commit();
3099
- updateProgress(progressCount / ids.length);
3392
+ var _getRawTag = getRawTag$1;
3393
+
3394
+ /** Used for built-in method references. */
3395
+
3396
+ var objectProto$3 = Object.prototype;
3397
+
3398
+ /**
3399
+ * Used to resolve the
3400
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3401
+ * of values.
3402
+ */
3403
+ var nativeObjectToString = objectProto$3.toString;
3404
+
3405
+ /**
3406
+ * Converts `value` to a string using `Object.prototype.toString`.
3407
+ *
3408
+ * @private
3409
+ * @param {*} value The value to convert.
3410
+ * @returns {string} Returns the converted string.
3411
+ */
3412
+ function objectToString$1(value) {
3413
+ return nativeObjectToString.call(value);
3414
+ }
3415
+ var _objectToString = objectToString$1;
3416
+ var Symbol$1 = _Symbol,
3417
+ getRawTag = _getRawTag,
3418
+ objectToString = _objectToString;
3419
+
3420
+ /** `Object#toString` result references. */
3421
+ var nullTag = '[object Null]',
3422
+ undefinedTag = '[object Undefined]';
3423
+
3424
+ /** Built-in value references. */
3425
+ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
3426
+
3427
+ /**
3428
+ * The base implementation of `getTag` without fallbacks for buggy environments.
3429
+ *
3430
+ * @private
3431
+ * @param {*} value The value to query.
3432
+ * @returns {string} Returns the `toStringTag`.
3433
+ */
3434
+ function baseGetTag$2(value) {
3435
+ if (value == null) {
3436
+ return value === undefined ? undefinedTag : nullTag;
3100
3437
  }
3438
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
3101
3439
  }
3102
- async function convertContextDocs(client, docs) {
3103
- const trans = client.transaction();
3104
- for (const doc of docs) {
3105
- const {
3106
- _id,
3107
- _type,
3108
- ...rest
3109
- } = doc;
3110
- trans.createOrReplace({
3111
- ...rest,
3112
- _id: "port.".concat(_id),
3113
- _alphaId: _id,
3114
- _type: contextDocumentTypeName
3115
- });
3440
+ var _baseGetTag = baseGetTag$2;
3441
+
3442
+ /**
3443
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
3444
+ * and has a `typeof` result of "object".
3445
+ *
3446
+ * @static
3447
+ * @memberOf _
3448
+ * @since 4.0.0
3449
+ * @category Lang
3450
+ * @param {*} value The value to check.
3451
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3452
+ * @example
3453
+ *
3454
+ * _.isObjectLike({});
3455
+ * // => true
3456
+ *
3457
+ * _.isObjectLike([1, 2, 3]);
3458
+ * // => true
3459
+ *
3460
+ * _.isObjectLike(_.noop);
3461
+ * // => false
3462
+ *
3463
+ * _.isObjectLike(null);
3464
+ * // => false
3465
+ */
3466
+
3467
+ function isObjectLike$1(value) {
3468
+ return value != null && typeof value == 'object';
3469
+ }
3470
+ var isObjectLike_1 = isObjectLike$1;
3471
+ var baseGetTag$1 = _baseGetTag,
3472
+ isObjectLike = isObjectLike_1;
3473
+
3474
+ /** `Object#toString` result references. */
3475
+ var symbolTag = '[object Symbol]';
3476
+
3477
+ /**
3478
+ * Checks if `value` is classified as a `Symbol` primitive or object.
3479
+ *
3480
+ * @static
3481
+ * @memberOf _
3482
+ * @since 4.0.0
3483
+ * @category Lang
3484
+ * @param {*} value The value to check.
3485
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
3486
+ * @example
3487
+ *
3488
+ * _.isSymbol(Symbol.iterator);
3489
+ * // => true
3490
+ *
3491
+ * _.isSymbol('abc');
3492
+ * // => false
3493
+ */
3494
+ function isSymbol$3(value) {
3495
+ return typeof value == 'symbol' || isObjectLike(value) && baseGetTag$1(value) == symbolTag;
3496
+ }
3497
+ var isSymbol_1 = isSymbol$3;
3498
+ var isArray$2 = isArray_1,
3499
+ isSymbol$2 = isSymbol_1;
3500
+
3501
+ /** Used to match property names within property paths. */
3502
+ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
3503
+ reIsPlainProp = /^\w*$/;
3504
+
3505
+ /**
3506
+ * Checks if `value` is a property name and not a property path.
3507
+ *
3508
+ * @private
3509
+ * @param {*} value The value to check.
3510
+ * @param {Object} [object] The object to query keys on.
3511
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
3512
+ */
3513
+ function isKey$1(value, object) {
3514
+ if (isArray$2(value)) {
3515
+ return false;
3116
3516
  }
3117
- await trans.commit();
3118
- }
3119
- async function convertDocs(client, docs, updateProgress) {
3120
- const chunkSize = 10;
3121
- for (let i = 0; i < docs.length; i += chunkSize) {
3122
- const progressCount = Math.min(docs.length, i + chunkSize);
3123
- const chunk = docs.slice(i, progressCount);
3124
- const trans = client.transaction();
3125
- const contextDocs = await client.fetch('*[_type=="'.concat(contextDocumentTypeName, '" && _alphaId != null]{_id, _alphaId}'));
3126
- chunk.forEach(oldDoc => {
3127
- var _a;
3128
- const documentType = oldDoc._id.replace(new RegExp("^(".concat(legacyAssistDocumentIdPrefix, "|").concat(assistDocumentIdPrefix, ")")), "");
3129
- const id = assistDocumentId(documentType);
3130
- const fields = ((_a = oldDoc.fields) != null ? _a : []).filter(field => {
3131
- var _a2;
3132
- return (_a2 = field.instructions) == null ? void 0 : _a2.length;
3133
- }).map(oldField => {
3134
- var _a2;
3135
- const instructions = ((_a2 = oldField.instructions) != null ? _a2 : []).map(inst => {
3136
- var _a3;
3137
- const prompt = ((_a3 = inst.prompt) != null ? _a3 : []).map(block => {
3138
- return mapBlock(block, contextDocs);
3139
- });
3140
- return {
3141
- ...inst,
3142
- _type: instructionTypeName,
3143
- prompt
3144
- };
3145
- });
3146
- return {
3147
- ...oldField,
3148
- _type: assistFieldTypeName,
3149
- instructions
3150
- };
3151
- });
3152
- if (fields.length) {
3153
- trans.createOrReplace({
3154
- _id: id,
3155
- _type: assistDocumentTypeName,
3156
- fields
3157
- });
3158
- }
3159
- trans.delete(oldDoc._id);
3160
- });
3161
- await trans.commit();
3162
- updateProgress(progressCount / docs.length);
3517
+ var type = typeof value;
3518
+ if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol$2(value)) {
3519
+ return true;
3163
3520
  }
3521
+ return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
3164
3522
  }
3165
- function isFieldRef(block) {
3166
- return block._type === "sanity.ai.prompt.fieldRef";
3167
- }
3168
- function isContext(block) {
3169
- return block._type === "sanity.ai.prompt.context";
3523
+ var _isKey = isKey$1;
3524
+
3525
+ /**
3526
+ * Checks if `value` is the
3527
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
3528
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
3529
+ *
3530
+ * @static
3531
+ * @memberOf _
3532
+ * @since 0.1.0
3533
+ * @category Lang
3534
+ * @param {*} value The value to check.
3535
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
3536
+ * @example
3537
+ *
3538
+ * _.isObject({});
3539
+ * // => true
3540
+ *
3541
+ * _.isObject([1, 2, 3]);
3542
+ * // => true
3543
+ *
3544
+ * _.isObject(_.noop);
3545
+ * // => true
3546
+ *
3547
+ * _.isObject(null);
3548
+ * // => false
3549
+ */
3550
+
3551
+ function isObject$2(value) {
3552
+ var type = typeof value;
3553
+ return value != null && (type == 'object' || type == 'function');
3170
3554
  }
3171
- function isUserInput(block) {
3172
- return block._type === "sanity.ai.prompt.userInput";
3555
+ var isObject_1 = isObject$2;
3556
+ var baseGetTag = _baseGetTag,
3557
+ isObject$1 = isObject_1;
3558
+
3559
+ /** `Object#toString` result references. */
3560
+ var asyncTag = '[object AsyncFunction]',
3561
+ funcTag = '[object Function]',
3562
+ genTag = '[object GeneratorFunction]',
3563
+ proxyTag = '[object Proxy]';
3564
+
3565
+ /**
3566
+ * Checks if `value` is classified as a `Function` object.
3567
+ *
3568
+ * @static
3569
+ * @memberOf _
3570
+ * @since 0.1.0
3571
+ * @category Lang
3572
+ * @param {*} value The value to check.
3573
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
3574
+ * @example
3575
+ *
3576
+ * _.isFunction(_);
3577
+ * // => true
3578
+ *
3579
+ * _.isFunction(/abc/);
3580
+ * // => false
3581
+ */
3582
+ function isFunction$1(value) {
3583
+ if (!isObject$1(value)) {
3584
+ return false;
3585
+ }
3586
+ // The use of `Object#toString` avoids issues with the `typeof` operator
3587
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
3588
+ var tag = baseGetTag(value);
3589
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
3173
3590
  }
3174
- function isSpan(block) {
3175
- return block._type === "span";
3591
+ var isFunction_1 = isFunction$1;
3592
+ var root$1 = _root;
3593
+
3594
+ /** Used to detect overreaching core-js shims. */
3595
+ var coreJsData$1 = root$1['__core-js_shared__'];
3596
+ var _coreJsData = coreJsData$1;
3597
+ var coreJsData = _coreJsData;
3598
+
3599
+ /** Used to detect methods masquerading as native. */
3600
+ var maskSrcKey = function () {
3601
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
3602
+ return uid ? 'Symbol(src)_1.' + uid : '';
3603
+ }();
3604
+
3605
+ /**
3606
+ * Checks if `func` has its source masked.
3607
+ *
3608
+ * @private
3609
+ * @param {Function} func The function to check.
3610
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
3611
+ */
3612
+ function isMasked$1(func) {
3613
+ return !!maskSrcKey && maskSrcKey in func;
3614
+ }
3615
+ var _isMasked = isMasked$1;
3616
+
3617
+ /** Used for built-in method references. */
3618
+
3619
+ var funcProto$1 = Function.prototype;
3620
+
3621
+ /** Used to resolve the decompiled source of functions. */
3622
+ var funcToString$1 = funcProto$1.toString;
3623
+
3624
+ /**
3625
+ * Converts `func` to its source code.
3626
+ *
3627
+ * @private
3628
+ * @param {Function} func The function to convert.
3629
+ * @returns {string} Returns the source code.
3630
+ */
3631
+ function toSource$1(func) {
3632
+ if (func != null) {
3633
+ try {
3634
+ return funcToString$1.call(func);
3635
+ } catch (e) {}
3636
+ try {
3637
+ return func + '';
3638
+ } catch (e) {}
3639
+ }
3640
+ return '';
3176
3641
  }
3177
- function mapBlock(block, migratedContexts) {
3178
- var _a, _b, _c, _d;
3179
- if (isFieldRef(block)) {
3180
- return {
3181
- ...block,
3182
- _type: fieldReferenceTypeName
3183
- };
3642
+ var _toSource = toSource$1;
3643
+ var isFunction = isFunction_1,
3644
+ isMasked = _isMasked,
3645
+ isObject = isObject_1,
3646
+ toSource = _toSource;
3647
+
3648
+ /**
3649
+ * Used to match `RegExp`
3650
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
3651
+ */
3652
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
3653
+
3654
+ /** Used to detect host constructors (Safari). */
3655
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
3656
+
3657
+ /** Used for built-in method references. */
3658
+ var funcProto = Function.prototype,
3659
+ objectProto$2 = Object.prototype;
3660
+
3661
+ /** Used to resolve the decompiled source of functions. */
3662
+ var funcToString = funcProto.toString;
3663
+
3664
+ /** Used to check objects for own properties. */
3665
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
3666
+
3667
+ /** Used to detect if a method is native. */
3668
+ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
3669
+
3670
+ /**
3671
+ * The base implementation of `_.isNative` without bad shim checks.
3672
+ *
3673
+ * @private
3674
+ * @param {*} value The value to check.
3675
+ * @returns {boolean} Returns `true` if `value` is a native function,
3676
+ * else `false`.
3677
+ */
3678
+ function baseIsNative$1(value) {
3679
+ if (!isObject(value) || isMasked(value)) {
3680
+ return false;
3184
3681
  }
3185
- if (isUserInput(block)) {
3186
- return {
3187
- ...block,
3188
- _type: userInputTypeName
3189
- };
3682
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
3683
+ return pattern.test(toSource(value));
3684
+ }
3685
+ var _baseIsNative = baseIsNative$1;
3686
+
3687
+ /**
3688
+ * Gets the value at `key` of `object`.
3689
+ *
3690
+ * @private
3691
+ * @param {Object} [object] The object to query.
3692
+ * @param {string} key The key of the property to get.
3693
+ * @returns {*} Returns the property value.
3694
+ */
3695
+
3696
+ function getValue$1(object, key) {
3697
+ return object == null ? undefined : object[key];
3698
+ }
3699
+ var _getValue = getValue$1;
3700
+ var baseIsNative = _baseIsNative,
3701
+ getValue = _getValue;
3702
+
3703
+ /**
3704
+ * Gets the native function at `key` of `object`.
3705
+ *
3706
+ * @private
3707
+ * @param {Object} object The object to query.
3708
+ * @param {string} key The key of the method to get.
3709
+ * @returns {*} Returns the function if it's native, else `undefined`.
3710
+ */
3711
+ function getNative$2(object, key) {
3712
+ var value = getValue(object, key);
3713
+ return baseIsNative(value) ? value : undefined;
3714
+ }
3715
+ var _getNative = getNative$2;
3716
+ var getNative$1 = _getNative;
3717
+
3718
+ /* Built-in method references that are verified to be native. */
3719
+ var nativeCreate$4 = getNative$1(Object, 'create');
3720
+ var _nativeCreate = nativeCreate$4;
3721
+ var nativeCreate$3 = _nativeCreate;
3722
+
3723
+ /**
3724
+ * Removes all key-value entries from the hash.
3725
+ *
3726
+ * @private
3727
+ * @name clear
3728
+ * @memberOf Hash
3729
+ */
3730
+ function hashClear$1() {
3731
+ this.__data__ = nativeCreate$3 ? nativeCreate$3(null) : {};
3732
+ this.size = 0;
3733
+ }
3734
+ var _hashClear = hashClear$1;
3735
+
3736
+ /**
3737
+ * Removes `key` and its value from the hash.
3738
+ *
3739
+ * @private
3740
+ * @name delete
3741
+ * @memberOf Hash
3742
+ * @param {Object} hash The hash to modify.
3743
+ * @param {string} key The key of the value to remove.
3744
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
3745
+ */
3746
+
3747
+ function hashDelete$1(key) {
3748
+ var result = this.has(key) && delete this.__data__[key];
3749
+ this.size -= result ? 1 : 0;
3750
+ return result;
3751
+ }
3752
+ var _hashDelete = hashDelete$1;
3753
+ var nativeCreate$2 = _nativeCreate;
3754
+
3755
+ /** Used to stand-in for `undefined` hash values. */
3756
+ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
3757
+
3758
+ /** Used for built-in method references. */
3759
+ var objectProto$1 = Object.prototype;
3760
+
3761
+ /** Used to check objects for own properties. */
3762
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
3763
+
3764
+ /**
3765
+ * Gets the hash value for `key`.
3766
+ *
3767
+ * @private
3768
+ * @name get
3769
+ * @memberOf Hash
3770
+ * @param {string} key The key of the value to get.
3771
+ * @returns {*} Returns the entry value.
3772
+ */
3773
+ function hashGet$1(key) {
3774
+ var data = this.__data__;
3775
+ if (nativeCreate$2) {
3776
+ var result = data[key];
3777
+ return result === HASH_UNDEFINED$1 ? undefined : result;
3190
3778
  }
3191
- if (isContext(block)) {
3192
- const newBlock = {
3193
- ...block,
3194
- _type: instructionContextTypeName,
3195
- reference: {
3196
- _type: "reference",
3197
- _ref: (_c = (_a = migratedContexts.find(c => {
3198
- var _a2;
3199
- return c._alphaId === ((_a2 = block.reference) == null ? void 0 : _a2._ref);
3200
- })) == null ? void 0 : _a._id) != null ? _c : (_b = block.reference) == null ? void 0 : _b._ref
3201
- }
3202
- };
3203
- return newBlock;
3779
+ return hasOwnProperty$1.call(data, key) ? data[key] : undefined;
3780
+ }
3781
+ var _hashGet = hashGet$1;
3782
+ var nativeCreate$1 = _nativeCreate;
3783
+
3784
+ /** Used for built-in method references. */
3785
+ var objectProto = Object.prototype;
3786
+
3787
+ /** Used to check objects for own properties. */
3788
+ var hasOwnProperty = objectProto.hasOwnProperty;
3789
+
3790
+ /**
3791
+ * Checks if a hash value for `key` exists.
3792
+ *
3793
+ * @private
3794
+ * @name has
3795
+ * @memberOf Hash
3796
+ * @param {string} key The key of the entry to check.
3797
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3798
+ */
3799
+ function hashHas$1(key) {
3800
+ var data = this.__data__;
3801
+ return nativeCreate$1 ? data[key] !== undefined : hasOwnProperty.call(data, key);
3802
+ }
3803
+ var _hashHas = hashHas$1;
3804
+ var nativeCreate = _nativeCreate;
3805
+
3806
+ /** Used to stand-in for `undefined` hash values. */
3807
+ var HASH_UNDEFINED = '__lodash_hash_undefined__';
3808
+
3809
+ /**
3810
+ * Sets the hash `key` to `value`.
3811
+ *
3812
+ * @private
3813
+ * @name set
3814
+ * @memberOf Hash
3815
+ * @param {string} key The key of the value to set.
3816
+ * @param {*} value The value to set.
3817
+ * @returns {Object} Returns the hash instance.
3818
+ */
3819
+ function hashSet$1(key, value) {
3820
+ var data = this.__data__;
3821
+ this.size += this.has(key) ? 0 : 1;
3822
+ data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
3823
+ return this;
3824
+ }
3825
+ var _hashSet = hashSet$1;
3826
+ var hashClear = _hashClear,
3827
+ hashDelete = _hashDelete,
3828
+ hashGet = _hashGet,
3829
+ hashHas = _hashHas,
3830
+ hashSet = _hashSet;
3831
+
3832
+ /**
3833
+ * Creates a hash object.
3834
+ *
3835
+ * @private
3836
+ * @constructor
3837
+ * @param {Array} [entries] The key-value pairs to cache.
3838
+ */
3839
+ function Hash$1(entries) {
3840
+ var index = -1,
3841
+ length = entries == null ? 0 : entries.length;
3842
+ this.clear();
3843
+ while (++index < length) {
3844
+ var entry = entries[index];
3845
+ this.set(entry[0], entry[1]);
3204
3846
  }
3205
- if (isSpan(block)) {
3206
- return block;
3847
+ }
3848
+
3849
+ // Add methods to `Hash`.
3850
+ Hash$1.prototype.clear = hashClear;
3851
+ Hash$1.prototype['delete'] = hashDelete;
3852
+ Hash$1.prototype.get = hashGet;
3853
+ Hash$1.prototype.has = hashHas;
3854
+ Hash$1.prototype.set = hashSet;
3855
+ var _Hash = Hash$1;
3856
+
3857
+ /**
3858
+ * Removes all key-value entries from the list cache.
3859
+ *
3860
+ * @private
3861
+ * @name clear
3862
+ * @memberOf ListCache
3863
+ */
3864
+
3865
+ function listCacheClear$1() {
3866
+ this.__data__ = [];
3867
+ this.size = 0;
3868
+ }
3869
+ var _listCacheClear = listCacheClear$1;
3870
+
3871
+ /**
3872
+ * Performs a
3873
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
3874
+ * comparison between two values to determine if they are equivalent.
3875
+ *
3876
+ * @static
3877
+ * @memberOf _
3878
+ * @since 4.0.0
3879
+ * @category Lang
3880
+ * @param {*} value The value to compare.
3881
+ * @param {*} other The other value to compare.
3882
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
3883
+ * @example
3884
+ *
3885
+ * var object = { 'a': 1 };
3886
+ * var other = { 'a': 1 };
3887
+ *
3888
+ * _.eq(object, object);
3889
+ * // => true
3890
+ *
3891
+ * _.eq(object, other);
3892
+ * // => false
3893
+ *
3894
+ * _.eq('a', 'a');
3895
+ * // => true
3896
+ *
3897
+ * _.eq('a', Object('a'));
3898
+ * // => false
3899
+ *
3900
+ * _.eq(NaN, NaN);
3901
+ * // => true
3902
+ */
3903
+
3904
+ function eq$1(value, other) {
3905
+ return value === other || value !== value && other !== other;
3906
+ }
3907
+ var eq_1 = eq$1;
3908
+ var eq = eq_1;
3909
+
3910
+ /**
3911
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
3912
+ *
3913
+ * @private
3914
+ * @param {Array} array The array to inspect.
3915
+ * @param {*} key The key to search for.
3916
+ * @returns {number} Returns the index of the matched value, else `-1`.
3917
+ */
3918
+ function assocIndexOf$4(array, key) {
3919
+ var length = array.length;
3920
+ while (length--) {
3921
+ if (eq(array[length][0], key)) {
3922
+ return length;
3923
+ }
3207
3924
  }
3208
- const textBlock = block;
3209
- return {
3210
- ...textBlock,
3211
- children: ((_d = textBlock.children) != null ? _d : []).map(child => mapBlock(child, migratedContexts))
3925
+ return -1;
3926
+ }
3927
+ var _assocIndexOf = assocIndexOf$4;
3928
+ var assocIndexOf$3 = _assocIndexOf;
3929
+
3930
+ /** Used for built-in method references. */
3931
+ var arrayProto = Array.prototype;
3932
+
3933
+ /** Built-in value references. */
3934
+ var splice = arrayProto.splice;
3935
+
3936
+ /**
3937
+ * Removes `key` and its value from the list cache.
3938
+ *
3939
+ * @private
3940
+ * @name delete
3941
+ * @memberOf ListCache
3942
+ * @param {string} key The key of the value to remove.
3943
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
3944
+ */
3945
+ function listCacheDelete$1(key) {
3946
+ var data = this.__data__,
3947
+ index = assocIndexOf$3(data, key);
3948
+ if (index < 0) {
3949
+ return false;
3950
+ }
3951
+ var lastIndex = data.length - 1;
3952
+ if (index == lastIndex) {
3953
+ data.pop();
3954
+ } else {
3955
+ splice.call(data, index, 1);
3956
+ }
3957
+ --this.size;
3958
+ return true;
3959
+ }
3960
+ var _listCacheDelete = listCacheDelete$1;
3961
+ var assocIndexOf$2 = _assocIndexOf;
3962
+
3963
+ /**
3964
+ * Gets the list cache value for `key`.
3965
+ *
3966
+ * @private
3967
+ * @name get
3968
+ * @memberOf ListCache
3969
+ * @param {string} key The key of the value to get.
3970
+ * @returns {*} Returns the entry value.
3971
+ */
3972
+ function listCacheGet$1(key) {
3973
+ var data = this.__data__,
3974
+ index = assocIndexOf$2(data, key);
3975
+ return index < 0 ? undefined : data[index][1];
3976
+ }
3977
+ var _listCacheGet = listCacheGet$1;
3978
+ var assocIndexOf$1 = _assocIndexOf;
3979
+
3980
+ /**
3981
+ * Checks if a list cache value for `key` exists.
3982
+ *
3983
+ * @private
3984
+ * @name has
3985
+ * @memberOf ListCache
3986
+ * @param {string} key The key of the entry to check.
3987
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3988
+ */
3989
+ function listCacheHas$1(key) {
3990
+ return assocIndexOf$1(this.__data__, key) > -1;
3991
+ }
3992
+ var _listCacheHas = listCacheHas$1;
3993
+ var assocIndexOf = _assocIndexOf;
3994
+
3995
+ /**
3996
+ * Sets the list cache `key` to `value`.
3997
+ *
3998
+ * @private
3999
+ * @name set
4000
+ * @memberOf ListCache
4001
+ * @param {string} key The key of the value to set.
4002
+ * @param {*} value The value to set.
4003
+ * @returns {Object} Returns the list cache instance.
4004
+ */
4005
+ function listCacheSet$1(key, value) {
4006
+ var data = this.__data__,
4007
+ index = assocIndexOf(data, key);
4008
+ if (index < 0) {
4009
+ ++this.size;
4010
+ data.push([key, value]);
4011
+ } else {
4012
+ data[index][1] = value;
4013
+ }
4014
+ return this;
4015
+ }
4016
+ var _listCacheSet = listCacheSet$1;
4017
+ var listCacheClear = _listCacheClear,
4018
+ listCacheDelete = _listCacheDelete,
4019
+ listCacheGet = _listCacheGet,
4020
+ listCacheHas = _listCacheHas,
4021
+ listCacheSet = _listCacheSet;
4022
+
4023
+ /**
4024
+ * Creates an list cache object.
4025
+ *
4026
+ * @private
4027
+ * @constructor
4028
+ * @param {Array} [entries] The key-value pairs to cache.
4029
+ */
4030
+ function ListCache$1(entries) {
4031
+ var index = -1,
4032
+ length = entries == null ? 0 : entries.length;
4033
+ this.clear();
4034
+ while (++index < length) {
4035
+ var entry = entries[index];
4036
+ this.set(entry[0], entry[1]);
4037
+ }
4038
+ }
4039
+
4040
+ // Add methods to `ListCache`.
4041
+ ListCache$1.prototype.clear = listCacheClear;
4042
+ ListCache$1.prototype['delete'] = listCacheDelete;
4043
+ ListCache$1.prototype.get = listCacheGet;
4044
+ ListCache$1.prototype.has = listCacheHas;
4045
+ ListCache$1.prototype.set = listCacheSet;
4046
+ var _ListCache = ListCache$1;
4047
+ var getNative = _getNative,
4048
+ root = _root;
4049
+
4050
+ /* Built-in method references that are verified to be native. */
4051
+ var Map$2 = getNative(root, 'Map');
4052
+ var _Map = Map$2;
4053
+ var Hash = _Hash,
4054
+ ListCache = _ListCache,
4055
+ Map$1 = _Map;
4056
+
4057
+ /**
4058
+ * Removes all key-value entries from the map.
4059
+ *
4060
+ * @private
4061
+ * @name clear
4062
+ * @memberOf MapCache
4063
+ */
4064
+ function mapCacheClear$1() {
4065
+ this.size = 0;
4066
+ this.__data__ = {
4067
+ 'hash': new Hash(),
4068
+ 'map': new (Map$1 || ListCache)(),
4069
+ 'string': new Hash()
3212
4070
  };
3213
4071
  }
3214
- function AssistLayout(props) {
3215
- var _a;
3216
- const [connectors, setConnectors] = react.useState([]);
3217
- const migrate = (_a = props.config.alphaMigration) != null ? _a : true;
3218
- return /* @__PURE__ */jsxRuntime.jsxs(AiAssistanceConfigProvider, {
3219
- config: props.config,
3220
- children: [migrate ? /* @__PURE__ */jsxRuntime.jsx(AlphaMigration, {}) : null, /* @__PURE__ */jsxRuntime.jsx(RunInstructionProvider, {
3221
- children: /* @__PURE__ */jsxRuntime.jsxs(ConnectorsProvider, {
3222
- onConnectorsChange: setConnectors,
3223
- children: [props.renderDefault(props), /* @__PURE__ */jsxRuntime.jsx(ui.ThemeProvider, {
3224
- tone: "default",
3225
- children: /* @__PURE__ */jsxRuntime.jsx(AssistConnectorsOverlay, {
3226
- connectors
4072
+ var _mapCacheClear = mapCacheClear$1;
4073
+
4074
+ /**
4075
+ * Checks if `value` is suitable for use as unique object key.
4076
+ *
4077
+ * @private
4078
+ * @param {*} value The value to check.
4079
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
4080
+ */
4081
+
4082
+ function isKeyable$1(value) {
4083
+ var type = typeof value;
4084
+ return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
4085
+ }
4086
+ var _isKeyable = isKeyable$1;
4087
+ var isKeyable = _isKeyable;
4088
+
4089
+ /**
4090
+ * Gets the data for `map`.
4091
+ *
4092
+ * @private
4093
+ * @param {Object} map The map to query.
4094
+ * @param {string} key The reference key.
4095
+ * @returns {*} Returns the map data.
4096
+ */
4097
+ function getMapData$4(map, key) {
4098
+ var data = map.__data__;
4099
+ return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
4100
+ }
4101
+ var _getMapData = getMapData$4;
4102
+ var getMapData$3 = _getMapData;
4103
+
4104
+ /**
4105
+ * Removes `key` and its value from the map.
4106
+ *
4107
+ * @private
4108
+ * @name delete
4109
+ * @memberOf MapCache
4110
+ * @param {string} key The key of the value to remove.
4111
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4112
+ */
4113
+ function mapCacheDelete$1(key) {
4114
+ var result = getMapData$3(this, key)['delete'](key);
4115
+ this.size -= result ? 1 : 0;
4116
+ return result;
4117
+ }
4118
+ var _mapCacheDelete = mapCacheDelete$1;
4119
+ var getMapData$2 = _getMapData;
4120
+
4121
+ /**
4122
+ * Gets the map value for `key`.
4123
+ *
4124
+ * @private
4125
+ * @name get
4126
+ * @memberOf MapCache
4127
+ * @param {string} key The key of the value to get.
4128
+ * @returns {*} Returns the entry value.
4129
+ */
4130
+ function mapCacheGet$1(key) {
4131
+ return getMapData$2(this, key).get(key);
4132
+ }
4133
+ var _mapCacheGet = mapCacheGet$1;
4134
+ var getMapData$1 = _getMapData;
4135
+
4136
+ /**
4137
+ * Checks if a map value for `key` exists.
4138
+ *
4139
+ * @private
4140
+ * @name has
4141
+ * @memberOf MapCache
4142
+ * @param {string} key The key of the entry to check.
4143
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4144
+ */
4145
+ function mapCacheHas$1(key) {
4146
+ return getMapData$1(this, key).has(key);
4147
+ }
4148
+ var _mapCacheHas = mapCacheHas$1;
4149
+ var getMapData = _getMapData;
4150
+
4151
+ /**
4152
+ * Sets the map `key` to `value`.
4153
+ *
4154
+ * @private
4155
+ * @name set
4156
+ * @memberOf MapCache
4157
+ * @param {string} key The key of the value to set.
4158
+ * @param {*} value The value to set.
4159
+ * @returns {Object} Returns the map cache instance.
4160
+ */
4161
+ function mapCacheSet$1(key, value) {
4162
+ var data = getMapData(this, key),
4163
+ size = data.size;
4164
+ data.set(key, value);
4165
+ this.size += data.size == size ? 0 : 1;
4166
+ return this;
4167
+ }
4168
+ var _mapCacheSet = mapCacheSet$1;
4169
+ var mapCacheClear = _mapCacheClear,
4170
+ mapCacheDelete = _mapCacheDelete,
4171
+ mapCacheGet = _mapCacheGet,
4172
+ mapCacheHas = _mapCacheHas,
4173
+ mapCacheSet = _mapCacheSet;
4174
+
4175
+ /**
4176
+ * Creates a map cache object to store key-value pairs.
4177
+ *
4178
+ * @private
4179
+ * @constructor
4180
+ * @param {Array} [entries] The key-value pairs to cache.
4181
+ */
4182
+ function MapCache$1(entries) {
4183
+ var index = -1,
4184
+ length = entries == null ? 0 : entries.length;
4185
+ this.clear();
4186
+ while (++index < length) {
4187
+ var entry = entries[index];
4188
+ this.set(entry[0], entry[1]);
4189
+ }
4190
+ }
4191
+
4192
+ // Add methods to `MapCache`.
4193
+ MapCache$1.prototype.clear = mapCacheClear;
4194
+ MapCache$1.prototype['delete'] = mapCacheDelete;
4195
+ MapCache$1.prototype.get = mapCacheGet;
4196
+ MapCache$1.prototype.has = mapCacheHas;
4197
+ MapCache$1.prototype.set = mapCacheSet;
4198
+ var _MapCache = MapCache$1;
4199
+ var MapCache = _MapCache;
4200
+
4201
+ /** Error message constants. */
4202
+ var FUNC_ERROR_TEXT = 'Expected a function';
4203
+
4204
+ /**
4205
+ * Creates a function that memoizes the result of `func`. If `resolver` is
4206
+ * provided, it determines the cache key for storing the result based on the
4207
+ * arguments provided to the memoized function. By default, the first argument
4208
+ * provided to the memoized function is used as the map cache key. The `func`
4209
+ * is invoked with the `this` binding of the memoized function.
4210
+ *
4211
+ * **Note:** The cache is exposed as the `cache` property on the memoized
4212
+ * function. Its creation may be customized by replacing the `_.memoize.Cache`
4213
+ * constructor with one whose instances implement the
4214
+ * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
4215
+ * method interface of `clear`, `delete`, `get`, `has`, and `set`.
4216
+ *
4217
+ * @static
4218
+ * @memberOf _
4219
+ * @since 0.1.0
4220
+ * @category Function
4221
+ * @param {Function} func The function to have its output memoized.
4222
+ * @param {Function} [resolver] The function to resolve the cache key.
4223
+ * @returns {Function} Returns the new memoized function.
4224
+ * @example
4225
+ *
4226
+ * var object = { 'a': 1, 'b': 2 };
4227
+ * var other = { 'c': 3, 'd': 4 };
4228
+ *
4229
+ * var values = _.memoize(_.values);
4230
+ * values(object);
4231
+ * // => [1, 2]
4232
+ *
4233
+ * values(other);
4234
+ * // => [3, 4]
4235
+ *
4236
+ * object.a = 2;
4237
+ * values(object);
4238
+ * // => [1, 2]
4239
+ *
4240
+ * // Modify the result cache.
4241
+ * values.cache.set(object, ['a', 'b']);
4242
+ * values(object);
4243
+ * // => ['a', 'b']
4244
+ *
4245
+ * // Replace `_.memoize.Cache`.
4246
+ * _.memoize.Cache = WeakMap;
4247
+ */
4248
+ function memoize$1(func, resolver) {
4249
+ if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
4250
+ throw new TypeError(FUNC_ERROR_TEXT);
4251
+ }
4252
+ var memoized = function () {
4253
+ var args = arguments,
4254
+ key = resolver ? resolver.apply(this, args) : args[0],
4255
+ cache = memoized.cache;
4256
+ if (cache.has(key)) {
4257
+ return cache.get(key);
4258
+ }
4259
+ var result = func.apply(this, args);
4260
+ memoized.cache = cache.set(key, result) || cache;
4261
+ return result;
4262
+ };
4263
+ memoized.cache = new (memoize$1.Cache || MapCache)();
4264
+ return memoized;
4265
+ }
4266
+
4267
+ // Expose `MapCache`.
4268
+ memoize$1.Cache = MapCache;
4269
+ var memoize_1 = memoize$1;
4270
+ var memoize = memoize_1;
4271
+
4272
+ /** Used as the maximum memoize cache size. */
4273
+ var MAX_MEMOIZE_SIZE = 500;
4274
+
4275
+ /**
4276
+ * A specialized version of `_.memoize` which clears the memoized function's
4277
+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.
4278
+ *
4279
+ * @private
4280
+ * @param {Function} func The function to have its output memoized.
4281
+ * @returns {Function} Returns the new memoized function.
4282
+ */
4283
+ function memoizeCapped$1(func) {
4284
+ var result = memoize(func, function (key) {
4285
+ if (cache.size === MAX_MEMOIZE_SIZE) {
4286
+ cache.clear();
4287
+ }
4288
+ return key;
4289
+ });
4290
+ var cache = result.cache;
4291
+ return result;
4292
+ }
4293
+ var _memoizeCapped = memoizeCapped$1;
4294
+ var memoizeCapped = _memoizeCapped;
4295
+
4296
+ /** Used to match property names within property paths. */
4297
+ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
4298
+
4299
+ /** Used to match backslashes in property paths. */
4300
+ var reEscapeChar = /\\(\\)?/g;
4301
+
4302
+ /**
4303
+ * Converts `string` to a property path array.
4304
+ *
4305
+ * @private
4306
+ * @param {string} string The string to convert.
4307
+ * @returns {Array} Returns the property path array.
4308
+ */
4309
+ var stringToPath$1 = memoizeCapped(function (string) {
4310
+ var result = [];
4311
+ if (string.charCodeAt(0) === 46 /* . */) {
4312
+ result.push('');
4313
+ }
4314
+ string.replace(rePropName, function (match, number, quote, subString) {
4315
+ result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
4316
+ });
4317
+ return result;
4318
+ });
4319
+ var _stringToPath = stringToPath$1;
4320
+
4321
+ /**
4322
+ * A specialized version of `_.map` for arrays without support for iteratee
4323
+ * shorthands.
4324
+ *
4325
+ * @private
4326
+ * @param {Array} [array] The array to iterate over.
4327
+ * @param {Function} iteratee The function invoked per iteration.
4328
+ * @returns {Array} Returns the new mapped array.
4329
+ */
4330
+
4331
+ function arrayMap$1(array, iteratee) {
4332
+ var index = -1,
4333
+ length = array == null ? 0 : array.length,
4334
+ result = Array(length);
4335
+ while (++index < length) {
4336
+ result[index] = iteratee(array[index], index, array);
4337
+ }
4338
+ return result;
4339
+ }
4340
+ var _arrayMap = arrayMap$1;
4341
+ var Symbol = _Symbol,
4342
+ arrayMap = _arrayMap,
4343
+ isArray$1 = isArray_1,
4344
+ isSymbol$1 = isSymbol_1;
4345
+
4346
+ /** Used as references for various `Number` constants. */
4347
+ var INFINITY$1 = 1 / 0;
4348
+
4349
+ /** Used to convert symbols to primitives and strings. */
4350
+ var symbolProto = Symbol ? Symbol.prototype : undefined,
4351
+ symbolToString = symbolProto ? symbolProto.toString : undefined;
4352
+
4353
+ /**
4354
+ * The base implementation of `_.toString` which doesn't convert nullish
4355
+ * values to empty strings.
4356
+ *
4357
+ * @private
4358
+ * @param {*} value The value to process.
4359
+ * @returns {string} Returns the string.
4360
+ */
4361
+ function baseToString$1(value) {
4362
+ // Exit early for strings to avoid a performance hit in some environments.
4363
+ if (typeof value == 'string') {
4364
+ return value;
4365
+ }
4366
+ if (isArray$1(value)) {
4367
+ // Recursively convert values (susceptible to call stack limits).
4368
+ return arrayMap(value, baseToString$1) + '';
4369
+ }
4370
+ if (isSymbol$1(value)) {
4371
+ return symbolToString ? symbolToString.call(value) : '';
4372
+ }
4373
+ var result = value + '';
4374
+ return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
4375
+ }
4376
+ var _baseToString = baseToString$1;
4377
+ var baseToString = _baseToString;
4378
+
4379
+ /**
4380
+ * Converts `value` to a string. An empty string is returned for `null`
4381
+ * and `undefined` values. The sign of `-0` is preserved.
4382
+ *
4383
+ * @static
4384
+ * @memberOf _
4385
+ * @since 4.0.0
4386
+ * @category Lang
4387
+ * @param {*} value The value to convert.
4388
+ * @returns {string} Returns the converted string.
4389
+ * @example
4390
+ *
4391
+ * _.toString(null);
4392
+ * // => ''
4393
+ *
4394
+ * _.toString(-0);
4395
+ * // => '-0'
4396
+ *
4397
+ * _.toString([1, 2, 3]);
4398
+ * // => '1,2,3'
4399
+ */
4400
+ function toString$1(value) {
4401
+ return value == null ? '' : baseToString(value);
4402
+ }
4403
+ var toString_1 = toString$1;
4404
+ var isArray = isArray_1,
4405
+ isKey = _isKey,
4406
+ stringToPath = _stringToPath,
4407
+ toString = toString_1;
4408
+
4409
+ /**
4410
+ * Casts `value` to a path array if it's not one.
4411
+ *
4412
+ * @private
4413
+ * @param {*} value The value to inspect.
4414
+ * @param {Object} [object] The object to query keys on.
4415
+ * @returns {Array} Returns the cast property path array.
4416
+ */
4417
+ function castPath$1(value, object) {
4418
+ if (isArray(value)) {
4419
+ return value;
4420
+ }
4421
+ return isKey(value, object) ? [value] : stringToPath(toString(value));
4422
+ }
4423
+ var _castPath = castPath$1;
4424
+ var isSymbol = isSymbol_1;
4425
+
4426
+ /** Used as references for various `Number` constants. */
4427
+ var INFINITY = 1 / 0;
4428
+
4429
+ /**
4430
+ * Converts `value` to a string key if it's not a string or symbol.
4431
+ *
4432
+ * @private
4433
+ * @param {*} value The value to inspect.
4434
+ * @returns {string|symbol} Returns the key.
4435
+ */
4436
+ function toKey$1(value) {
4437
+ if (typeof value == 'string' || isSymbol(value)) {
4438
+ return value;
4439
+ }
4440
+ var result = value + '';
4441
+ return result == '0' && 1 / value == -INFINITY ? '-0' : result;
4442
+ }
4443
+ var _toKey = toKey$1;
4444
+ var castPath = _castPath,
4445
+ toKey = _toKey;
4446
+
4447
+ /**
4448
+ * The base implementation of `_.get` without support for default values.
4449
+ *
4450
+ * @private
4451
+ * @param {Object} object The object to query.
4452
+ * @param {Array|string} path The path of the property to get.
4453
+ * @returns {*} Returns the resolved value.
4454
+ */
4455
+ function baseGet$1(object, path) {
4456
+ path = castPath(path, object);
4457
+ var index = 0,
4458
+ length = path.length;
4459
+ while (object != null && index < length) {
4460
+ object = object[toKey(path[index++])];
4461
+ }
4462
+ return index && index == length ? object : undefined;
4463
+ }
4464
+ var _baseGet = baseGet$1;
4465
+ var baseGet = _baseGet;
4466
+
4467
+ /**
4468
+ * Gets the value at `path` of `object`. If the resolved value is
4469
+ * `undefined`, the `defaultValue` is returned in its place.
4470
+ *
4471
+ * @static
4472
+ * @memberOf _
4473
+ * @since 3.7.0
4474
+ * @category Object
4475
+ * @param {Object} object The object to query.
4476
+ * @param {Array|string} path The path of the property to get.
4477
+ * @param {*} [defaultValue] The value returned for `undefined` resolved values.
4478
+ * @returns {*} Returns the resolved value.
4479
+ * @example
4480
+ *
4481
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
4482
+ *
4483
+ * _.get(object, 'a[0].b.c');
4484
+ * // => 3
4485
+ *
4486
+ * _.get(object, ['a', '0', 'b', 'c']);
4487
+ * // => 3
4488
+ *
4489
+ * _.get(object, 'a.b.c', 'default');
4490
+ * // => 'default'
4491
+ */
4492
+ function get(object, path, defaultValue) {
4493
+ var result = object == null ? undefined : baseGet(object, path);
4494
+ return result === undefined ? defaultValue : result;
4495
+ }
4496
+ var get_1 = get;
4497
+ var get$1 = /*@__PURE__*/getDefaultExportFromCjs(get_1);
4498
+ const getLanguageParams = (select, document) => {
4499
+ if (!select || !document) {
4500
+ return {};
4501
+ }
4502
+ const selection = select || {};
4503
+ const selectedValue = {};
4504
+ for (const [key, path] of Object.entries(selection)) {
4505
+ let value = get$1(document, path);
4506
+ if (Array.isArray(value)) {
4507
+ value = value.filter(item => typeof item === "object" ? (item == null ? void 0 : item._type) !== "reference" || "_ref" in item : true);
4508
+ }
4509
+ selectedValue[key] = value;
4510
+ }
4511
+ return selectedValue;
4512
+ };
4513
+ const toFieldLanguagesKeyPrefix = "sanityStudio:assist:field-languages:from:";
4514
+ function getPreferredToFieldLanguages(fromLanguageId) {
4515
+ if (typeof localStorage === "undefined") {
4516
+ return [];
4517
+ }
4518
+ const value = localStorage.getItem("".concat(toFieldLanguagesKeyPrefix).concat(fromLanguageId));
4519
+ return value ? JSON.parse(value) : [];
4520
+ }
4521
+ function setPreferredToFieldLanguages(fromLanguageId, languageIds) {
4522
+ if (typeof localStorage === "undefined") {
4523
+ return;
4524
+ }
4525
+ localStorage.setItem("".concat(toFieldLanguagesKeyPrefix).concat(fromLanguageId), JSON.stringify(languageIds));
4526
+ }
4527
+ const FieldTranslationContext = react.createContext({
4528
+ openFieldTranslation: () => {},
4529
+ translationLoading: false
4530
+ });
4531
+ function useFieldTranslation() {
4532
+ return react.useContext(FieldTranslationContext);
4533
+ }
4534
+ function hasValuesToTranslate(fieldLanguageMaps, fromLanguage, basePath) {
4535
+ return fieldLanguageMaps == null ? void 0 : fieldLanguageMaps.some(map => map.inputLanguageId === (fromLanguage == null ? void 0 : fromLanguage.id) && map.inputPath && sanity.pathToString(map.inputPath).startsWith(sanity.pathToString(basePath)));
4536
+ }
4537
+ function FieldTranslationProvider(props) {
4538
+ var _a, _b, _c;
4539
+ const {
4540
+ config: assistConfig
4541
+ } = useAiAssistanceConfig();
4542
+ const apiClient = useApiClient(assistConfig.__customApiClient);
4543
+ const config = (_a = assistConfig.translate) == null ? void 0 : _a.field;
4544
+ const {
4545
+ translate: runTranslate
4546
+ } = useTranslate(apiClient);
4547
+ const [dialogOpen, setDialogOpen] = react.useState(false);
4548
+ const [fieldTranslationParams, setFieldTranslationParams] = react.useState();
4549
+ const [languages, setLanguages] = react.useState();
4550
+ const [fromLanguage, setFromLanguage] = react.useState(void 0);
4551
+ const [toLanguages, setToLanguages] = react.useState(void 0);
4552
+ const [fieldLanguageMaps, setFieldLanguageMaps] = react.useState();
4553
+ const close = react.useCallback(() => {
4554
+ setDialogOpen(false);
4555
+ setLanguages(void 0);
4556
+ setFieldTranslationParams(void 0);
4557
+ }, []);
4558
+ const languageClient = sanity.useClient({
4559
+ apiVersion: (_b = config == null ? void 0 : config.apiVersion) != null ? _b : "2022-11-27"
4560
+ });
4561
+ const documentId = (_c = fieldTranslationParams == null ? void 0 : fieldTranslationParams.document) == null ? void 0 : _c._id;
4562
+ const id = react.useId();
4563
+ const selectFromLanguage = react.useCallback((from, languages2, params) => {
4564
+ var _a2, _b2;
4565
+ const {
4566
+ document,
4567
+ documentSchema
4568
+ } = params != null ? params : {};
4569
+ setFromLanguage(from);
4570
+ if (!document || !documentSchema || !params || !languages2) {
4571
+ setFieldLanguageMaps(void 0);
4572
+ return;
4573
+ }
4574
+ const preferred = getPreferredToFieldLanguages(from.id);
4575
+ const allToLanguages = languages2.filter(l => l.id !== (from == null ? void 0 : from.id));
4576
+ const filteredToLanguages = allToLanguages.filter(l => !preferred.length || preferred.includes(l.id));
4577
+ setToLanguages(filteredToLanguages);
4578
+ const fromId = from == null ? void 0 : from.id;
4579
+ const allToIds = (_a2 = allToLanguages == null ? void 0 : allToLanguages.map(l => l.id)) != null ? _a2 : [];
4580
+ const docMembers = getDocumentMembersFlat(document, documentSchema);
4581
+ if (fromId && (allToIds == null ? void 0 : allToIds.length)) {
4582
+ const transMap = getFieldLanguageMap(documentSchema, docMembers, fromId, allToIds.filter(toId => fromId !== toId), (_b2 = config == null ? void 0 : config.translationOutputs) != null ? _b2 : defaultLanguageOutputs);
4583
+ setFieldLanguageMaps(transMap);
4584
+ } else {
4585
+ setFieldLanguageMaps(void 0);
4586
+ }
4587
+ }, [config]);
4588
+ const toggleToLanguage = react.useCallback((toggledLang, toLanguages2, languages2) => {
4589
+ if (!languages2 || !fromLanguage) {
4590
+ return;
4591
+ }
4592
+ const wasSelected = !!(toLanguages2 == null ? void 0 : toLanguages2.find(l => l.id === toggledLang.id));
4593
+ const newToLangs = languages2.filter(anyLang => !!(toLanguages2 == null ? void 0 : toLanguages2.find(selectedLang => toggledLang.id !== selectedLang.id && selectedLang.id === anyLang.id)) || toggledLang.id === anyLang.id && !wasSelected);
4594
+ setToLanguages(newToLangs);
4595
+ setPreferredToFieldLanguages(fromLanguage.id, newToLangs.map(l => l.id));
4596
+ }, [fromLanguage]);
4597
+ const openFieldTranslation = react.useCallback(async params => {
4598
+ setDialogOpen(true);
4599
+ const languageParams = getLanguageParams(config == null ? void 0 : config.selectLanguageParams, params.document);
4600
+ const languages2 = await (typeof (config == null ? void 0 : config.languages) === "function" ? config == null ? void 0 : config.languages(languageClient, languageParams) : Promise.resolve(config == null ? void 0 : config.languages));
4601
+ setLanguages(languages2);
4602
+ setFieldTranslationParams(params);
4603
+ const fromLanguage2 = languages2 == null ? void 0 : languages2[0];
4604
+ if (fromLanguage2) {
4605
+ selectFromLanguage(fromLanguage2, languages2, params);
4606
+ } else {
4607
+ console.error("No languages available for selected language params", languageParams);
4608
+ }
4609
+ }, [selectFromLanguage, config, languageClient]);
4610
+ const contextValue = react.useMemo(() => {
4611
+ return {
4612
+ openFieldTranslation,
4613
+ translationLoading: false
4614
+ };
4615
+ }, [openFieldTranslation]);
4616
+ const runDisabled = !fromLanguage || !(toLanguages == null ? void 0 : toLanguages.length) || !(fieldLanguageMaps == null ? void 0 : fieldLanguageMaps.length) || !documentId || !hasValuesToTranslate(fieldLanguageMaps, fromLanguage, fieldTranslationParams.translatePath);
4617
+ const onRunTranslation = react.useCallback(() => {
4618
+ const translatePath = fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath;
4619
+ if (fieldLanguageMaps && documentId && translatePath) {
4620
+ runTranslate({
4621
+ documentId,
4622
+ translatePath,
4623
+ fieldLanguageMap: fieldLanguageMaps.map(map => ({
4624
+ ...map,
4625
+ // eslint-disable-next-line max-nested-callbacks
4626
+ outputs: map.outputs.filter(out => !!(toLanguages == null ? void 0 : toLanguages.find(l => l.id === out.id)))
4627
+ })),
4628
+ conditionalMembers: fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers
4629
+ });
4630
+ }
4631
+ close();
4632
+ }, [fieldLanguageMaps, documentId, runTranslate, close, toLanguages, fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath, fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers]);
4633
+ const runButton = /* @__PURE__ */jsxRuntime.jsx(ui.Button, {
4634
+ text: "Translate",
4635
+ tone: "primary",
4636
+ icon: icons.PlayIcon,
4637
+ style: {
4638
+ width: "100%"
4639
+ },
4640
+ disabled: runDisabled,
4641
+ onClick: onRunTranslation
4642
+ });
4643
+ return /* @__PURE__ */jsxRuntime.jsxs(FieldTranslationContext.Provider, {
4644
+ value: contextValue,
4645
+ children: [dialogOpen ? /* @__PURE__ */jsxRuntime.jsx(ui.Dialog, {
4646
+ id,
4647
+ width: 1,
4648
+ open: dialogOpen,
4649
+ onClose: close,
4650
+ header: "Translate fields",
4651
+ footer: /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
4652
+ justify: "space-between",
4653
+ padding: 2,
4654
+ flex: 1,
4655
+ children: runDisabled ? /* @__PURE__ */jsxRuntime.jsx(ui.Tooltip, {
4656
+ content: /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
4657
+ padding: 2,
4658
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4659
+ children: "There is nothing to translate in the selected from-language."
4660
+ })
4661
+ }),
4662
+ placement: "top",
4663
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
4664
+ flex: 1,
4665
+ children: runButton
3227
4666
  })
4667
+ }) : runButton
4668
+ }),
4669
+ children: languages ? /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
4670
+ padding: 4,
4671
+ gap: 5,
4672
+ align: "flex-start",
4673
+ justify: "center",
4674
+ children: [/* @__PURE__ */jsxRuntime.jsxs(ui.Stack, {
4675
+ space: 2,
4676
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Box, {
4677
+ marginBottom: 2,
4678
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4679
+ weight: "semibold",
4680
+ children: "From"
4681
+ })
4682
+ }), languages == null ? void 0 : languages.map(radioLanguage => /* @__PURE__ */jsxRuntime.jsx(FromLanguageRadio, {
4683
+ ...{
4684
+ radioLanguage,
4685
+ fromLanguage,
4686
+ selectFromLanguage,
4687
+ languages,
4688
+ fieldTranslationParams
4689
+ }
4690
+ }, radioLanguage.id))]
4691
+ }), /* @__PURE__ */jsxRuntime.jsxs(ui.Stack, {
4692
+ space: 2,
4693
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Box, {
4694
+ marginBottom: 2,
4695
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4696
+ weight: "semibold",
4697
+ children: "To"
4698
+ })
4699
+ }), languages.map(checkboxLanguage => /* @__PURE__ */jsxRuntime.jsx(ToLanguageCheckbox, {
4700
+ ...{
4701
+ checkboxLanguage,
4702
+ fromLanguage,
4703
+ toLanguages,
4704
+ toggleToLanguage,
4705
+ languages
4706
+ }
4707
+ }, checkboxLanguage.id))]
4708
+ })]
4709
+ }) : /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
4710
+ padding: 4,
4711
+ gap: 2,
4712
+ align: "flex-start",
4713
+ justify: "center",
4714
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Box, {
4715
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {})
4716
+ }), /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4717
+ children: "Loading languages..."
3228
4718
  })]
3229
4719
  })
4720
+ }) : null, props.children]
4721
+ });
4722
+ }
4723
+ function ToLanguageCheckbox(props) {
4724
+ var _a;
4725
+ const {
4726
+ checkboxLanguage,
4727
+ fromLanguage,
4728
+ toLanguages,
4729
+ toggleToLanguage,
4730
+ languages
4731
+ } = props;
4732
+ const langId = checkboxLanguage.id;
4733
+ const onChange = react.useCallback(() => toggleToLanguage(checkboxLanguage, toLanguages, languages), [toggleToLanguage, checkboxLanguage, toLanguages, languages]);
4734
+ return /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
4735
+ gap: 3,
4736
+ align: "center",
4737
+ as: "label",
4738
+ style: langId === (fromLanguage == null ? void 0 : fromLanguage.id) ? {
4739
+ opacity: 0.5
4740
+ } : void 0,
4741
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Checkbox, {
4742
+ name: "toLang",
4743
+ value: langId,
4744
+ checked: langId !== (fromLanguage == null ? void 0 : fromLanguage.id) && !!(toLanguages == null ? void 0 : toLanguages.find(tl => tl.id === langId)),
4745
+ onChange,
4746
+ disabled: langId === (fromLanguage == null ? void 0 : fromLanguage.id)
4747
+ }), /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4748
+ muted: langId === (fromLanguage == null ? void 0 : fromLanguage.id),
4749
+ children: (_a = checkboxLanguage.title) != null ? _a : langId
3230
4750
  })]
4751
+ }, langId);
4752
+ }
4753
+ function FromLanguageRadio(props) {
4754
+ var _a;
4755
+ const {
4756
+ languages,
4757
+ radioLanguage,
4758
+ selectFromLanguage,
4759
+ fromLanguage,
4760
+ fieldTranslationParams
4761
+ } = props;
4762
+ const langId = radioLanguage.id;
4763
+ const onChange = react.useCallback(() => selectFromLanguage(radioLanguage, languages, fieldTranslationParams), [selectFromLanguage, radioLanguage, languages, fieldTranslationParams]);
4764
+ return /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
4765
+ gap: 3,
4766
+ align: "center",
4767
+ as: "label",
4768
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Radio, {
4769
+ name: "fromLang",
4770
+ value: langId,
4771
+ checked: langId === (fromLanguage == null ? void 0 : fromLanguage.id),
4772
+ onChange
4773
+ }), /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
4774
+ children: (_a = radioLanguage.title) != null ? _a : radioLanguage.id
4775
+ })]
4776
+ }, langId);
4777
+ }
4778
+ function AssistLayout(props) {
4779
+ const [connectors, setConnectors] = react.useState([]);
4780
+ return /* @__PURE__ */jsxRuntime.jsx(AiAssistanceConfigProvider, {
4781
+ config: props.config,
4782
+ children: /* @__PURE__ */jsxRuntime.jsx(RunInstructionProvider, {
4783
+ children: /* @__PURE__ */jsxRuntime.jsx(FieldTranslationProvider, {
4784
+ children: /* @__PURE__ */jsxRuntime.jsxs(ConnectorsProvider, {
4785
+ onConnectorsChange: setConnectors,
4786
+ children: [props.renderDefault(props), /* @__PURE__ */jsxRuntime.jsx(ui.ThemeProvider, {
4787
+ tone: "default",
4788
+ children: /* @__PURE__ */jsxRuntime.jsx(AssistConnectorsOverlay, {
4789
+ connectors
4790
+ })
4791
+ })]
4792
+ })
4793
+ })
4794
+ })
3231
4795
  });
3232
4796
  }
3233
4797
  var __freeze$1 = Object.freeze;
@@ -3253,7 +4817,10 @@ function ErrorWrapper(props) {
3253
4817
  const catchError = react.useCallback(params => {
3254
4818
  setError(params.error);
3255
4819
  }, [setError]);
3256
- const unsetValue = react.useCallback(() => onChange(sanity.PatchEvent.from(sanity.unset())), [onChange]);
4820
+ const unsetValue = react.useCallback(() => {
4821
+ onChange(sanity.PatchEvent.from(sanity.unset()));
4822
+ setError(void 0);
4823
+ }, [onChange]);
3257
4824
  const dismiss = react.useCallback(() => setError(void 0), []);
3258
4825
  const catcher = /* @__PURE__ */jsxRuntime.jsx(ui.ErrorBoundary, {
3259
4826
  onCatch: catchError,
@@ -3321,6 +4888,7 @@ function AssistFormBlock(props) {
3321
4888
  _key: key
3322
4889
  }));
3323
4890
  }, [onChange, key]);
4891
+ const singlePresence = presence[0];
3324
4892
  return /* @__PURE__ */jsxRuntime.jsx(ErrorWrapper, {
3325
4893
  onChange: localOnChange,
3326
4894
  children: /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
@@ -3329,9 +4897,9 @@ function AssistFormBlock(props) {
3329
4897
  children: [/* @__PURE__ */jsxRuntime.jsx(ui.Box, {
3330
4898
  flex: 1,
3331
4899
  children: props.renderDefault(props)
3332
- }), presence.map(pre => /* @__PURE__ */jsxRuntime.jsx(AiFieldPresence, {
3333
- presence: pre
3334
- }, pre.lastActiveAt))]
4900
+ }), singlePresence && /* @__PURE__ */jsxRuntime.jsx(AiFieldPresence, {
4901
+ presence: singlePresence
4902
+ })]
3335
4903
  })
3336
4904
  });
3337
4905
  }
@@ -3375,16 +4943,24 @@ function InstructionInput(props) {
3375
4943
  ...props
3376
4944
  }), /* @__PURE__ */jsxRuntime.jsx(ShareField, {
3377
4945
  ...props
3378
- }), /* @__PURE__ */jsxRuntime.jsx(PromptField, {
4946
+ }), /* @__PURE__ */jsxRuntime.jsx(ObjectMember, {
4947
+ fieldName: "prompt",
4948
+ ...props
4949
+ }), /* @__PURE__ */jsxRuntime.jsx(ObjectMember, {
4950
+ fieldName: "output",
3379
4951
  ...props
3380
4952
  })]
3381
4953
  });
3382
4954
  }
3383
- function PromptField(props) {
3384
- const promptMember = findFieldMember(props.members, "prompt");
3385
- return promptMember ? /* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember, {
4955
+ function ObjectMember(_ref13) {
4956
+ let {
4957
+ fieldName,
4958
+ ...props
4959
+ } = _ref13;
4960
+ const member = findFieldMember(props.members, fieldName);
4961
+ return member ? /* @__PURE__ */jsxRuntime.jsx(sanity.ObjectInputMember, {
3386
4962
  ...props,
3387
- member: promptMember
4963
+ member
3388
4964
  }) : null;
3389
4965
  }
3390
4966
  const NONE = [];
@@ -3519,8 +5095,8 @@ function IconInput(props) {
3519
5095
  onChange
3520
5096
  } = props;
3521
5097
  const id = react.useId();
3522
- const items = react.useMemo(() => Object.entries(icons.icons).map(_ref10 => {
3523
- let [key, icon] = _ref10;
5098
+ const items = react.useMemo(() => Object.entries(icons.icons).map(_ref14 => {
5099
+ let [key, icon] = _ref14;
3524
5100
  return /* @__PURE__ */jsxRuntime.jsx(IconItem, {
3525
5101
  iconKey: key,
3526
5102
  icon,
@@ -3548,12 +5124,12 @@ function IconInput(props) {
3548
5124
  }
3549
5125
  });
3550
5126
  }
3551
- function IconItem(_ref11) {
5127
+ function IconItem(_ref15) {
3552
5128
  let {
3553
5129
  icon,
3554
5130
  iconKey: key,
3555
5131
  onChange
3556
- } = _ref11;
5132
+ } = _ref15;
3557
5133
  const onClick = react.useCallback(() => onChange(sanity.set(key)), [onChange, key]);
3558
5134
  return /* @__PURE__ */jsxRuntime.jsx(ui.MenuItem, {
3559
5135
  icon,
@@ -3564,8 +5140,8 @@ function IconItem(_ref11) {
3564
5140
  }
3565
5141
  function getIcon(iconName) {
3566
5142
  var _a, _b;
3567
- return (_b = (_a = Object.entries(icons.icons).find(_ref12 => {
3568
- let [key] = _ref12;
5143
+ return (_b = (_a = Object.entries(icons.icons).find(_ref16 => {
5144
+ let [key] = _ref16;
3569
5145
  return key === iconName;
3570
5146
  })) == null ? void 0 : _a[1]) != null ? _b : icons.icons.sparkles;
3571
5147
  }
@@ -3724,11 +5300,11 @@ const contextDocumentSchema = sanity.defineType({
3724
5300
  title: "title",
3725
5301
  context: "context"
3726
5302
  },
3727
- prepare(_ref13) {
5303
+ prepare(_ref17) {
3728
5304
  let {
3729
5305
  title,
3730
5306
  context
3731
- } = _ref13;
5307
+ } = _ref17;
3732
5308
  var _a;
3733
5309
  const text = context == null ? void 0 : context.flatMap(block => block == null ? void 0 : block.children).flatMap(child => {
3734
5310
  var _a2;
@@ -3814,10 +5390,204 @@ function InstructionsArrayField(props) {
3814
5390
  title: " "
3815
5391
  });
3816
5392
  }
5393
+ function InstructionOutputField(props) {
5394
+ var _a;
5395
+ const {
5396
+ fieldSchema
5397
+ } = (_a = react.useContext(SelectedFieldContext)) != null ? _a : {};
5398
+ if (!fieldSchema || !(sanity.isObjectSchemaType(fieldSchema) || sanity.isArrayOfObjectsSchemaType(fieldSchema))) {
5399
+ return null;
5400
+ }
5401
+ return /* @__PURE__ */jsxRuntime.jsx(EnabledOutputField, {
5402
+ ...props,
5403
+ fieldSchema,
5404
+ children: props.children
5405
+ });
5406
+ }
5407
+ function EnabledOutputField(_ref18) {
5408
+ let {
5409
+ fieldSchema,
5410
+ ...props
5411
+ } = _ref18;
5412
+ var _a;
5413
+ const [open, setOpen] = react.useState(!!((_a = props.value) == null ? void 0 : _a.length));
5414
+ const onExpand = react.useCallback(() => setOpen(true), []);
5415
+ const onCollapse = react.useCallback(() => setOpen(false), []);
5416
+ return props.renderDefault({
5417
+ ...props,
5418
+ collapsible: true,
5419
+ onExpand,
5420
+ onCollapse,
5421
+ collapsed: !open,
5422
+ level: 1,
5423
+ title: sanity.isObjectSchemaType(fieldSchema) ? "Allowed fields" : "Allowed types"
5424
+ });
5425
+ }
5426
+ function InstructionOutputInput(props) {
5427
+ var _a;
5428
+ const {
5429
+ fieldSchema
5430
+ } = (_a = react.useContext(SelectedFieldContext)) != null ? _a : {};
5431
+ if (!fieldSchema) {
5432
+ return null;
5433
+ }
5434
+ if (sanity.isObjectSchemaType(fieldSchema)) {
5435
+ return /* @__PURE__ */jsxRuntime.jsx(ObjectOutputInput, {
5436
+ ...props,
5437
+ fieldSchema
5438
+ });
5439
+ }
5440
+ if (sanity.isArrayOfObjectsSchemaType(fieldSchema)) {
5441
+ return /* @__PURE__ */jsxRuntime.jsx(ArrayOutputInput, {
5442
+ ...props,
5443
+ fieldSchema
5444
+ });
5445
+ }
5446
+ return null;
5447
+ }
5448
+ function useEmptySelectAllValue(value, allowedValues, onChange) {
5449
+ react.useEffect(() => {
5450
+ var _a, _b;
5451
+ const validValues = value == null ? void 0 : value.filter(v => allowedValues.find(f => f.name === (v._type === outputFieldTypeName ? v.relativePath : v.type)));
5452
+ const valueLength = (_a = value == null ? void 0 : value.length) != null ? _a : 0;
5453
+ const validLength = (_b = validValues == null ? void 0 : validValues.length) != null ? _b : 0;
5454
+ if (!validLength && valueLength || validLength >= allowedValues.length) {
5455
+ onChange(sanity.PatchEvent.from([sanity.unset()]));
5456
+ }
5457
+ }, [allowedValues, value, onChange]);
5458
+ }
5459
+ function ObjectOutputInput(_ref19) {
5460
+ let {
5461
+ fieldSchema,
5462
+ ...props
5463
+ } = _ref19;
5464
+ const {
5465
+ value,
5466
+ onChange
5467
+ } = props;
5468
+ const fields = react.useMemo(() => fieldSchema.fields.filter(field => isAssistSupported(field.type)), [fieldSchema.fields]);
5469
+ useEmptySelectAllValue(value, fields, onChange);
5470
+ const onSelectChange = react.useCallback((checked, selectedValue) => {
5471
+ if (checked) {
5472
+ if (value == null ? void 0 : value.length) {
5473
+ onChange(sanity.PatchEvent.from(sanity.unset([{
5474
+ _key: selectedValue
5475
+ }])));
5476
+ } else {
5477
+ const items = fields.filter(f => f.name !== selectedValue).map(field => sanity.typed({
5478
+ _key: field.name,
5479
+ _type: "sanity.assist.output.field",
5480
+ relativePath: field.name
5481
+ }));
5482
+ onChange(sanity.PatchEvent.from([sanity.setIfMissing([]), sanity.insert(items, "after", [-1])]));
5483
+ }
5484
+ } else {
5485
+ const patchValue = {
5486
+ _key: selectedValue,
5487
+ _type: "sanity.assist.output.field",
5488
+ relativePath: selectedValue
5489
+ };
5490
+ onChange(sanity.PatchEvent.from([sanity.setIfMissing([]), sanity.insert([patchValue], "after", [-1])]));
5491
+ }
5492
+ }, [onChange, value, fields]);
5493
+ return /* @__PURE__ */jsxRuntime.jsx(ui.Stack, {
5494
+ space: 2,
5495
+ children: fields.map(field => {
5496
+ var _a;
5497
+ return /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
5498
+ align: "center",
5499
+ gap: 2,
5500
+ children: /* @__PURE__ */jsxRuntime.jsx(Selectable, {
5501
+ value: field.name,
5502
+ title: (_a = field.type.title) != null ? _a : field.name,
5503
+ arrayValue: value,
5504
+ onChange: onSelectChange
5505
+ })
5506
+ }, field.name);
5507
+ })
5508
+ });
5509
+ }
5510
+ function ArrayOutputInput(_ref20) {
5511
+ let {
5512
+ fieldSchema,
5513
+ ...props
5514
+ } = _ref20;
5515
+ const {
5516
+ value,
5517
+ onChange
5518
+ } = props;
5519
+ const ofItems = react.useMemo(() => fieldSchema.of.filter(itemType => isAssistSupported(itemType)), [fieldSchema.of]);
5520
+ useEmptySelectAllValue(value, ofItems, onChange);
5521
+ const onSelectChange = react.useCallback((checked, selectedValue) => {
5522
+ if (checked) {
5523
+ if (value == null ? void 0 : value.length) {
5524
+ onChange(sanity.PatchEvent.from(sanity.unset([{
5525
+ _key: selectedValue
5526
+ }])));
5527
+ } else {
5528
+ const items = ofItems.filter(f => f.name !== selectedValue).map(field => sanity.typed({
5529
+ _key: field.name,
5530
+ _type: "sanity.assist.output.type",
5531
+ type: field.name
5532
+ }));
5533
+ onChange(sanity.PatchEvent.from([sanity.setIfMissing([]), sanity.insert(items, "after", [-1])]));
5534
+ }
5535
+ } else {
5536
+ const patchValue = {
5537
+ _key: selectedValue,
5538
+ _type: "sanity.assist.output.type",
5539
+ type: selectedValue
5540
+ };
5541
+ onChange(sanity.PatchEvent.from([sanity.setIfMissing([]), sanity.insert([patchValue], "after", [-1])]));
5542
+ }
5543
+ }, [onChange, value, ofItems]);
5544
+ return /* @__PURE__ */jsxRuntime.jsx(ui.Stack, {
5545
+ space: 2,
5546
+ children: ofItems.map(itemType => {
5547
+ var _a;
5548
+ return /* @__PURE__ */jsxRuntime.jsx(ui.Flex, {
5549
+ children: /* @__PURE__ */jsxRuntime.jsx(Selectable, {
5550
+ value: itemType.name,
5551
+ title: isType(itemType, "block") ? "Text" : (_a = itemType.title) != null ? _a : itemType.name,
5552
+ arrayValue: value,
5553
+ onChange: onSelectChange
5554
+ })
5555
+ }, itemType.name);
5556
+ })
5557
+ });
5558
+ }
5559
+ function Selectable(_ref21) {
5560
+ let {
5561
+ title,
5562
+ arrayValue,
5563
+ value,
5564
+ onChange
5565
+ } = _ref21;
5566
+ const checked = !(arrayValue == null ? void 0 : arrayValue.length) || !!(arrayValue == null ? void 0 : arrayValue.find(v => v._key === value));
5567
+ const handleChange = react.useCallback(() => onChange(checked, value), [onChange, checked, value]);
5568
+ return /* @__PURE__ */jsxRuntime.jsxs(ui.Flex, {
5569
+ gap: 2,
5570
+ align: "flex-start",
5571
+ children: [/* @__PURE__ */jsxRuntime.jsx(ui.Checkbox, {
5572
+ checked,
5573
+ onChange: handleChange
5574
+ }), /* @__PURE__ */jsxRuntime.jsx(ui.Card, {
5575
+ marginTop: 1,
5576
+ onClick: handleChange,
5577
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Text, {
5578
+ style: {
5579
+ cursor: "default"
5580
+ },
5581
+ size: 1,
5582
+ children: title
5583
+ })
5584
+ })]
5585
+ });
5586
+ }
3817
5587
  const fieldReference = sanity.defineType({
3818
5588
  type: "object",
3819
5589
  name: fieldReferenceTypeName,
3820
- title: "Document field",
5590
+ title: "Field",
3821
5591
  icon: icons.ThListIcon,
3822
5592
  fields: [sanity.defineField({
3823
5593
  type: "string",
@@ -3857,10 +5627,10 @@ const fieldReference = sanity.defineType({
3857
5627
  select: {
3858
5628
  path: "path"
3859
5629
  },
3860
- prepare(_ref14) {
5630
+ prepare(_ref22) {
3861
5631
  let {
3862
5632
  path
3863
- } = _ref14;
5633
+ } = _ref22;
3864
5634
  return {
3865
5635
  title: path,
3866
5636
  path,
@@ -3987,7 +5757,6 @@ const prompt = sanity.defineType({
3987
5757
  type: userInput.name,
3988
5758
  }),*/]
3989
5759
  });
3990
-
3991
5760
  const instruction = sanity.defineType({
3992
5761
  type: "object",
3993
5762
  name: instructionTypeName,
@@ -4006,12 +5775,12 @@ const instruction = sanity.defineType({
4006
5775
  title: "title",
4007
5776
  userId: "userId"
4008
5777
  },
4009
- prepare: _ref15 => {
5778
+ prepare: _ref23 => {
4010
5779
  let {
4011
5780
  icon,
4012
5781
  title,
4013
5782
  userId
4014
- } = _ref15;
5783
+ } = _ref23;
4015
5784
  return {
4016
5785
  title,
4017
5786
  icon: icon ? icons.icons[icon] : icons.SparklesIcon,
@@ -4116,6 +5885,33 @@ const instruction = sanity.defineType({
4116
5885
  var _a, _b;
4117
5886
  return (_b = (_a = context.currentUser) == null ? void 0 : _a.id) != null ? _b : "";
4118
5887
  }
5888
+ }), sanity.defineField({
5889
+ type: "array",
5890
+ name: "output",
5891
+ title: "Output filter",
5892
+ components: {
5893
+ input: InstructionOutputInput,
5894
+ field: InstructionOutputField
5895
+ },
5896
+ of: [sanity.defineArrayMember({
5897
+ type: "object",
5898
+ name: outputFieldTypeName,
5899
+ title: "Output field",
5900
+ fields: [{
5901
+ type: "string",
5902
+ name: "path",
5903
+ title: "Path"
5904
+ }]
5905
+ }), sanity.defineArrayMember({
5906
+ type: "object",
5907
+ name: outputTypeTypeName,
5908
+ title: "Output type",
5909
+ fields: [{
5910
+ type: "string",
5911
+ name: "type",
5912
+ title: "Type"
5913
+ }]
5914
+ })]
4119
5915
  })]
4120
5916
  });
4121
5917
  const fieldInstructions = sanity.defineType({
@@ -4332,7 +6128,7 @@ function PrivateIcon() {
4332
6128
  children: /* @__PURE__ */jsxRuntime.jsx(icons.LockIcon, {})
4333
6129
  });
4334
6130
  }
4335
- const ImageContext = react.createContext(void 0);
6131
+ const ImageContext = react.createContext({});
4336
6132
  function ImageContextProvider(props) {
4337
6133
  var _a;
4338
6134
  const {
@@ -4357,28 +6153,30 @@ function ImageContextProvider(props) {
4357
6153
  isSyncing
4358
6154
  } = sanity.useSyncState(publicId(documentId), documentSchemaType.name);
4359
6155
  react.useEffect(() => {
4360
- const captionField = getCaptionFieldOption(schemaType);
4361
- if (assetRef && documentId && captionField && assetRef !== assetRefState && !isSyncing) {
6156
+ const descriptionField = getDescriptionFieldOption(schemaType);
6157
+ if (assetRef && documentId && descriptionField && assetRef !== assetRefState && !isSyncing) {
4362
6158
  setAssetRefState(assetRef);
4363
6159
  generateCaption({
4364
- path: sanity.pathToString([...path, captionField]),
6160
+ path: sanity.pathToString([...path, descriptionField]),
4365
6161
  documentId
4366
6162
  });
4367
6163
  }
4368
6164
  }, [schemaType, path, assetRef, assetRefState, documentId, generateCaption, isSyncing]);
4369
6165
  const context = react.useMemo(() => {
4370
- const captionField = getCaptionFieldOption(schemaType);
4371
- return captionField ? {
4372
- captionPath: sanity.pathToString([...path, captionField]),
6166
+ const descriptionField = getDescriptionFieldOption(schemaType);
6167
+ const imageInstructionField = getImageInstructionFieldOption(schemaType);
6168
+ return {
6169
+ imageDescriptionPath: descriptionField ? sanity.pathToString([...path, descriptionField]) : void 0,
6170
+ imageInstructionPath: imageInstructionField ? sanity.pathToString([...path, imageInstructionField]) : void 0,
4373
6171
  assetRef
4374
- } : void 0;
6172
+ };
4375
6173
  }, [schemaType, path, assetRef]);
4376
6174
  return /* @__PURE__ */jsxRuntime.jsx(ImageContext.Provider, {
4377
6175
  value: context,
4378
6176
  children: props.renderDefault(props)
4379
6177
  });
4380
6178
  }
4381
- function node$1(node2) {
6179
+ function node$3(node2) {
4382
6180
  return node2;
4383
6181
  }
4384
6182
  const generateCaptionsActions = {
@@ -4394,12 +6192,12 @@ const generateCaptionsActions = {
4394
6192
  loading
4395
6193
  } = useGenerateCaption(apiClient);
4396
6194
  const imageContext = react.useContext(ImageContext);
4397
- if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.captionPath)) {
6195
+ if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageDescriptionPath)) {
4398
6196
  const {
4399
6197
  documentId
4400
6198
  } = useAssistDocumentContext();
4401
6199
  return react.useMemo(() => {
4402
- return node$1({
6200
+ return node$3({
4403
6201
  type: "action",
4404
6202
  icon: loading ? () => /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
4405
6203
  style: {
@@ -4411,7 +6209,7 @@ const generateCaptionsActions = {
4411
6209
  }
4412
6210
  })
4413
6211
  }) : icons.ImageIcon,
4414
- title: "Generate caption",
6212
+ title: "Generate image description",
4415
6213
  onAction: () => {
4416
6214
  if (loading) {
4417
6215
  return;
@@ -4430,6 +6228,185 @@ const generateCaptionsActions = {
4430
6228
  return void 0;
4431
6229
  }
4432
6230
  };
6231
+ function node$2(node2) {
6232
+ return node2;
6233
+ }
6234
+ const translateActions = {
6235
+ name: "sanity-assist-translate",
6236
+ useAction(props) {
6237
+ var _a, _b, _c, _d, _e, _f, _g, _h;
6238
+ const {
6239
+ config,
6240
+ status
6241
+ } = useAiAssistanceConfig();
6242
+ const apiClient = useApiClient(config == null ? void 0 : config.__customApiClient);
6243
+ const {
6244
+ schemaType: fieldSchemaType,
6245
+ path,
6246
+ documentId,
6247
+ documentSchemaType,
6248
+ documentIsAssistable
6249
+ } = props;
6250
+ const isDocumentLevel = path.length === 0;
6251
+ const readOnly = fieldSchemaType.readOnly === true;
6252
+ const docTransTypes = (_b = (_a = config.translate) == null ? void 0 : _a.document) == null ? void 0 : _b.documentTypes;
6253
+ const options = fieldSchemaType == null ? void 0 : fieldSchemaType.options;
6254
+ const addFieldAction = isDocumentLevel || ((_c = options == null ? void 0 : options.aiAssist) == null ? void 0 : _c.translateAction);
6255
+ const fieldTransEnabled = addFieldAction && documentSchemaType && ((_f = (_e = (_d = config.translate) == null ? void 0 : _d.field) == null ? void 0 : _e.documentTypes) == null ? void 0 : _f.includes(documentSchemaType.name));
6256
+ const documentTranslationEnabled = addFieldAction && documentSchemaType && (!docTransTypes && isAssistSupported(fieldSchemaType) || (docTransTypes == null ? void 0 : docTransTypes.includes(documentSchemaType.name)));
6257
+ if (documentSchemaType && (documentTranslationEnabled || fieldTransEnabled)) {
6258
+ const {
6259
+ value: documentValue,
6260
+ onChange: documentOnChange,
6261
+ formState
6262
+ } = desk.useDocumentPane();
6263
+ const docRef = react.useRef(documentValue);
6264
+ docRef.current = documentValue;
6265
+ const formStateRef = react.useRef(formState);
6266
+ formStateRef.current = formState;
6267
+ const translationApi = useTranslate(apiClient);
6268
+ const translate = useDraftDelayedTask({
6269
+ documentOnChange,
6270
+ isDocAssistable: documentIsAssistable != null ? documentIsAssistable : false,
6271
+ task: translationApi.translate
6272
+ });
6273
+ const languagePath = (_h = (_g = config.translate) == null ? void 0 : _g.document) == null ? void 0 : _h.languageField;
6274
+ const translateDocumentAction = react.useMemo(() => {
6275
+ if (!languagePath || !documentTranslationEnabled) {
6276
+ return void 0;
6277
+ }
6278
+ const title = path.length ? "Translate" : "Translate document";
6279
+ return node$2({
6280
+ type: "action",
6281
+ icon: translationApi.loading ? () => /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
6282
+ style: {
6283
+ height: 17
6284
+ },
6285
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {
6286
+ style: {
6287
+ transform: "translateY(6px)"
6288
+ }
6289
+ })
6290
+ }) : icons.TranslateIcon,
6291
+ title,
6292
+ onAction: () => {
6293
+ if (translationApi.loading || !languagePath || !documentId) {
6294
+ return;
6295
+ }
6296
+ translate({
6297
+ languagePath,
6298
+ translatePath: path,
6299
+ documentId: documentId != null ? documentId : "",
6300
+ conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
6301
+ });
6302
+ },
6303
+ renderAsButton: true,
6304
+ disabled: translationApi.loading || readOnly
6305
+ });
6306
+ }, [languagePath, translate, documentId, translationApi.loading, documentTranslationEnabled, path, readOnly]);
6307
+ const fieldTranslate = useFieldTranslation();
6308
+ const openFieldTranslation = useDraftDelayedTask({
6309
+ documentOnChange,
6310
+ isDocAssistable: documentIsAssistable != null ? documentIsAssistable : false,
6311
+ task: fieldTranslate.openFieldTranslation
6312
+ });
6313
+ const translateFieldsAction = react.useMemo(() => fieldTransEnabled ? node$2({
6314
+ type: "action",
6315
+ icon: fieldTranslate.translationLoading ? () => /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
6316
+ style: {
6317
+ height: 17
6318
+ },
6319
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {
6320
+ style: {
6321
+ transform: "translateY(6px)"
6322
+ }
6323
+ })
6324
+ }) : icons.TranslateIcon,
6325
+ title: "Translate fields...",
6326
+ onAction: () => {
6327
+ if (fieldTranslate.translationLoading || !documentId) {
6328
+ return;
6329
+ }
6330
+ if (formStateRef.current) {
6331
+ getConditionalMembers(formStateRef.current);
6332
+ }
6333
+ openFieldTranslation({
6334
+ document: docRef.current,
6335
+ documentSchema: documentSchemaType,
6336
+ translatePath: path,
6337
+ conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
6338
+ });
6339
+ },
6340
+ renderAsButton: true,
6341
+ disabled: fieldTranslate.translationLoading || readOnly
6342
+ }) : void 0, [openFieldTranslation, documentSchemaType, documentId, fieldTranslate.translationLoading, fieldTransEnabled, path, readOnly]);
6343
+ return react.useMemo(() => {
6344
+ if (!(status == null ? void 0 : status.initialized)) {
6345
+ return void 0;
6346
+ }
6347
+ return node$2({
6348
+ type: "group",
6349
+ icon: () => null,
6350
+ title: "Translation",
6351
+ children: [translateDocumentAction, translateFieldsAction].filter(c => !!c),
6352
+ expanded: true
6353
+ });
6354
+ }, [translateDocumentAction, translateFieldsAction, status]);
6355
+ }
6356
+ return void 0;
6357
+ }
6358
+ };
6359
+ function node$1(node2) {
6360
+ return node2;
6361
+ }
6362
+ const generateImagActions = {
6363
+ name: "sanity-assist-generate-image",
6364
+ useAction(props) {
6365
+ const pathKey = usePathKey(props.path);
6366
+ const {
6367
+ config
6368
+ } = useAiAssistanceConfig();
6369
+ const apiClient = useApiClient(config == null ? void 0 : config.__customApiClient);
6370
+ const {
6371
+ generateImage,
6372
+ loading
6373
+ } = useGenerateImage(apiClient);
6374
+ const imageContext = react.useContext(ImageContext);
6375
+ if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageInstructionPath)) {
6376
+ const {
6377
+ documentId
6378
+ } = useAssistDocumentContext();
6379
+ return react.useMemo(() => {
6380
+ return node$1({
6381
+ type: "action",
6382
+ icon: loading ? () => /* @__PURE__ */jsxRuntime.jsx(ui.Box, {
6383
+ style: {
6384
+ height: 17
6385
+ },
6386
+ children: /* @__PURE__ */jsxRuntime.jsx(ui.Spinner, {
6387
+ style: {
6388
+ transform: "translateY(6px)"
6389
+ }
6390
+ })
6391
+ }) : icons.ImageIcon,
6392
+ title: "Generate image from prompt",
6393
+ onAction: () => {
6394
+ if (loading) {
6395
+ return;
6396
+ }
6397
+ generateImage({
6398
+ path: pathKey,
6399
+ documentId: documentId != null ? documentId : ""
6400
+ });
6401
+ },
6402
+ renderAsButton: true,
6403
+ disabled: loading
6404
+ });
6405
+ }, [generateImage, pathKey, documentId, loading]);
6406
+ }
6407
+ return void 0;
6408
+ }
6409
+ };
4433
6410
  function node(node2) {
4434
6411
  return node2;
4435
6412
  }
@@ -4450,7 +6427,8 @@ const assistFieldActions = {
4450
6427
  documentOnChange,
4451
6428
  documentSchemaType,
4452
6429
  documentId,
4453
- selectedPath
6430
+ selectedPath,
6431
+ assistableDocumentId
4454
6432
  } =
4455
6433
  // document field actions do not have access to the document context
4456
6434
  // conditional hook _should_ be safe here since the logical path will be stable
@@ -4460,8 +6438,11 @@ const assistFieldActions = {
4460
6438
  // eslint-disable-next-line react-hooks/rules-of-hooks
4461
6439
  useAssistDocumentContext();
4462
6440
  const {
4463
- value: docValue
6441
+ value: docValue,
6442
+ formState
4464
6443
  } = desk.useDocumentPane();
6444
+ const formStateRef = react.useRef(formState);
6445
+ formStateRef.current = formState;
4465
6446
  const currentUser = sanity.useCurrentUser();
4466
6447
  const isHidden = !assistDocument;
4467
6448
  const pathKey = usePathKey(props.path);
@@ -4475,7 +6456,7 @@ const assistFieldActions = {
4475
6456
  isDocAssistable: documentIsAssistable != null ? documentIsAssistable : false
4476
6457
  });
4477
6458
  const isSelectable = !!useSelectedField(documentSchemaType, typePath);
4478
- const assistSupported = useAssistSupported(props.path, schemaType) && isSelectable && isSchemaAssistEnabled(documentSchemaType);
6459
+ const assistSupported = useAssistSupported(props.path, schemaType) && isSelectable && isSchemaAssistEnabled(documentSchemaType) && schemaType.readOnly !== true;
4479
6460
  const fieldAssist = react.useMemo(() => {
4480
6461
  var _a;
4481
6462
  return ((_a = assistDocument == null ? void 0 : assistDocument.fields) != null ? _a : []).find(f => f.path === typePath || pathKey === documentRootKey && f.path === pathKey);
@@ -4485,6 +6466,13 @@ const assistFieldActions = {
4485
6466
  const isPathSelected = pathKey === selectedPath;
4486
6467
  const isSelected = isInspectorOpen && isPathSelected;
4487
6468
  const imageCaptionAction = generateCaptionsActions.useAction(props);
6469
+ const imageGenAction = generateImagActions.useAction(props);
6470
+ const translateAction = translateActions.useAction(sanity.typed({
6471
+ ...props,
6472
+ documentId: assistableDocumentId,
6473
+ documentIsAssistable,
6474
+ documentSchemaType
6475
+ }));
4488
6476
  const manageInstructions = react.useCallback(() => isSelected ? closeInspector(aiInspectorId) : openInspector(aiInspectorId, {
4489
6477
  [fieldPathParam]: pathKey,
4490
6478
  [instructionParam]: void 0
@@ -4498,7 +6486,8 @@ const assistFieldActions = {
4498
6486
  assistDocumentId,
4499
6487
  path: pathKey,
4500
6488
  typePath,
4501
- instruction
6489
+ instruction,
6490
+ conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
4502
6491
  });
4503
6492
  }, [requestRunInstruction, assistableDocId, pathKey, typePath, assistDocumentId, fieldAssistKey]);
4504
6493
  const privateInstructions = react.useMemo(() => {
@@ -4511,7 +6500,7 @@ const assistFieldActions = {
4511
6500
  }, [fieldAssist == null ? void 0 : fieldAssist.instructions]);
4512
6501
  const instructions = react.useMemo(() => [...privateInstructions, ...sharedInstructions], [privateInstructions, sharedInstructions]);
4513
6502
  const runInstructionsGroup = react.useMemo(() => {
4514
- return (instructions == null ? void 0 : instructions.length) || imageCaptionAction ? node({
6503
+ return (instructions == null ? void 0 : instructions.length) || imageCaptionAction || translateAction || imageGenAction ? node({
4515
6504
  type: "group",
4516
6505
  icon: () => null,
4517
6506
  title: "Run instructions",
@@ -4522,10 +6511,10 @@ const assistFieldActions = {
4522
6511
  hidden: isHidden,
4523
6512
  documentIsNew: !!documentIsNew,
4524
6513
  assistSupported
4525
- }))), imageCaptionAction].filter(Boolean),
6514
+ }))), imageCaptionAction, imageGenAction].filter(a => !!a),
4526
6515
  expanded: true
4527
6516
  }) : void 0;
4528
- }, [instructions, currentUser == null ? void 0 : currentUser.id, onInstructionAction, isHidden, documentIsNew, assistSupported, imageCaptionAction]);
6517
+ }, [instructions, currentUser == null ? void 0 : currentUser.id, onInstructionAction, isHidden, documentIsNew, assistSupported, imageCaptionAction, translateAction, imageGenAction]);
4529
6518
  const instructionsLength = (instructions == null ? void 0 : instructions.length) || 0;
4530
6519
  const manageInstructionsItem = react.useMemo(() => node({
4531
6520
  type: "action",
@@ -4538,13 +6527,13 @@ const assistFieldActions = {
4538
6527
  type: "group",
4539
6528
  icon: icons.SparklesIcon,
4540
6529
  title: pluginTitleShort,
4541
- children: [runInstructionsGroup, assistSupported && manageInstructionsItem].filter(c => !!c),
6530
+ children: [runInstructionsGroup, translateAction, assistSupported && manageInstructionsItem].filter(c => !!c).filter(c => c.type === "group" ? c.children.length : true),
4542
6531
  expanded: false,
4543
6532
  renderAsButton: true,
4544
- hidden: !assistSupported && !imageCaptionAction
6533
+ hidden: !assistSupported && !imageCaptionAction && !translateAction && !imageGenAction
4545
6534
  }), [
4546
6535
  //documentIsNew,
4547
- runInstructionsGroup, manageInstructionsItem, assistSupported, imageCaptionAction]);
6536
+ runInstructionsGroup, manageInstructionsItem, assistSupported, imageCaptionAction, translateAction, imageGenAction]);
4548
6537
  const emptyAction = react.useMemo(() => node({
4549
6538
  type: "action",
4550
6539
  hidden: !assistSupported,
@@ -4554,7 +6543,7 @@ const assistFieldActions = {
4554
6543
  title: pluginTitleShort,
4555
6544
  selected: isSelected
4556
6545
  }), [assistSupported, manageInstructions, isSelected]);
4557
- if (instructionsLength === 0 && !imageCaptionAction) {
6546
+ if (instructionsLength === 0 && !imageCaptionAction && !translateAction && !imageGenAction) {
4558
6547
  return emptyAction;
4559
6548
  }
4560
6549
  return group;
@@ -4574,9 +6563,7 @@ function instructionItem(props) {
4574
6563
  iconRight: isPrivate ? PrivateIcon : void 0,
4575
6564
  title: getInstructionTitle(instruction),
4576
6565
  onAction: () => onInstructionAction(instruction),
4577
- disabled: assistSupported ? false : {
4578
- reason: "".concat(pluginTitle, " is not supported for this field")
4579
- },
6566
+ disabled: !assistSupported,
4580
6567
  hidden
4581
6568
  });
4582
6569
  }
@@ -4653,7 +6640,7 @@ function useInstructionToaster(documentId, documentSchemaType) {
4653
6640
  }
4654
6641
  function AssistDocumentInputWrapper(props) {
4655
6642
  var _a;
4656
- if (!isType(props.schemaType, "document") && props.id !== "root") {
6643
+ if (!isType(props.schemaType, "document") && props.id !== "root" && props.id !== assistFormId) {
4657
6644
  return /* @__PURE__ */jsxRuntime.jsx(AssistInput, {
4658
6645
  ...props
4659
6646
  });
@@ -4667,18 +6654,34 @@ function AssistDocumentInputWrapper(props) {
4667
6654
  documentId
4668
6655
  });
4669
6656
  }
4670
- function AssistDocumentInput(_ref16) {
6657
+ function AssistDocumentInput(_ref24) {
4671
6658
  let {
4672
6659
  documentId,
4673
6660
  ...props
4674
- } = _ref16;
6661
+ } = _ref24;
4675
6662
  useInstructionToaster(documentId, props.schemaType);
6663
+ const schemaType = react.useMemo(() => {
6664
+ if (props.schemaType.name !== assistDocumentTypeName) {
6665
+ return props.schemaType;
6666
+ }
6667
+ return {
6668
+ ...props.schemaType,
6669
+ type: {
6670
+ ...props.schemaType.type,
6671
+ // compatability with i18nArrays plugin that requires this to be document
6672
+ name: "document"
6673
+ }
6674
+ };
6675
+ }, [props.schemaType]);
4676
6676
  return /* @__PURE__ */jsxRuntime.jsx(FirstAssistedPathProvider, {
4677
6677
  members: props.members,
4678
6678
  children: /* @__PURE__ */jsxRuntime.jsx(AssistDocumentContextProvider, {
4679
- schemaType: props.schemaType,
6679
+ schemaType,
4680
6680
  documentId,
4681
- children: props.renderDefault(props)
6681
+ children: props.renderDefault({
6682
+ ...props,
6683
+ schemaType
6684
+ })
4682
6685
  })
4683
6686
  });
4684
6687
  }
@@ -4716,11 +6719,11 @@ function AssistDocumentPresence(props) {
4716
6719
  const anyPresence2 = (_b = (_a = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _a.filter(run => !run.ended && !run.reason)) == null ? void 0 : _b.flatMap(run => {
4717
6720
  var _a2;
4718
6721
  return (_a2 = run.presence) != null ? _a2 : [];
4719
- }).find(f => f.started && /* @__PURE__ */new Date().getTime() - new Date(f.started).getTime() < 3e4);
6722
+ }).find(f => f.started && ( /* @__PURE__ */new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4720
6723
  if (anyPresence2) {
4721
6724
  return aiPresence(anyPresence2, []);
4722
6725
  }
4723
- const anyRun = (_d = (_c = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _c.filter(run => !run.ended && !run.reason)) == null ? void 0 : _d.find(f => f.started && /* @__PURE__ */new Date().getTime() - new Date(f.started).getTime() < 3e4);
6726
+ const anyRun = (_d = (_c = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _c.filter(run => !run.ended && !run.reason)) == null ? void 0 : _d.find(f => f.started && ( /* @__PURE__ */new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4724
6727
  return anyRun ? aiPresence({
4725
6728
  started: anyRun.started,
4726
6729
  path: documentRootKey,
@@ -4749,31 +6752,41 @@ const assist = sanity.definePlugin(config => {
4749
6752
  schema: {
4750
6753
  types: schemaTypes
4751
6754
  },
6755
+ i18n: {
6756
+ bundles: [{}]
6757
+ },
4752
6758
  document: {
4753
6759
  inspectors: (prev, context) => {
4754
- const docSchema = context.schema.get(context.documentType);
6760
+ const documentType = context.documentType;
6761
+ const docSchema = context.schema.get(documentType);
4755
6762
  if (docSchema && isSchemaAssistEnabled(docSchema)) {
4756
6763
  return [...prev, assistInspector];
4757
6764
  }
4758
6765
  return prev;
4759
6766
  },
4760
- unstable_fieldActions: (prev, _ref17) => {
6767
+ unstable_fieldActions: (prev, _ref25) => {
4761
6768
  let {
4762
6769
  documentType,
4763
6770
  schema
4764
- } = _ref17;
6771
+ } = _ref25;
6772
+ if (documentType === assistDocumentTypeName) {
6773
+ return [];
6774
+ }
4765
6775
  const docSchema = schema.get(documentType);
4766
6776
  if (docSchema && isSchemaAssistEnabled(docSchema)) {
4767
6777
  return [...prev, assistFieldActions];
4768
6778
  }
4769
6779
  return prev;
4770
6780
  },
4771
- unstable_languageFilter: (prev, _ref18) => {
6781
+ unstable_languageFilter: (prev, _ref26) => {
4772
6782
  let {
4773
6783
  documentId,
4774
6784
  schema,
4775
6785
  schemaType
4776
- } = _ref18;
6786
+ } = _ref26;
6787
+ if (schemaType === assistDocumentTypeName) {
6788
+ return [];
6789
+ }
4777
6790
  const docSchema = schema.get(schemaType);
4778
6791
  if (docSchema && sanity.isObjectSchemaType(docSchema) && isSchemaAssistEnabled(docSchema)) {
4779
6792
  return [...prev, createAssistDocumentPresence(documentId, docSchema)];
@@ -4830,4 +6843,5 @@ const assist = sanity.definePlugin(config => {
4830
6843
  exports.SchemaTypeTool = SchemaTypeTool;
4831
6844
  exports.assist = assist;
4832
6845
  exports.contextDocumentTypeName = contextDocumentTypeName;
6846
+ exports.defaultLanguageOutputs = defaultLanguageOutputs;
4833
6847
  //# sourceMappingURL=index.js.map