@sanity/assist 3.0.9 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -64,16 +64,13 @@ function isImage(schemaType) {
64
64
  return isType(schemaType, "image");
65
65
  }
66
66
  function getDescriptionFieldOption(schemaType) {
67
- var _a, _b;
68
- return schemaType ? ((_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageDescriptionField) || getDescriptionFieldOption(schemaType.type) : void 0;
67
+ return schemaType ? schemaType.options?.aiAssist?.imageDescriptionField || getDescriptionFieldOption(schemaType.type) : void 0;
69
68
  }
70
69
  function getImageInstructionFieldOption(schemaType) {
71
- var _a, _b;
72
- return schemaType ? ((_b = (_a = schemaType.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField) || getImageInstructionFieldOption(schemaType.type) : void 0;
70
+ return schemaType ? schemaType.options?.aiAssist?.imageInstructionField || getImageInstructionFieldOption(schemaType.type) : void 0;
73
71
  }
74
72
  function isSchemaAssistEnabled(type) {
75
- var _a, _b;
76
- return !((_b = (_a = type.options) == null ? void 0 : _a.aiAssist) != null && _b.exclude);
73
+ return !type.options?.aiAssist?.exclude;
77
74
  }
78
75
  function isAssistSupported(type) {
79
76
  return !isSchemaAssistEnabled(type) || isDisabled(type) ? !1 : type.jsonType === "array" ? !type.of.every((t) => isDisabled(t)) : type.jsonType === "object" ? !type.fields.every((field) => isDisabled(field.type)) : !0;
@@ -82,8 +79,7 @@ function isDisabled(type) {
82
79
  return !isSchemaAssistEnabled(type) || isUnsupportedType(type);
83
80
  }
84
81
  function isUnsupportedType(type) {
85
- var _a, _b;
86
- 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 && _b.embeddingsIndex) || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
82
+ return type.jsonType === "number" || type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "reference") && !type?.options?.aiAssist?.embeddingsIndex || isType(type, "crossDatasetReference") || isType(type, "slug") || isType(type, "url") || isType(type, "date") || isType(type, "datetime") || isType(type, "file");
87
83
  }
88
84
  const hiddenTypes = [
89
85
  "any",
@@ -121,18 +117,14 @@ const hiddenTypes = [
121
117
  ], inlineTypes = ["document", "object", "image", "file"];
122
118
  function serializeSchema(schema, options2) {
123
119
  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, options2)).filter((t) => !("to" in t && t.to && !t.to.length || "of" in t && t.of && !t.of.length || "fields" in t && t.fields && !t.fields.length));
124
- return list.sort((a, b) => {
125
- var _a, _b;
126
- return ((_a = a == null ? void 0 : a.name) != null ? _a : "").localeCompare((_b = b == null ? void 0 : b.name) != null ? _b : "");
127
- }), list;
120
+ return list.sort((a, b) => (a?.name ?? "").localeCompare(b?.name ?? "")), list;
128
121
  }
129
122
  function getSchemaStub(schemaType, schema, options2) {
130
- var _a;
131
- if (!((_a = schemaType.type) != null && _a.name))
123
+ if (!schemaType.type?.name)
132
124
  throw console.error("Missing type name", schemaType.type), new Error("Type is missing name!");
133
125
  const baseSchema = {
134
126
  // we dont need type or id when we send using POST, so leave these out to save bandwidth
135
- ...options2 != null && options2.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
127
+ ...options2?.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
136
128
  name: schemaType.name,
137
129
  title: schemaType.title,
138
130
  type: schemaType.type.name,
@@ -141,18 +133,14 @@ function getSchemaStub(schemaType, schema, options2) {
141
133
  return removeUndef(baseSchema);
142
134
  }
143
135
  function getBaseFields(schema, type, typeName, options2) {
144
- var _a, _b, _c, _d, _e, _f;
145
136
  const schemaOptions = removeUndef({
146
- imagePromptField: (_b = (_a = type.options) == null ? void 0 : _a.aiAssist) == null ? void 0 : _b.imageInstructionField,
147
- embeddingsIndex: (_d = (_c = type.options) == null ? void 0 : _c.aiAssist) == null ? void 0 : _d.embeddingsIndex
137
+ imagePromptField: type.options?.aiAssist?.imageInstructionField,
138
+ embeddingsIndex: type.options?.aiAssist?.embeddingsIndex
148
139
  });
149
140
  return removeUndef({
150
141
  options: Object.keys(schemaOptions).length ? schemaOptions : void 0,
151
- 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(
152
- (v) => {
153
- var _a2;
154
- return typeof v == "string" ? v : (_a2 = v.value) != null ? _a2 : `${v.title}`;
155
- }
142
+ values: Array.isArray(type?.options?.list) ? type?.options?.list.map(
143
+ (v) => typeof v == "string" ? v : v.value ?? `${v.title}`
156
144
  ) : void 0,
157
145
  of: "of" in type && typeName === "array" ? arrayOf(type, schema, options2) : void 0,
158
146
  to: "to" in type && typeName === "reference" ? refToTypeNames(type) : void 0,
@@ -175,16 +163,12 @@ function serializeFields(schema, schemaType, options2) {
175
163
  hidden: typeof fs.hidden == "function" ? fs.hidden : fs.hidden ? !0 : f.type.hidden
176
164
  }
177
165
  }))
178
- ) : schemaType.fields).filter((f) => {
179
- var _a, _b;
180
- return !["sanity.imageHotspot", "sanity.imageCrop"].includes((_b = (_a = f.type) == null ? void 0 : _a.name) != null ? _b : "");
181
- }).filter((f) => isAssistSupported(f.type)).map((field) => serializeMember(schema, field.type, field.name, options2));
166
+ ) : schemaType.fields).filter((f) => !["sanity.imageHotspot", "sanity.imageCrop"].includes(f.type?.name ?? "")).filter((f) => isAssistSupported(f.type)).map((field) => serializeMember(schema, field.type, field.name, options2));
182
167
  }
183
168
  function serializeMember(schema, type, name, options2) {
184
- var _a, _b;
185
- const typeName = schema.get(type == null ? void 0 : type.name) ? type.name : (_b = (_a = type.type) == null ? void 0 : _a.name) != null ? _b : "";
169
+ const typeName = schema.get(type?.name) ? type.name : type.type?.name ?? "";
186
170
  return removeUndef({
187
- ...options2 != null && options2.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
171
+ ...options2?.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
188
172
  name,
189
173
  type: typeName,
190
174
  title: type.title,
@@ -192,7 +176,7 @@ function serializeMember(schema, type, name, options2) {
192
176
  });
193
177
  }
194
178
  function serializeInlineOf(blockSchemaType, schema, options2) {
195
- const childrenField = blockSchemaType.fields.find((f) => f.name === "children"), childrenType = childrenField == null ? void 0 : childrenField.type;
179
+ const childrenType = blockSchemaType.fields.find((f) => f.name === "children")?.type;
196
180
  if (!(!childrenType || !sanity.isArraySchemaType(childrenType)))
197
181
  return arrayOf(
198
182
  {
@@ -204,7 +188,7 @@ function serializeInlineOf(blockSchemaType, schema, options2) {
204
188
  );
205
189
  }
206
190
  function serializeAnnotations(blockSchemaType, schema, options2) {
207
- const markDefs = blockSchemaType.fields.find((f) => f.name === "markDefs"), marksType = markDefs == null ? void 0 : markDefs.type;
191
+ const marksType = blockSchemaType.fields.find((f) => f.name === "markDefs")?.type;
208
192
  if (!(!marksType || !sanity.isArraySchemaType(marksType)))
209
193
  return arrayOf(marksType, schema, options2);
210
194
  }
@@ -258,7 +242,7 @@ function SchemaTypeTool() {
258
242
  ] }),
259
243
  /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 2, children: [
260
244
  /* @__PURE__ */ jsxRuntime.jsx(ui.Label, { children: "Stored schema" }),
261
- /* @__PURE__ */ jsxRuntime.jsx("ul", { children: (data != null ? data : NO_DATA).map((type) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsx(SchemaEntry, { schemaStub: type }) }, type.name)) })
245
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { children: (data ?? NO_DATA).map((type) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: /* @__PURE__ */ jsxRuntime.jsx(SchemaEntry, { schemaStub: type }) }, type.name)) })
262
246
  ] })
263
247
  ] })
264
248
  ] }) });
@@ -273,8 +257,7 @@ function getDocumentMembersFlat(doc, schemaType) {
273
257
  }
274
258
  function extractPaths(doc, schemaType, path, maxDepth2) {
275
259
  return path.length >= maxDepth2 ? [] : schemaType.fields.reduce((acc, field) => {
276
- var _a, _b;
277
- const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = (_a = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _a : {};
260
+ const fieldPath = [...path, field.name], fieldSchema = field.type, { value } = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0] ?? {};
278
261
  if (!value)
279
262
  return acc;
280
263
  const thisFieldWithPath = {
@@ -287,9 +270,9 @@ function extractPaths(doc, schemaType, path, maxDepth2) {
287
270
  const innerFields = extractPaths(doc, fieldSchema, fieldPath, maxDepth2);
288
271
  return [...acc, thisFieldWithPath, ...innerFields];
289
272
  } else if (fieldSchema.jsonType === "array" && fieldSchema.of.length && fieldSchema.of.some((item) => "fields" in item)) {
290
- const { value: arrayValue } = (_b = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0]) != null ? _b : {};
273
+ const { value: arrayValue } = mutator.extractWithPath(sanity.pathToString(fieldPath), doc)[0] ?? {};
291
274
  let arrayPaths = [];
292
- if (arrayValue != null && arrayValue.length)
275
+ if (arrayValue?.length)
293
276
  for (const item of arrayValue) {
294
277
  const itemPath = [...fieldPath, { _key: item._key }];
295
278
  let itemSchema = fieldSchema.of.find((t) => t.name === item._type);
@@ -335,15 +318,14 @@ const defaultLanguageOutputs = function(member, enclosingType, translateFromLang
335
318
  })) : void 0;
336
319
  };
337
320
  function getFieldLanguageMap(documentSchema, documentMembers, translateFromLanguageId, outputLanguageIds, langFn) {
338
- var _a, _b, _c;
339
321
  const translationMaps = [];
340
322
  for (const member of documentMembers) {
341
- const parentPath = member.path.slice(0, -1), enclosingType = (_b = (_a = documentMembers.find((m) => sanity.pathToString(m.path) === sanity.pathToString(parentPath))) == null ? void 0 : _a.schemaType) != null ? _b : documentSchema, translations = (_c = langFn(
323
+ const parentPath = member.path.slice(0, -1), enclosingType = documentMembers.find((m) => sanity.pathToString(m.path) === sanity.pathToString(parentPath))?.schemaType ?? documentSchema, translations = langFn(
342
324
  member,
343
325
  enclosingType,
344
326
  translateFromLanguageId,
345
327
  outputLanguageIds
346
- )) == null ? void 0 : _c.filter((translation) => translation.id !== translateFromLanguageId);
328
+ )?.filter((translation) => translation.id !== translateFromLanguageId);
347
329
  translations && translationMaps.push({
348
330
  inputLanguageId: translateFromLanguageId,
349
331
  inputPath: member.path,
@@ -354,7 +336,6 @@ function getFieldLanguageMap(documentSchema, documentMembers, translateFromLangu
354
336
  }
355
337
  const releaseAnnouncementUrl = "https://www.sanity.io/blog/sanity-ai-assist-announcement?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", instructionGuideUrl = "https://sanity.io/guides/getting-started-with-ai-assist-instructions?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", giveFeedbackUrl = "https://forms.gle/Kwz7CThxGeA2GiEU8", salesUrl = "https://www.sanity.io/contact/sales?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", packageName = "@sanity/assist", pluginTitle = "Sanity AI Assist", pluginTitleShort = "AI Assist", maxHistoryVisibilityMs = dateFns.minutesToMilliseconds(30), assistFormId = "assist", preventDefault = (ev) => ev.preventDefault();
356
338
  function DocumentForm(props) {
357
- var _a;
358
339
  const {
359
340
  collapsedFieldSets,
360
341
  collapsedPaths,
@@ -372,7 +353,7 @@ function DocumentForm(props) {
372
353
  onSetCollapsedPath,
373
354
  ready,
374
355
  validation
375
- } = structure.useDocumentPane(), documentStore = sanity.useDocumentStore(), presence = sanity.useDocumentPresence(documentId), patchChannel = react.useMemo(() => sanity.createPatchChannel(), []), isLocked = (_a = editState == null ? void 0 : editState.transactionSyncLock) == null ? void 0 : _a.enabled;
356
+ } = structure.useDocumentPane(), documentStore = sanity.useDocumentStore(), presence = sanity.useDocumentPresence(documentId), patchChannel = react.useMemo(() => sanity.createPatchChannel(), []), isLocked = editState?.transactionSyncLock?.enabled;
376
357
  react.useEffect(() => {
377
358
  const sub = documentStore.pair.documentEvents(documentId, documentType).pipe(
378
359
  operators.tap((event) => {
@@ -383,7 +364,7 @@ function DocumentForm(props) {
383
364
  sub.unsubscribe();
384
365
  };
385
366
  }, [documentId, documentStore, documentType, patchChannel]);
386
- const hasRev = !!(value != null && value._rev);
367
+ const hasRev = !!value?._rev;
387
368
  react.useEffect(() => {
388
369
  hasRev && patchChannel.publish({
389
370
  type: "mutation",
@@ -476,14 +457,11 @@ function prepareRebaseEvent(event) {
476
457
  };
477
458
  }
478
459
  const AssistTypeContext = react.createContext({}), illegalIdChars = /[^a-zA-Z0-9._-]/g;
479
- function publicId(id) {
480
- return id.replace("drafts.", "");
481
- }
482
460
  function assistDocumentId(documentType) {
483
461
  return `${assistDocumentIdPrefix}${documentType}`.replace(illegalIdChars, "_");
484
462
  }
485
463
  function assistTasksStatusId(documentId) {
486
- return `${assistDocumentStatusIdPrefix}${publicId(documentId)}`;
464
+ return sanity.isVersionId(documentId) ? `${assistDocumentStatusIdPrefix}${sanity.getVersionFromId(documentId)}.${sanity.getPublishedId(documentId)}` : `${assistDocumentStatusIdPrefix}${sanity.getPublishedId(documentId)}`;
487
465
  }
488
466
  function useDocumentState(id, docType) {
489
467
  const state = sanity.useEditState(id, docType);
@@ -498,7 +476,7 @@ function useStudioAssistDocument({
498
476
  assistDocumentId(documentTypeName),
499
477
  assistDocumentTypeName
500
478
  ), assistTasksStatus = useDocumentState(
501
- assistTasksStatusId(documentId != null ? documentId : ""),
479
+ assistTasksStatusId(documentId ?? ""),
502
480
  assistTasksStatusTypeName
503
481
  ), client = sanity.useClient({ apiVersion: "2023-01-01" });
504
482
  return react.useEffect(() => {
@@ -508,22 +486,17 @@ function useStudioAssistDocument({
508
486
  }).catch(() => {
509
487
  });
510
488
  }, [client, assistDocument, documentTypeName, initDoc]), react.useMemo(() => {
511
- var _a, _b;
512
489
  if (!assistDocument)
513
490
  return;
514
- const tasks = (_a = assistTasksStatus == null ? void 0 : assistTasksStatus.tasks) != null ? _a : [], fields = ((_b = assistDocument == null ? void 0 : assistDocument.fields) != null ? _b : []).map((assistField) => {
515
- var _a2;
516
- return {
517
- ...assistField,
518
- tasks: tasks.filter((task) => task.path === assistField.path),
519
- instructions: (_a2 = assistField.instructions) == null ? void 0 : _a2.filter((p) => !p.userId || p.userId === (currentUser == null ? void 0 : currentUser.id)).map((instruction2) => asStudioInstruction(instruction2, tasks))
520
- };
521
- });
491
+ const tasks = assistTasksStatus?.tasks ?? [], fields = (assistDocument?.fields ?? []).map((assistField) => ({
492
+ ...assistField,
493
+ tasks: tasks.filter((task) => task.path === assistField.path),
494
+ instructions: assistField.instructions?.filter((p) => !p.userId || p.userId === currentUser?.id).map((instruction2) => asStudioInstruction(instruction2, tasks))
495
+ }));
522
496
  return sanity.typed({
523
497
  ...assistDocument,
524
- tasks: tasks == null ? void 0 : tasks.map((task) => {
525
- var _a2, _b2;
526
- const instruction2 = (_b2 = (_a2 = fields.find((f) => f.path === task.path)) == null ? void 0 : _a2.instructions) == null ? void 0 : _b2.find((i) => i._key === task.instructionKey);
498
+ tasks: tasks?.map((task) => {
499
+ const instruction2 = fields.find((f) => f.path === task.path)?.instructions?.find((i) => i._key === task.instructionKey);
527
500
  return {
528
501
  ...task,
529
502
  instruction: instruction2
@@ -548,12 +521,11 @@ function getPathKey(path) {
548
521
  return path.length ? Array.isArray(path) ? sanity.pathToString(path) : path : documentRootKey;
549
522
  }
550
523
  function getInstructionTitle(instruction2) {
551
- var _a;
552
- return (_a = instruction2 == null ? void 0 : instruction2.title) != null ? _a : "Untitled";
524
+ return instruction2?.title ?? "Untitled";
553
525
  }
554
526
  const basePath = "/assist/tasks/instruction";
555
527
  function canUseAssist(status) {
556
- return (status == null ? void 0 : status.enabled) && status.initialized && status.validToken;
528
+ return status?.enabled && status.initialized && status.validToken;
557
529
  }
558
530
  function useApiClient(customApiClient) {
559
531
  const client = sanity.useClient({ apiVersion: "2023-06-05" });
@@ -580,7 +552,7 @@ function useTranslate(apiClient) {
580
552
  fieldLanguageMap,
581
553
  conditionalMembers,
582
554
  translatePath: translatePath.length === 0 ? documentRootKey : sanity.pathToString(translatePath),
583
- userId: user == null ? void 0 : user.id
555
+ userId: user?.id
584
556
  }
585
557
  }).catch((e) => {
586
558
  throw toast.push({
@@ -612,7 +584,7 @@ function useGenerateCaption(apiClient) {
612
584
  path,
613
585
  documentId,
614
586
  types,
615
- userId: user == null ? void 0 : user.id
587
+ userId: user?.id
616
588
  }
617
589
  }).catch((e) => {
618
590
  throw toast.push({
@@ -644,7 +616,7 @@ function useGenerateImage(apiClient) {
644
616
  path,
645
617
  documentId,
646
618
  types,
647
- userId: user == null ? void 0 : user.id
619
+ userId: user?.id
648
620
  }
649
621
  }).catch((e) => {
650
622
  throw toast.push({
@@ -705,7 +677,7 @@ function useRunInstructionApi(apiClient) {
705
677
  body: {
706
678
  ...request,
707
679
  types,
708
- userId: user == null ? void 0 : user.id
680
+ userId: user?.id
709
681
  }
710
682
  }).catch((e) => {
711
683
  throw toast.push({
@@ -734,8 +706,7 @@ function useAiAssistanceConfig() {
734
706
  return context;
735
707
  }
736
708
  function AiAssistanceConfigProvider(props) {
737
- var _a;
738
- const [status, setStatus] = react.useState(), [error, setError] = react.useState(), apiClient = useApiClient((_a = props.config) == null ? void 0 : _a.__customApiClient), { getInstructStatus, loading: statusLoading } = useGetInstructStatus(apiClient), { initInstruct, loading: initLoading } = useInitInstruct(apiClient);
709
+ const [status, setStatus] = react.useState(), [error, setError] = react.useState(), apiClient = useApiClient(props.config?.__customApiClient), { getInstructStatus, loading: statusLoading } = useGetInstructStatus(apiClient), { initInstruct, loading: initLoading } = useInitInstruct(apiClient);
739
710
  react.useEffect(() => {
740
711
  getInstructStatus().then((s) => setStatus(s)).catch((e) => {
741
712
  console.error(e), setError(e);
@@ -772,16 +743,14 @@ function isUserInputBlock(block) {
772
743
  return block._type === userInputTypeName;
773
744
  }
774
745
  function RunInstructionProvider(props) {
775
- var _a;
776
- const { config } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { runInstruction: runInstructionRequest, loading } = useRunInstructionApi(apiClient), id = react.useId(), [inputs, setInputs] = react.useState(NO_INPUT), [runRequest, setRunRequest] = react.useState(), runInstruction = react.useCallback(
746
+ const { config } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { runInstruction: runInstructionRequest, loading } = useRunInstructionApi(apiClient), id = react.useId(), [inputs, setInputs] = react.useState(NO_INPUT), [runRequest, setRunRequest] = react.useState(), runInstruction = react.useCallback(
777
747
  (req) => {
778
- var _a2;
779
748
  if (loading)
780
749
  return;
781
- const { instruction: instruction2, ...request } = req, instructionKey = instruction2._key, userInputBlocks = (_a2 = instruction2 == null ? void 0 : instruction2.prompt) == null ? void 0 : _a2.flatMap(
750
+ const { instruction: instruction2, ...request } = req, instructionKey = instruction2._key, userInputBlocks = instruction2?.prompt?.flatMap(
782
751
  (block) => block._type === "block" ? block.children.filter(isUserInputBlock) : [block]
783
752
  ).filter(isUserInputBlock);
784
- if (!(userInputBlocks != null && userInputBlocks.length)) {
753
+ if (!userInputBlocks?.length) {
785
754
  runInstructionRequest({
786
755
  ...request,
787
756
  instructionKey,
@@ -811,11 +780,8 @@ function RunInstructionProvider(props) {
811
780
  }
812
781
  close();
813
782
  }, [close, runInstructionRequest, runRequest, inputs]), open = !!runRequest, runDisabled = react.useMemo(
814
- () => {
815
- var _a2, _b;
816
- return ((_b = (_a2 = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a2.length) != null ? _b : 0) > Object.entries(inputs).filter(([, value]) => !!value).length;
817
- },
818
- [runRequest == null ? void 0 : runRequest.userInputBlocks, inputs]
783
+ () => (runRequest?.userInputBlocks?.length ?? 0) > Object.entries(inputs).filter(([, value]) => !!value).length,
784
+ [runRequest?.userInputBlocks, inputs]
819
785
  ), runButton = /* @__PURE__ */ jsxRuntime.jsx(
820
786
  ui.Button,
821
787
  {
@@ -838,7 +804,7 @@ function RunInstructionProvider(props) {
838
804
  open,
839
805
  onClose: close,
840
806
  width: 1,
841
- header: getInstructionTitle(runRequest == null ? void 0 : runRequest.instruction),
807
+ header: getInstructionTitle(runRequest?.instruction),
842
808
  footer: /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { justify: "space-between", padding: 2, flex: 1, children: runDisabled ? /* @__PURE__ */ jsxRuntime.jsx(
843
809
  ui.Tooltip,
844
810
  {
@@ -847,7 +813,7 @@ function RunInstructionProvider(props) {
847
813
  children: /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { flex: 1, children: runButton })
848
814
  }
849
815
  ) : runButton }),
850
- children: /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { padding: 4, space: 2, children: (_a = runRequest == null ? void 0 : runRequest.userInputBlocks) == null ? void 0 : _a.map((block, i) => /* @__PURE__ */ jsxRuntime.jsx(
816
+ children: /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { padding: 4, space: 2, children: runRequest?.userInputBlocks?.map((block, i) => /* @__PURE__ */ jsxRuntime.jsx(
851
817
  UserInput,
852
818
  {
853
819
  block,
@@ -863,29 +829,22 @@ function RunInstructionProvider(props) {
863
829
  ] });
864
830
  }
865
831
  function UserInput(props) {
866
- var _a;
867
832
  const { block, autoFocus, setInputs, inputs } = props, key = block._key, textAreaRef = react.useRef(null), onChange = react.useCallback(
868
833
  (e) => {
869
- setInputs((current) => {
870
- var _a2;
871
- return {
872
- ...current,
873
- [key]: ((_a2 = e.currentTarget) != null ? _a2 : e.target).value
874
- };
875
- });
834
+ setInputs((current) => ({
835
+ ...current,
836
+ [key]: (e.currentTarget ?? e.target).value
837
+ }));
876
838
  },
877
839
  [key, setInputs]
878
840
  ), value = react.useMemo(() => inputs[key], [inputs, key]);
879
841
  return react.useEffect(() => {
880
- autoFocus && setTimeout(() => {
881
- var _a2;
882
- return (_a2 = textAreaRef.current) == null ? void 0 : _a2.focus();
883
- }, 0);
842
+ autoFocus && setTimeout(() => textAreaRef.current?.focus(), 0);
884
843
  }, [autoFocus]), /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { padding: 2, space: 3, children: [
885
844
  /* @__PURE__ */ jsxRuntime.jsx(
886
845
  sanity.FormFieldHeaderText,
887
846
  {
888
- title: (_a = block == null ? void 0 : block.message) != null ? _a : "Provide more context",
847
+ title: block?.message ?? "Provide more context",
889
848
  description: block.description
890
849
  }
891
850
  ),
@@ -904,10 +863,6 @@ function UserInput(props) {
904
863
  function isDocAssistable(documentSchemaType, published, draft) {
905
864
  return !!(documentSchemaType.liveEdit ? published : draft);
906
865
  }
907
- function getAssistableDocId(documentSchemaType, documentId) {
908
- const baseId = publicId(documentId);
909
- return documentSchemaType.liveEdit ? baseId : `drafts.${baseId}`;
910
- }
911
866
  function useRequestRunInstruction(args) {
912
867
  const { runInstruction, instructionLoading } = useRunInstruction(), requestRunInstruction = useDraftDelayedTask({
913
868
  ...args,
@@ -952,7 +907,6 @@ function conditionalState(memberState) {
952
907
  }
953
908
  function extractConditionalPaths(node, maxDepth2) {
954
909
  return node.path.length >= maxDepth2 ? [] : node.members.reduce((acc, member) => {
955
- var _a, _b;
956
910
  if (member.kind === "error")
957
911
  return acc;
958
912
  if (member.kind === "field") {
@@ -977,12 +931,12 @@ function extractConditionalPaths(node, maxDepth2) {
977
931
  }
978
932
  return [...acc, conditionalState(member.field)];
979
933
  } else if (member.kind === "fieldSet") {
980
- const conditionalFieldset = !!((_b = (_a = node.schemaType) == null ? void 0 : _a.fieldsets) != null && _b.some(
934
+ const conditionalFieldset = !!node.schemaType?.fieldsets?.some(
981
935
  (f) => !f.single && f.name === member.fieldSet.name && typeof f.hidden == "function"
982
- )), innerFields = extractConditionalPaths(member.fieldSet, maxDepth2).map((f) => ({
936
+ ), innerFields = extractConditionalPaths(member.fieldSet, maxDepth2).map((f) => ({
983
937
  ...f,
984
938
  // if fieldset is conditional, visible fields must also be considered conditional
985
- conditional: conditionalFieldset != null ? conditionalFieldset : f.conditional
939
+ conditional: conditionalFieldset ?? f.conditional
986
940
  }));
987
941
  return [...acc, ...innerFields];
988
942
  }
@@ -1039,19 +993,17 @@ const SelectedFieldContext = react.createContext(void 0), SelectedFieldContextPr
1039
993
  function getTypeIcon(schemaType) {
1040
994
  let t = schemaType;
1041
995
  for (; t; ) {
1042
- if (t.icon)
1043
- return t.icon;
996
+ if (t.icon) return t.icon;
1044
997
  t = t.type;
1045
998
  }
1046
999
  return isType(schemaType, "slug") ? icons.LinkIcon : isType(schemaType, "image") ? icons.ImageIcon : schemaType.jsonType === "array" && isPortableTextArray(schemaType) ? icons.BlockContentIcon : schemaType.jsonType === "array" ? icons.OlistIcon : schemaType.jsonType === "object" ? icons.BlockquoteIcon : schemaType.jsonType === "string" ? icons.StringIcon : icons.DocumentIcon;
1047
1000
  }
1048
1001
  function getFieldRefsWithDocument(schemaType) {
1049
- var _a;
1050
1002
  const fields = getFieldRefs(schemaType);
1051
1003
  return [
1052
1004
  {
1053
1005
  key: documentRootKey,
1054
- icon: (_a = schemaType.icon) != null ? _a : icons.DocumentIcon,
1006
+ icon: schemaType.icon ?? icons.DocumentIcon,
1055
1007
  title: "The entire document",
1056
1008
  path: [],
1057
1009
  schemaType
@@ -1061,8 +1013,7 @@ function getFieldRefsWithDocument(schemaType) {
1061
1013
  }
1062
1014
  function getFieldRefs(schemaType, parent, depth = 0) {
1063
1015
  return depth >= maxDepth ? [] : schemaType.fields.filter((f) => !f.name.startsWith("_")).flatMap((field) => {
1064
- var _a;
1065
- const path = parent ? [...parent.path, field.name] : [field.name], title = (_a = field.type.title) != null ? _a : field.name, fieldRef = {
1016
+ const path = parent ? [...parent.path, field.name] : [field.name], title = field.type.title ?? field.name, fieldRef = {
1066
1017
  key: patchableKey(sanity.pathToString(path)),
1067
1018
  path,
1068
1019
  title: parent ? [parent.title, title].join(" / ") : title,
@@ -1074,11 +1025,10 @@ function getFieldRefs(schemaType, parent, depth = 0) {
1074
1025
  }
1075
1026
  function getSyntheticFields(schemaType, parent, depth = 0) {
1076
1027
  return depth >= maxDepth ? [] : schemaType.of.filter((itemType) => !isType(itemType, "block")).flatMap((itemType) => {
1077
- var _a;
1078
- const segment = { _key: itemType.name }, title = (_a = itemType.title) != null ? _a : itemType.name, path = parent ? [...parent.path, segment] : [segment], fieldRef = {
1028
+ const segment = { _key: itemType.name }, title = itemType.title ?? itemType.name, path = [...parent.path, segment], fieldRef = {
1079
1029
  key: patchableKey(sanity.pathToString(path)),
1080
1030
  path,
1081
- title: parent ? [parent.title, title].join(" / ") : title,
1031
+ title: [parent.title, title].join(" / "),
1082
1032
  schemaType: itemType,
1083
1033
  icon: getTypeIcon(itemType),
1084
1034
  synthetic: !0
@@ -1093,7 +1043,7 @@ function getTypePath(doc, pathString) {
1093
1043
  let valid = !0;
1094
1044
  const syntheticPath = path.map((segment) => {
1095
1045
  if (currentPath.push(segment), sanity.isKeySegment(segment)) {
1096
- const match = mutator.extractWithPath(sanity.pathToString(currentPath), doc)[0], value = match == null ? void 0 : match.value;
1046
+ const match = mutator.extractWithPath(sanity.pathToString(currentPath), doc)[0], value = match?.value;
1097
1047
  if (match && value && typeof value == "object" && "_type" in value)
1098
1048
  return { _key: value._type };
1099
1049
  valid = !1;
@@ -1113,20 +1063,16 @@ function useSelectedField(documentSchemaType, path) {
1113
1063
  () => documentSchemaType && sanity.isObjectSchemaType(documentSchemaType) ? getFieldRefsWithDocument(documentSchemaType) : [],
1114
1064
  [documentSchemaType]
1115
1065
  );
1116
- return react.useMemo(() => path ? selectableFields == null ? void 0 : selectableFields.find((f) => f.key === path) : void 0, [selectableFields, path]);
1066
+ return react.useMemo(() => path ? selectableFields?.find((f) => f.key === path) : void 0, [selectableFields, path]);
1117
1067
  }
1118
1068
  function getFieldTitle(field) {
1119
- var _a, _b, _c;
1120
- const schemaType = field == null ? void 0 : field.schemaType;
1121
- return (_c = (_b = (_a = field == null ? void 0 : field.title) != null ? _a : schemaType == null ? void 0 : schemaType.title) != null ? _b : schemaType == null ? void 0 : schemaType.name) != null ? _c : "Untitled";
1069
+ const schemaType = field?.schemaType;
1070
+ return field?.title ?? schemaType?.title ?? schemaType?.name ?? "Untitled";
1122
1071
  }
1123
1072
  function useAiPaneRouter() {
1124
1073
  const paneRouter = structure.usePaneRouter();
1125
1074
  return react.useMemo(
1126
- () => {
1127
- var _a;
1128
- return { ...paneRouter, params: (_a = paneRouter.params) != null ? _a : {} };
1129
- },
1075
+ () => ({ ...paneRouter, params: paneRouter.params ?? {} }),
1130
1076
  [paneRouter]
1131
1077
  );
1132
1078
  }
@@ -1143,13 +1089,9 @@ function FieldAutocomplete(props) {
1143
1089
  /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: react.createElement(field.icon) }),
1144
1090
  /* @__PURE__ */ jsxRuntime.jsx(FieldTitle, { field })
1145
1091
  ] }) }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { as: "button", padding: 3, radius: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { accent: !0, size: 1, children: option.value }) });
1146
- }, []), renderValue = react.useCallback((value, option) => {
1147
- var _a;
1148
- return (_a = option == null ? void 0 : option.field.title) != null ? _a : value;
1149
- }, []), filterOption = react.useCallback((query, option) => {
1150
- var _a, _b, _c;
1092
+ }, []), renderValue = react.useCallback((value, option) => option?.field.title ?? value, []), filterOption = react.useCallback((query, option) => {
1151
1093
  const lQuery = query.toLowerCase();
1152
- return ((_a = option == null ? void 0 : option.value) == null ? void 0 : _a.toLowerCase().includes(lQuery)) || ((_c = (_b = option == null ? void 0 : option.field) == null ? void 0 : _b.title) == null ? void 0 : _c.toLowerCase().includes(lQuery));
1094
+ return option?.value?.toLowerCase().includes(lQuery) || option?.field?.title?.toLowerCase().includes(lQuery);
1153
1095
  }, []);
1154
1096
  return /* @__PURE__ */ jsxRuntime.jsx(
1155
1097
  ui.Autocomplete,
@@ -1164,7 +1106,7 @@ function FieldAutocomplete(props) {
1164
1106
  radius: 2,
1165
1107
  renderOption,
1166
1108
  renderValue,
1167
- value: currentField == null ? void 0 : currentField.key,
1109
+ value: currentField?.key,
1168
1110
  filterOption
1169
1111
  }
1170
1112
  );
@@ -1251,22 +1193,17 @@ function InstructionTaskHistoryButton(props) {
1251
1193
  },
1252
1194
  [client, documentId]
1253
1195
  ), titledTasks = react.useMemo(() => {
1254
- var _a;
1255
- const t = (_a = tasks == null ? void 0 : tasks.filter(
1196
+ const t = tasks?.filter(
1256
1197
  (task) => task.started && (/* @__PURE__ */ new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs
1257
1198
  ).map((task) => {
1258
- var _a2;
1259
- const instruction2 = instructions == null ? void 0 : instructions.find((i) => i._key === task.instructionKey);
1199
+ const instruction2 = instructions?.find((i) => i._key === task.instructionKey);
1260
1200
  return {
1261
1201
  ...task,
1262
- title: showTitles ? (_a2 = task.title) != null ? _a2 : getInstructionTitle(instruction2) : void 0,
1202
+ title: showTitles ? task.title ?? getInstructionTitle(instruction2) : void 0,
1263
1203
  cancel: () => cancelRun(task._key)
1264
1204
  };
1265
- })) != null ? _a : [];
1266
- return t.sort((a, b) => {
1267
- var _a2, _b;
1268
- return new Date((_a2 = b.started) != null ? _a2 : "").getTime() - new Date((_b = a.started) != null ? _b : "").getTime();
1269
- }), t;
1205
+ }) ?? [];
1206
+ return t.sort((a, b) => new Date(b.started ?? "").getTime() - new Date(a.started ?? "").getTime()), t;
1270
1207
  }, [tasks, instructions, cancelRun, showTitles]), isRunning = react.useMemo(() => titledTasks.some((r) => !r.ended), [titledTasks]), hasErrors = react.useMemo(
1271
1208
  () => titledTasks.some((r) => r.reason === "error" || r.reason === "timeout"),
1272
1209
  [titledTasks]
@@ -1275,14 +1212,14 @@ function InstructionTaskHistoryButton(props) {
1275
1212
  }, []);
1276
1213
  ui.useClickOutside(handleClickOutside, [button, popover]);
1277
1214
  const handleEscape = react.useCallback(() => {
1278
- setOpen(!1), button == null || button.focus();
1215
+ setOpen(!1), button?.focus();
1279
1216
  }, [button]);
1280
1217
  return /* @__PURE__ */ jsxRuntime.jsx(
1281
1218
  ui.Popover,
1282
1219
  {
1283
1220
  constrainSize: !0,
1284
1221
  content: /* @__PURE__ */ jsxRuntime.jsx(TaskList, { onEscape: handleEscape, tasks: titledTasks }),
1285
- open: open && !!(titledTasks != null && titledTasks.length),
1222
+ open: open && !!titledTasks?.length,
1286
1223
  placement: "top",
1287
1224
  portal: !0,
1288
1225
  ref: setPopover,
@@ -1290,7 +1227,7 @@ function InstructionTaskHistoryButton(props) {
1290
1227
  children: /* @__PURE__ */ jsxRuntime.jsx(
1291
1228
  TaskStatusButton,
1292
1229
  {
1293
- disabled: !(titledTasks != null && titledTasks.length),
1230
+ disabled: !titledTasks?.length,
1294
1231
  hasErrors,
1295
1232
  isRunning,
1296
1233
  onClick: toggleOpen,
@@ -1333,9 +1270,8 @@ function TaskList(props) {
1333
1270
  ), /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { padding: 1, space: 1, children: tasks.map((task) => /* @__PURE__ */ jsxRuntime.jsx(TaskItem, { task }, task._key)) });
1334
1271
  }
1335
1272
  function TaskItem(props) {
1336
- var _a;
1337
1273
  const { task } = props, taskType = task.reason && TASK_CONFIG[task.reason];
1338
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { radius: 2, tone: taskType && (taskType == null ? void 0 : taskType.tone), children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { align: "center", gap: 1, children: [
1274
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { radius: 2, tone: taskType && taskType?.tone, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { align: "center", gap: 1, children: [
1339
1275
  /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { align: "flex-start", flex: 1, gap: 3, padding: 3, children: [
1340
1276
  /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: "none", children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, children: [
1341
1277
  taskType && react.createElement(taskType.icon),
@@ -1350,12 +1286,21 @@ function TaskItem(props) {
1350
1286
  ] })
1351
1287
  ] }),
1352
1288
  task.message ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: task.message }) : null,
1353
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: /* @__PURE__ */ jsxRuntime.jsx(TimeAgo, { date: (_a = task.ended) != null ? _a : task.started }) })
1289
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: /* @__PURE__ */ jsxRuntime.jsx(TimeAgo, { date: task.ended ?? task.started }) })
1354
1290
  ] })
1355
1291
  ] }),
1356
1292
  !task.ended && /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: "none", padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { fontSize: 1, mode: "bleed", onClick: task.cancel, text: "Cancel" }) })
1357
1293
  ] }) });
1358
1294
  }
1295
+ const AssistDocumentContext = react.createContext(
1296
+ void 0
1297
+ );
1298
+ function useAssistDocumentContext() {
1299
+ const context = react.useContext(AssistDocumentContext);
1300
+ if (!context)
1301
+ throw new Error("AssistDocumentContext value is missing");
1302
+ return context;
1303
+ }
1359
1304
  const CardWithShadowBelow = styledComponents.styled(ui.Card)`
1360
1305
  position: relative;
1361
1306
 
@@ -1397,7 +1342,7 @@ function AssistInspectorWrapper(props) {
1397
1342
  ] })
1398
1343
  ] }) });
1399
1344
  const status = context.status;
1400
- return status != null && status.enabled ? !(status != null && status.initialized) || !status.validToken ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { direction: "column", height: "fill", children: [
1345
+ return status?.enabled ? !status?.initialized || !status.validToken ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { direction: "column", height: "fill", children: [
1401
1346
  /* @__PURE__ */ jsxRuntime.jsx(
1402
1347
  structure.DocumentInspectorHeader,
1403
1348
  {
@@ -1411,16 +1356,16 @@ function AssistInspectorWrapper(props) {
1411
1356
  "Failed to start ",
1412
1357
  pluginTitle
1413
1358
  ] }) : null,
1414
- !context.error && !(status != null && status.initialized) ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, weight: "semibold", children: [
1359
+ !context.error && !status?.initialized ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, weight: "semibold", children: [
1415
1360
  pluginTitle,
1416
1361
  " is not enabled"
1417
1362
  ] }) : null,
1418
- !context.error && status != null && status.initialized && !status.validToken ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1363
+ !context.error && status?.initialized && !status.validToken ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1419
1364
  /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, weight: "semibold", children: "Invalid token" }),
1420
1365
  /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "The token used by the AI Assistant is not valid and has to be regenerated." })
1421
1366
  ] }) : null,
1422
1367
  context.error && /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: !0, size: 1, children: "Something went wrong. See console for details." }),
1423
- !context.error && !(status != null && status.initialized) && /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, muted: !0, children: [
1368
+ !context.error && !status?.initialized && /* @__PURE__ */ jsxRuntime.jsxs(ui.Text, { size: 1, muted: !0, children: [
1424
1369
  "Please enable ",
1425
1370
  pluginTitle,
1426
1371
  "."
@@ -1430,7 +1375,7 @@ function AssistInspectorWrapper(props) {
1430
1375
  {
1431
1376
  fontSize: 1,
1432
1377
  icon: context.initLoading ? /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { marginTop: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, {}) }) : context.error ? icons.RetryIcon : void 0,
1433
- text: context.error ? "Retry" : status != null && status.initialized && !status.validToken ? `Restore ${pluginTitle}` : `Enable ${pluginTitle} now`,
1378
+ text: context.error ? "Retry" : status?.initialized && !status.validToken ? `Restore ${pluginTitle}` : `Enable ${pluginTitle} now`,
1434
1379
  tone: "primary",
1435
1380
  onClick: context.init,
1436
1381
  disabled: context.initLoading
@@ -1466,40 +1411,29 @@ function AssistInspectorWrapper(props) {
1466
1411
  ] });
1467
1412
  }
1468
1413
  function AssistInspector(props) {
1469
- var _a, _b;
1470
- const { params } = useAiPaneRouter(), boundary = react.useRef(null), pathKey = params == null ? void 0 : params[fieldPathParam], instructionKey = params == null ? void 0 : params[instructionParam], documentPane = structure.useDocumentPane(), {
1414
+ const { params } = useAiPaneRouter(), boundary = react.useRef(null), pathKey = params?.[fieldPathParam], instructionKey = params?.[instructionParam], documentPane = structure.useDocumentPane(), {
1471
1415
  documentId,
1472
1416
  documentType,
1473
1417
  value: docValue,
1474
1418
  schemaType,
1475
1419
  onChange: documentOnChange,
1476
1420
  formState
1477
- } = documentPane, { published, draft } = sanity.useEditState(documentId, documentType, "low"), formStateRef = react.useRef(formState);
1421
+ } = documentPane, { assistableDocumentId, documentIsAssistable } = useAssistDocumentContext(), formStateRef = react.useRef(formState);
1478
1422
  formStateRef.current = formState;
1479
- const assistableDocId = getAssistableDocId(schemaType, documentId), { instructionLoading, requestRunInstruction } = useRequestRunInstruction({
1423
+ const { instructionLoading, requestRunInstruction } = useRequestRunInstruction({
1480
1424
  documentOnChange,
1481
- isDocAssistable: isDocAssistable(schemaType, published, draft)
1482
- }), typePath = useTypePath(docValue, pathKey != null ? pathKey : ""), selectedField = useSelectedField(schemaType, typePath), aiDocId = assistDocumentId(documentType), assistDocument = useStudioAssistDocument({ documentId, schemaType, initDoc: !0 }), assistField = (_a = assistDocument == null ? void 0 : assistDocument.fields) == null ? void 0 : _a.find((f) => f.path === typePath), instruction2 = (_b = assistField == null ? void 0 : assistField.instructions) == null ? void 0 : _b.find((i) => i._key === instructionKey), tasks = react.useMemo(
1483
- () => {
1484
- var _a2;
1485
- return (_a2 = assistDocument == null ? void 0 : assistDocument.tasks) == null ? void 0 : _a2.filter((i) => !instructionKey || i.instructionKey === instructionKey);
1486
- },
1487
- [assistDocument == null ? void 0 : assistDocument.tasks, instructionKey]
1425
+ isDocAssistable: documentIsAssistable
1426
+ }), typePath = useTypePath(docValue, pathKey ?? ""), selectedField = useSelectedField(schemaType, typePath), aiDocId = assistDocumentId(documentType), assistDocument = useStudioAssistDocument({ documentId, schemaType, initDoc: !0 }), instruction2 = assistDocument?.fields?.find((f) => f.path === typePath)?.instructions?.find((i) => i._key === instructionKey), tasks = react.useMemo(
1427
+ () => assistDocument?.tasks?.filter((i) => !instructionKey || i.instructionKey === instructionKey),
1428
+ [assistDocument?.tasks, instructionKey]
1488
1429
  ), instructions = react.useMemo(
1489
- () => {
1490
- var _a2;
1491
- return (_a2 = assistDocument == null ? void 0 : assistDocument.fields) == null ? void 0 : _a2.flatMap((f) => {
1492
- var _a3;
1493
- return (_a3 = f.instructions) != null ? _a3 : [];
1494
- });
1495
- },
1496
- [assistDocument == null ? void 0 : assistDocument.fields]
1497
- ), promptValue = instruction2 == null ? void 0 : instruction2.prompt, isEmptyPrompt = react.useMemo(() => {
1498
- var _a2, _b2;
1499
- if (!(promptValue != null && promptValue.length))
1430
+ () => assistDocument?.fields?.flatMap((f) => f.instructions ?? []),
1431
+ [assistDocument?.fields]
1432
+ ), promptValue = instruction2?.prompt, isEmptyPrompt = react.useMemo(() => {
1433
+ if (!promptValue?.length)
1500
1434
  return !0;
1501
- const firstBlock = promptValue[0], children = firstBlock == null ? void 0 : firstBlock.children;
1502
- return promptValue.length == 1 && (children == null ? void 0 : children.length) === 1 && !((_b2 = (_a2 = children == null ? void 0 : children[0]) == null ? void 0 : _a2.text) != null && _b2.length);
1435
+ const children = promptValue[0]?.children;
1436
+ return promptValue.length == 1 && children?.length === 1 && !children?.[0]?.text?.length;
1503
1437
  }, [promptValue]), paneNode = react.useMemo(
1504
1438
  () => ({
1505
1439
  type: "document",
@@ -1513,14 +1447,14 @@ function AssistInspector(props) {
1513
1447
  [aiDocId]
1514
1448
  ), runCurrentInstruction = react.useCallback(
1515
1449
  () => instruction2 && pathKey && typePath && requestRunInstruction({
1516
- documentId: assistableDocId,
1450
+ documentId: assistableDocumentId,
1517
1451
  path: pathKey,
1518
1452
  typePath,
1519
1453
  assistDocumentId: assistDocumentId(documentType),
1520
1454
  instruction: instruction2,
1521
1455
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
1522
1456
  }),
1523
- [pathKey, instruction2, typePath, documentType, assistableDocId, requestRunInstruction]
1457
+ [pathKey, instruction2, typePath, documentType, assistableDocumentId, requestRunInstruction]
1524
1458
  ), Region = react.useCallback((_props) => /* @__PURE__ */ jsxRuntime.jsx("div", { ..._props, style: { height: "100%", flex: 1, overflow: "auto" } }), []), assistTypeContext = react.useMemo(() => ({ typePath, documentType }), [typePath, documentType]);
1525
1459
  return !documentId || !schemaType || schemaType.jsonType !== "object" ? /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { flex: 1, padding: 4, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: "Document not ready yet." }) }) : /* @__PURE__ */ jsxRuntime.jsxs(
1526
1460
  ui.Flex,
@@ -1553,6 +1487,11 @@ function AssistInspector(props) {
1553
1487
  index: documentPane.index,
1554
1488
  itemId: "ai",
1555
1489
  pane: paneNode,
1490
+ forcedVersion: {
1491
+ isReleaseLocked: !1,
1492
+ selectedPerspectiveName: "published",
1493
+ selectedReleaseId: void 0
1494
+ },
1556
1495
  children: /* @__PURE__ */ jsxRuntime.jsx(DocumentForm, {})
1557
1496
  }
1558
1497
  )
@@ -1577,7 +1516,7 @@ function AssistInspector(props) {
1577
1516
  ] }) })
1578
1517
  ] }) }),
1579
1518
  /* @__PURE__ */ jsxRuntime.jsx(CardWithShadowAbove, { flex: "none", paddingX: 4, paddingY: 3, style: { justifySelf: "flex-end" }, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 2, flex: 1, justify: "flex-end", children: [
1580
- (schemaType == null ? void 0 : schemaType.name) && pathKey && instructionKey && /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(
1519
+ schemaType?.name && pathKey && instructionKey && /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(
1581
1520
  ui.Button,
1582
1521
  {
1583
1522
  mode: "ghost",
@@ -1592,7 +1531,7 @@ function AssistInspector(props) {
1592
1531
  /* @__PURE__ */ jsxRuntime.jsx(
1593
1532
  InstructionTaskHistoryButton,
1594
1533
  {
1595
- documentId: assistableDocId,
1534
+ documentId: assistableDocumentId,
1596
1535
  tasks,
1597
1536
  instructions,
1598
1537
  showTitles: !instructionKey
@@ -1690,7 +1629,7 @@ function FirstAssistedPathProvider(props) {
1690
1629
  const firstAssisted = members.find(
1691
1630
  (member) => member.kind === "field" && isAssistSupported(member.field.schemaType)
1692
1631
  );
1693
- return firstAssisted != null && firstAssisted.field.path ? sanity.pathToString(firstAssisted == null ? void 0 : firstAssisted.field.path) : void 0;
1632
+ return firstAssisted?.field.path ? sanity.pathToString(firstAssisted?.field.path) : void 0;
1694
1633
  }, [members]);
1695
1634
  return /* @__PURE__ */ jsxRuntime.jsx(FirstAssistedPathContext.Provider, { value: firstAssistedPath, children: props.children });
1696
1635
  }
@@ -1838,24 +1777,11 @@ function AiFieldPresence(props) {
1838
1777
  }
1839
1778
  ) });
1840
1779
  }
1841
- const AssistDocumentContext = react.createContext(
1842
- void 0
1843
- );
1844
- function useAssistDocumentContext() {
1845
- const context = react.useContext(AssistDocumentContext);
1846
- if (!context)
1847
- throw new Error("AssistDocumentContext value is missing");
1848
- return context;
1849
- }
1850
1780
  const NO_PRESENCE = [];
1851
1781
  function useAssistPresence(path, showFocusWithin) {
1852
- const context = useAssistDocumentContext(), assistDocument = context && "assistDocument" in context ? context.assistDocument : void 0, tasks = assistDocument == null ? void 0 : assistDocument.tasks;
1782
+ const context = useAssistDocumentContext(), tasks = (context && "assistDocument" in context ? context.assistDocument : void 0)?.tasks;
1853
1783
  return react.useMemo(() => {
1854
- var _a, _b;
1855
- const activePresence = (_b = (_a = tasks == null ? void 0 : tasks.filter((task) => !task.ended)) == null ? void 0 : _a.flatMap((task) => {
1856
- var _a2;
1857
- return (_a2 = task.presence) != null ? _a2 : [];
1858
- })) == null ? void 0 : _b.filter(
1784
+ const activePresence = tasks?.filter((task) => !task.ended)?.flatMap((task) => task.presence ?? [])?.filter(
1859
1785
  (p) => p.started && (/* @__PURE__ */ new Date()).getTime() - new Date(p.started).getTime() < maxHistoryVisibilityMs
1860
1786
  ).filter((presence) => {
1861
1787
  if (!presence.path || !path.length)
@@ -1866,11 +1792,10 @@ function useAssistPresence(path, showFocusWithin) {
1866
1792
  return typeof pathSegment == "string" ? pathSegment === statusSegment : sanity.isKeySegment(pathSegment) && sanity.isKeySegment(statusSegment) ? pathSegment._key === statusSegment._key : !1;
1867
1793
  });
1868
1794
  });
1869
- return activePresence != null && activePresence.length ? activePresence.map((status) => aiPresence(status, path)) : NO_PRESENCE;
1795
+ return activePresence?.length ? activePresence.map((status) => aiPresence(status, path)) : NO_PRESENCE;
1870
1796
  }, [showFocusWithin, tasks, path]);
1871
1797
  }
1872
1798
  function aiPresence(presence, path, title) {
1873
- var _a;
1874
1799
  return {
1875
1800
  user: {
1876
1801
  id: `sanity-assistant_${presence._key}`,
@@ -1878,7 +1803,7 @@ function aiPresence(presence, path, title) {
1878
1803
  },
1879
1804
  path,
1880
1805
  sessionId: "not-available",
1881
- lastActiveAt: (_a = presence == null ? void 0 : presence.started) != null ? _a : (/* @__PURE__ */ new Date()).toISOString()
1806
+ lastActiveAt: presence?.started ?? (/* @__PURE__ */ new Date()).toISOString()
1882
1807
  };
1883
1808
  }
1884
1809
  function AssistFieldWrapper(props) {
@@ -1913,14 +1838,13 @@ function useRegionRects() {
1913
1838
  const ref = react.useRef(null), [relativeBoundsRect, setRelativeBoundsRect] = react.useState(null), [relativeElementRect, setRelativeElementRect] = react.useState(null), [boundsScroll, setBoundsScroll] = react.useState({ x: 0, y: 0 }), [scroll, setScroll] = react.useState({ x: 0, y: 0 }), boundsScrollXRef = react.useRef(0), boundsScrollYRef = react.useRef(0), elementScrollXRef = react.useRef(0), elementScrollYRef = react.useRef(0);
1914
1839
  react.useEffect(() => {
1915
1840
  const el = ref.current;
1916
- if (!el)
1917
- return;
1841
+ if (!el) return;
1918
1842
  const scrollParents = [];
1919
1843
  let parent = el.parentElement;
1920
1844
  for (; parent && parent !== document.body; )
1921
1845
  hasOverflowScroll(parent) && scrollParents.push(parent), parent = parent.parentElement;
1922
1846
  function handleResize() {
1923
- const scrollParent = scrollParents[0], boundsRect = (scrollParent == null ? void 0 : scrollParent.getBoundingClientRect()) || {
1847
+ const boundsRect = scrollParents[0]?.getBoundingClientRect() || {
1924
1848
  x: 0,
1925
1849
  y: 0,
1926
1850
  width: window.innerWidth,
@@ -1943,7 +1867,7 @@ function useRegionRects() {
1943
1867
  for (const scrollParent2 of scrollParents)
1944
1868
  scrollX += scrollParent2.scrollLeft, scrollY += scrollParent2.scrollTop;
1945
1869
  const scrollParent = scrollParents[0];
1946
- boundsScrollXRef.current = scrollX - ((scrollParent == null ? void 0 : scrollParent.scrollLeft) || window.scrollX), boundsScrollYRef.current = scrollY - ((scrollParent == null ? void 0 : scrollParent.scrollTop) || window.scrollY), setBoundsScroll({
1870
+ boundsScrollXRef.current = scrollX - (scrollParent?.scrollLeft || window.scrollX), boundsScrollYRef.current = scrollY - (scrollParent?.scrollTop || window.scrollY), setBoundsScroll({
1947
1871
  x: boundsScrollXRef.current,
1948
1872
  y: boundsScrollYRef.current
1949
1873
  }), elementScrollXRef.current = scrollX, elementScrollYRef.current = scrollY, setScroll({ x: scrollX, y: scrollY });
@@ -1982,7 +1906,7 @@ function useRegionRects() {
1982
1906
  function ConnectorRegion(props) {
1983
1907
  const { children, onRectsChange, ...restProps } = props, { bounds, element, ref } = useRegionRects();
1984
1908
  return react.useEffect(() => {
1985
- onRectsChange == null || onRectsChange(bounds && element ? { bounds, element } : null);
1909
+ onRectsChange?.(bounds && element ? { bounds, element } : null);
1986
1910
  }, [bounds, element, onRectsChange]), /* @__PURE__ */ jsxRuntime.jsx("div", { ...restProps, ref, children });
1987
1911
  }
1988
1912
  const ConnectorsStoreContext = react.createContext(null);
@@ -2283,7 +2207,7 @@ const getLanguageParams = (select, document2) => {
2283
2207
  for (const [key, path] of Object.entries(selection)) {
2284
2208
  let value = get__default.default(document2, path);
2285
2209
  Array.isArray(value) && (value = value.filter(
2286
- (item) => typeof item == "object" ? (item == null ? void 0 : item._type) !== "reference" || "_ref" in item : !0
2210
+ (item) => typeof item == "object" ? item?._type !== "reference" || "_ref" in item : !0
2287
2211
  )), selectedValue[key] = value;
2288
2212
  }
2289
2213
  return selectedValue;
@@ -2306,34 +2230,32 @@ function useFieldTranslation() {
2306
2230
  return react.useContext(FieldTranslationContext);
2307
2231
  }
2308
2232
  function hasValuesToTranslate(fieldLanguageMaps, fromLanguage, basePath2) {
2309
- return fieldLanguageMaps == null ? void 0 : fieldLanguageMaps.some(
2310
- (map) => map.inputLanguageId === (fromLanguage == null ? void 0 : fromLanguage.id) && map.inputPath && sanity.pathToString(map.inputPath).startsWith(sanity.pathToString(basePath2))
2233
+ return fieldLanguageMaps?.some(
2234
+ (map) => map.inputLanguageId === fromLanguage?.id && map.inputPath && sanity.pathToString(map.inputPath).startsWith(sanity.pathToString(basePath2))
2311
2235
  );
2312
2236
  }
2313
2237
  function FieldTranslationProvider(props) {
2314
- var _a, _b, _c;
2315
- const { config: assistConfig } = useAiAssistanceConfig(), apiClient = useApiClient(assistConfig.__customApiClient), config = (_a = assistConfig.translate) == null ? void 0 : _a.field, { translate: runTranslate } = useTranslate(apiClient), [dialogOpen, setDialogOpen] = react.useState(!1), [fieldTranslationParams, setFieldTranslationParams] = react.useState(), [languages, setLanguages] = react.useState(), [fromLanguage, setFromLanguage] = react.useState(void 0), [toLanguages, setToLanguages] = react.useState(void 0), [fieldLanguageMaps, setFieldLanguageMaps] = react.useState(), close = react.useCallback(() => {
2238
+ const { config: assistConfig } = useAiAssistanceConfig(), apiClient = useApiClient(assistConfig.__customApiClient), config = assistConfig.translate?.field, { translate: runTranslate } = useTranslate(apiClient), [dialogOpen, setDialogOpen] = react.useState(!1), [fieldTranslationParams, setFieldTranslationParams] = react.useState(), [languages, setLanguages] = react.useState(), [fromLanguage, setFromLanguage] = react.useState(void 0), [toLanguages, setToLanguages] = react.useState(void 0), [fieldLanguageMaps, setFieldLanguageMaps] = react.useState(), close = react.useCallback(() => {
2316
2239
  setDialogOpen(!1), setLanguages(void 0), setFieldTranslationParams(void 0);
2317
- }, []), languageClient = sanity.useClient({ apiVersion: (_b = config == null ? void 0 : config.apiVersion) != null ? _b : "2022-11-27" }), documentId = (_c = fieldTranslationParams == null ? void 0 : fieldTranslationParams.document) == null ? void 0 : _c._id, id = react.useId(), selectFromLanguage = react.useCallback(
2240
+ }, []), languageClient = sanity.useClient({ apiVersion: config?.apiVersion ?? "2022-11-27" }), documentId = fieldTranslationParams?.document?._id, id = react.useId(), selectFromLanguage = react.useCallback(
2318
2241
  (from, languages2, params) => {
2319
- var _a2, _b2;
2320
- const { document: document2, documentSchema } = params != null ? params : {};
2242
+ const { document: document2, documentSchema } = params ?? {};
2321
2243
  if (setFromLanguage(from), !document2 || !documentSchema || !params || !languages2) {
2322
2244
  setFieldLanguageMaps(void 0);
2323
2245
  return;
2324
2246
  }
2325
- const preferred = getPreferredToFieldLanguages(from.id), allToLanguages = languages2.filter((l) => l.id !== (from == null ? void 0 : from.id)), filteredToLanguages = allToLanguages.filter(
2247
+ const preferred = getPreferredToFieldLanguages(from.id), allToLanguages = languages2.filter((l) => l.id !== from?.id), filteredToLanguages = allToLanguages.filter(
2326
2248
  (l) => !preferred.length || preferred.includes(l.id)
2327
2249
  );
2328
2250
  setToLanguages(filteredToLanguages);
2329
- const fromId = from == null ? void 0 : from.id, allToIds = (_a2 = allToLanguages == null ? void 0 : allToLanguages.map((l) => l.id)) != null ? _a2 : [], docMembers = getDocumentMembersFlat(document2, documentSchema);
2330
- if (fromId && allToIds != null && allToIds.length) {
2251
+ const fromId = from?.id, allToIds = allToLanguages?.map((l) => l.id) ?? [], docMembers = getDocumentMembersFlat(document2, documentSchema);
2252
+ if (fromId && allToIds?.length) {
2331
2253
  const transMap = getFieldLanguageMap(
2332
2254
  documentSchema,
2333
2255
  docMembers,
2334
2256
  fromId,
2335
2257
  allToIds.filter((toId) => fromId !== toId),
2336
- (_b2 = config == null ? void 0 : config.translationOutputs) != null ? _b2 : defaultLanguageOutputs
2258
+ config?.translationOutputs ?? defaultLanguageOutputs
2337
2259
  );
2338
2260
  setFieldLanguageMaps(transMap);
2339
2261
  } else
@@ -2344,10 +2266,10 @@ function FieldTranslationProvider(props) {
2344
2266
  (toggledLang, toLanguages2, languages2) => {
2345
2267
  if (!languages2 || !fromLanguage)
2346
2268
  return;
2347
- const wasSelected = !!(toLanguages2 != null && toLanguages2.find((l) => l.id === toggledLang.id)), newToLangs = languages2.filter(
2348
- (anyLang) => !!(toLanguages2 != null && toLanguages2.find(
2269
+ const wasSelected = !!toLanguages2?.find((l) => l.id === toggledLang.id), newToLangs = languages2.filter(
2270
+ (anyLang) => !!toLanguages2?.find(
2349
2271
  (selectedLang) => toggledLang.id !== selectedLang.id && selectedLang.id === anyLang.id
2350
- )) || toggledLang.id === anyLang.id && !wasSelected
2272
+ ) || toggledLang.id === anyLang.id && !wasSelected
2351
2273
  );
2352
2274
  setToLanguages(newToLangs), setPreferredToFieldLanguages(
2353
2275
  fromLanguage.id,
@@ -2358,26 +2280,26 @@ function FieldTranslationProvider(props) {
2358
2280
  ), openFieldTranslation = react.useCallback(
2359
2281
  async (params) => {
2360
2282
  setDialogOpen(!0);
2361
- const languageParams = getLanguageParams(config == null ? void 0 : config.selectLanguageParams, params.document), 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));
2283
+ const languageParams = getLanguageParams(config?.selectLanguageParams, params.document), languages2 = await (typeof config?.languages == "function" ? config?.languages(languageClient, languageParams) : Promise.resolve(config?.languages));
2362
2284
  setLanguages(languages2), setFieldTranslationParams(params);
2363
- const fromLanguage2 = languages2 == null ? void 0 : languages2[0];
2285
+ const fromLanguage2 = languages2?.[0];
2364
2286
  fromLanguage2 ? selectFromLanguage(fromLanguage2, languages2, params) : console.error("No languages available for selected language params", languageParams);
2365
2287
  },
2366
2288
  [selectFromLanguage, config, languageClient]
2367
2289
  ), contextValue = react.useMemo(() => ({
2368
2290
  openFieldTranslation,
2369
2291
  translationLoading: !1
2370
- }), [openFieldTranslation]), runDisabled = !fromLanguage || !(toLanguages != null && toLanguages.length) || !(fieldLanguageMaps != null && fieldLanguageMaps.length) || !documentId || !hasValuesToTranslate(fieldLanguageMaps, fromLanguage, fieldTranslationParams.translatePath), onRunTranslation = react.useCallback(() => {
2371
- const translatePath = fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath;
2292
+ }), [openFieldTranslation]), runDisabled = !fromLanguage || !toLanguages?.length || !fieldLanguageMaps?.length || !documentId || !hasValuesToTranslate(fieldLanguageMaps, fromLanguage, fieldTranslationParams.translatePath), onRunTranslation = react.useCallback(() => {
2293
+ const translatePath = fieldTranslationParams?.translatePath;
2372
2294
  fieldLanguageMaps && documentId && translatePath && runTranslate({
2373
2295
  documentId,
2374
2296
  translatePath,
2375
2297
  fieldLanguageMap: fieldLanguageMaps.map((map) => ({
2376
2298
  ...map,
2377
2299
  // eslint-disable-next-line max-nested-callbacks
2378
- outputs: map.outputs.filter((out) => !!(toLanguages != null && toLanguages.find((l) => l.id === out.id)))
2300
+ outputs: map.outputs.filter((out) => !!toLanguages?.find((l) => l.id === out.id))
2379
2301
  })),
2380
- conditionalMembers: fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers
2302
+ conditionalMembers: fieldTranslationParams?.conditionalMembers
2381
2303
  }), close();
2382
2304
  }, [
2383
2305
  fieldLanguageMaps,
@@ -2385,8 +2307,8 @@ function FieldTranslationProvider(props) {
2385
2307
  runTranslate,
2386
2308
  close,
2387
2309
  toLanguages,
2388
- fieldTranslationParams == null ? void 0 : fieldTranslationParams.translatePath,
2389
- fieldTranslationParams == null ? void 0 : fieldTranslationParams.conditionalMembers
2310
+ fieldTranslationParams?.translatePath,
2311
+ fieldTranslationParams?.conditionalMembers
2390
2312
  ]), runButton = /* @__PURE__ */ jsxRuntime.jsx(
2391
2313
  ui.Button,
2392
2314
  {
@@ -2418,7 +2340,7 @@ function FieldTranslationProvider(props) {
2418
2340
  children: languages ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { padding: 4, gap: 5, align: "flex-start", justify: "center", children: [
2419
2341
  /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 2, children: [
2420
2342
  /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { marginBottom: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { weight: "semibold", children: "From" }) }),
2421
- languages == null ? void 0 : languages.map((radioLanguage) => /* @__PURE__ */ jsxRuntime.jsx(
2343
+ languages?.map((radioLanguage) => /* @__PURE__ */ jsxRuntime.jsx(
2422
2344
  FromLanguageRadio,
2423
2345
  {
2424
2346
  radioLanguage,
@@ -2454,7 +2376,6 @@ function FieldTranslationProvider(props) {
2454
2376
  ] });
2455
2377
  }
2456
2378
  function ToLanguageCheckbox(props) {
2457
- var _a;
2458
2379
  const { checkboxLanguage, fromLanguage, toLanguages, toggleToLanguage, languages } = props, langId = checkboxLanguage.id, onChange = react.useCallback(
2459
2380
  () => toggleToLanguage(checkboxLanguage, toLanguages, languages),
2460
2381
  [toggleToLanguage, checkboxLanguage, toLanguages, languages]
@@ -2465,26 +2386,25 @@ function ToLanguageCheckbox(props) {
2465
2386
  gap: 3,
2466
2387
  align: "center",
2467
2388
  as: "label",
2468
- style: langId === (fromLanguage == null ? void 0 : fromLanguage.id) ? { opacity: 0.5 } : void 0,
2389
+ style: langId === fromLanguage?.id ? { opacity: 0.5 } : void 0,
2469
2390
  children: [
2470
2391
  /* @__PURE__ */ jsxRuntime.jsx(
2471
2392
  ui.Checkbox,
2472
2393
  {
2473
2394
  name: "toLang",
2474
2395
  value: langId,
2475
- checked: langId !== (fromLanguage == null ? void 0 : fromLanguage.id) && !!(toLanguages != null && toLanguages.find((tl) => tl.id === langId)),
2396
+ checked: langId !== fromLanguage?.id && !!toLanguages?.find((tl) => tl.id === langId),
2476
2397
  onChange,
2477
- disabled: langId === (fromLanguage == null ? void 0 : fromLanguage.id)
2398
+ disabled: langId === fromLanguage?.id
2478
2399
  }
2479
2400
  ),
2480
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: langId === (fromLanguage == null ? void 0 : fromLanguage.id), children: (_a = checkboxLanguage.title) != null ? _a : langId })
2401
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { muted: langId === fromLanguage?.id, children: checkboxLanguage.title ?? langId })
2481
2402
  ]
2482
2403
  },
2483
2404
  langId
2484
2405
  );
2485
2406
  }
2486
2407
  function FromLanguageRadio(props) {
2487
- var _a;
2488
2408
  const { languages, radioLanguage, selectFromLanguage, fromLanguage, fieldTranslationParams } = props, langId = radioLanguage.id, onChange = react.useCallback(
2489
2409
  () => selectFromLanguage(radioLanguage, languages, fieldTranslationParams),
2490
2410
  [selectFromLanguage, radioLanguage, languages, fieldTranslationParams]
@@ -2495,11 +2415,11 @@ function FromLanguageRadio(props) {
2495
2415
  {
2496
2416
  name: "fromLang",
2497
2417
  value: langId,
2498
- checked: langId === (fromLanguage == null ? void 0 : fromLanguage.id),
2418
+ checked: langId === fromLanguage?.id,
2499
2419
  onChange
2500
2420
  }
2501
2421
  ),
2502
- /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: (_a = radioLanguage.title) != null ? _a : radioLanguage.id })
2422
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: radioLanguage.title ?? radioLanguage.id })
2503
2423
  ] }, langId);
2504
2424
  }
2505
2425
  function AssistLayout(props) {
@@ -2583,10 +2503,9 @@ function AssistDocumentForm(props) {
2583
2503
  return props.readOnly ? /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { border: !0, tone: "caution", padding: 2, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, children: " You do not have sufficient permissions to manage instructions." }) }) : /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentFormEditable, { ...props });
2584
2504
  }
2585
2505
  function AssistDocumentFormEditable(props) {
2586
- const { onChange } = props, value = props.value, id = value == null ? void 0 : value._id, fields = value == null ? void 0 : value.fields, { params, setParams } = useAiPaneRouter(), pathKey = params[fieldPathParam], { typePath, documentType: targetDocumentType } = react.useContext(AssistTypeContext), instruction2 = params[instructionParam], activeKey = react.useMemo(() => {
2587
- var _a;
2506
+ const { onChange } = props, value = props.value, id = value?._id, fields = value?.fields, { params, setParams } = useAiPaneRouter(), pathKey = params[fieldPathParam], { typePath, documentType: targetDocumentType } = react.useContext(AssistTypeContext), instruction2 = params[instructionParam], activeKey = react.useMemo(() => {
2588
2507
  if (typePath)
2589
- return (_a = (fields != null ? fields : EMPTY_FIELDS).find((f) => f.path === typePath)) == null ? void 0 : _a._key;
2508
+ return (fields ?? EMPTY_FIELDS).find((f) => f.path === typePath)?._key;
2590
2509
  }, [fields, typePath]), activePath = react.useMemo(() => {
2591
2510
  if (!activeKey)
2592
2511
  return;
@@ -2598,23 +2517,21 @@ function AssistDocumentFormEditable(props) {
2598
2517
  }, [schema, targetDocumentType]), fieldSchema = useSelectedSchema(pathKey, documentSchema), context = react.useMemo(
2599
2518
  () => ({
2600
2519
  documentSchema,
2601
- fieldSchema: fieldSchema != null ? fieldSchema : documentSchema
2520
+ fieldSchema: fieldSchema ?? documentSchema
2602
2521
  }),
2603
2522
  [fieldSchema, documentSchema]
2604
- ), title = value == null ? void 0 : value.title;
2523
+ ), title = value?.title;
2605
2524
  react.useEffect(() => {
2606
- var _a;
2607
- !title && documentSchema && !(id != null && id.startsWith("drafts.")) && onChange(sanity.set((_a = documentSchema.title) != null ? _a : documentSchema.name, ["title"]));
2525
+ !title && documentSchema && !id?.startsWith("drafts.") && onChange(sanity.set(documentSchema.title ?? documentSchema.name, ["title"]));
2608
2526
  }, [title, documentSchema, onChange, id]);
2609
2527
  const { onPathOpen, ...formCallbacks } = sanity.useFormCallbacks(), newCallbacks = react.useMemo(
2610
2528
  () => ({
2611
2529
  ...formCallbacks,
2612
2530
  onPathOpen: (path) => {
2613
- var _a;
2614
2531
  !instruction2 && path.length === 4 && path[2] === "instructions" ? (setParams(
2615
2532
  sanity.typed({
2616
2533
  ...params,
2617
- [instructionParam]: (_a = path[3]) == null ? void 0 : _a._key
2534
+ [instructionParam]: path[3]?._key
2618
2535
  })
2619
2536
  ), onPathOpen([])) : setTimeout(() => onPathOpen(path), 0);
2620
2537
  }
@@ -2649,7 +2566,7 @@ function useSelectedSchema(fieldPath, documentSchema) {
2649
2566
  const path = sanity.stringToPath(fieldPath);
2650
2567
  let currentSchema = documentSchema;
2651
2568
  for (let i = 0; i < path.length; i++) {
2652
- const segment = path[i], field = currentSchema == null ? void 0 : currentSchema.fields.find((f) => f.name === segment);
2569
+ const segment = path[i], field = currentSchema?.fields.find((f) => f.name === segment);
2653
2570
  if (!field)
2654
2571
  return;
2655
2572
  if (i === path.length - 1)
@@ -2670,18 +2587,16 @@ function FieldsInitializer({
2670
2587
  }) {
2671
2588
  const {
2672
2589
  config: { __presets: presets }
2673
- } = useAiAssistanceConfig(), existingField = fields == null ? void 0 : fields.find((f) => f._key === pathKey), documentPresets = !!(documentSchema != null && documentSchema.name) && (presets == null ? void 0 : presets[documentSchema == null ? void 0 : documentSchema.name]), missingPresetInstructions = react.useMemo(() => {
2674
- var _a, _b;
2590
+ } = useAiAssistanceConfig(), existingField = fields?.find((f) => f._key === pathKey), documentPresets = !!documentSchema?.name && presets?.[documentSchema?.name], missingPresetInstructions = react.useMemo(() => {
2675
2591
  if (!documentPresets || !pathKey)
2676
2592
  return;
2677
- const existingInstructions = existingField == null ? void 0 : existingField.instructions, presetField = (_a = documentPresets.fields) == null ? void 0 : _a.find((f) => f.path === pathKey);
2678
- return (_b = presetField == null ? void 0 : presetField.instructions) == null ? void 0 : _b.filter(
2679
- (i) => !(existingInstructions != null && existingInstructions.some((ei) => ei._key === i._key))
2593
+ const existingInstructions = existingField?.instructions;
2594
+ return documentPresets.fields?.find((f) => f.path === pathKey)?.instructions?.filter(
2595
+ (i) => !existingInstructions?.some((ei) => ei._key === i._key)
2680
2596
  );
2681
2597
  }, [documentPresets, pathKey, existingField]), initialized = react.useRef(!1);
2682
2598
  return react.useEffect(() => {
2683
- var _a;
2684
- if (initialized.current || !pathKey || existingField && !(missingPresetInstructions != null && missingPresetInstructions.length))
2599
+ if (initialized.current || !pathKey || existingField && !missingPresetInstructions?.length)
2685
2600
  return;
2686
2601
  let event = sanity.PatchEvent.from([sanity.setIfMissing([], ["fields"])]);
2687
2602
  existingField || (event = event.append(
@@ -2697,17 +2612,14 @@ function FieldsInitializer({
2697
2612
  "after",
2698
2613
  ["fields", -1]
2699
2614
  )
2700
- )), (_a = existingField == null ? void 0 : existingField.instructions) != null && _a.length || (event = event.append([sanity.setIfMissing([], ["fields", { _key: pathKey }, "instructions"])])), missingPresetInstructions != null && missingPresetInstructions.length && (event = event.append(
2615
+ )), existingField?.instructions?.length || (event = event.append([sanity.setIfMissing([], ["fields", { _key: pathKey }, "instructions"])])), missingPresetInstructions?.length && (event = event.append(
2701
2616
  sanity.insert(
2702
2617
  missingPresetInstructions.map(
2703
- (preset) => {
2704
- var _a2;
2705
- return {
2706
- ...preset,
2707
- _type: "sanity.assist.instruction",
2708
- prompt: (_a2 = preset.prompt) == null ? void 0 : _a2.map((p) => ({ markDefs: [], ...p }))
2709
- };
2710
- }
2618
+ (preset) => ({
2619
+ ...preset,
2620
+ _type: "sanity.assist.instruction",
2621
+ prompt: preset.prompt?.map((p) => ({ markDefs: [], ...p }))
2622
+ })
2711
2623
  ),
2712
2624
  "after",
2713
2625
  ["fields", { _key: pathKey }, "instructions", -1]
@@ -2720,11 +2632,10 @@ function AssistInlineFormBlock(props) {
2720
2632
  return /* @__PURE__ */ jsxRuntime.jsx(InlineBlockValueContext.Provider, { value: props.value, children: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.renderDefault(props) }) });
2721
2633
  }
2722
2634
  function FieldRefPreview(props) {
2723
- var _a, _b, _c, _d;
2724
- const documentSchema = (_a = react.useContext(SelectedFieldContext)) == null ? void 0 : _a.documentSchema, path = (_c = (_b = react.useContext(InlineBlockValueContext)) == null ? void 0 : _b.path) != null ? _c : props.path, selectedField = useSelectedField(documentSchema, path);
2635
+ const { actions } = props, documentSchema = react.useContext(SelectedFieldContext)?.documentSchema, path = react.useContext(InlineBlockValueContext)?.path ?? props.path, selectedField = useSelectedField(documentSchema, path);
2725
2636
  return /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 2, align: "center", style: { width: "100%" }, children: [
2726
- /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { flex: 1, gap: 2, align: "center", paddingY: 3, paddingX: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, textOverflow: "ellipsis", children: (_d = selectedField == null ? void 0 : selectedField.title) != null ? _d : "Select field" }) }) }),
2727
- /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.actions })
2637
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { flex: 1, gap: 2, align: "center", paddingY: 3, paddingX: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 1, textOverflow: "ellipsis", children: selectedField?.title ?? "Select field" }) }) }),
2638
+ actions
2728
2639
  ] });
2729
2640
  }
2730
2641
  function HiddenFieldTitle(props) {
@@ -2754,13 +2665,11 @@ function IconItem({
2754
2665
  return /* @__PURE__ */ jsxRuntime.jsx(ui.MenuItem, { icon, title: key, text: key, onClick });
2755
2666
  }
2756
2667
  function getIcon(iconName) {
2757
- var _a, _b;
2758
- return (_b = (_a = Object.entries(icons.icons).find(([key]) => key === iconName)) == null ? void 0 : _a[1]) != null ? _b : icons.icons.sparkles;
2668
+ return Object.entries(icons.icons).find(([key]) => key === iconName)?.[1] ?? icons.icons.sparkles;
2759
2669
  }
2760
2670
  function InstructionVisibility(props) {
2761
2671
  const { value, onChange } = props, user = sanity.useCurrentUser(), handleChange = react.useCallback(() => {
2762
- var _a;
2763
- const newValue = value ? "" : (_a = user == null ? void 0 : user.id) != null ? _a : "";
2672
+ const newValue = value ? "" : user?.id ?? "";
2764
2673
  onChange(newValue ? sanity.set(newValue) : sanity.unset());
2765
2674
  }, [onChange, user, value]), id = react.useId();
2766
2675
  return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 2, align: "flex-start", children: [
@@ -2779,11 +2688,9 @@ function InstructionVisibility(props) {
2779
2688
  ] }) });
2780
2689
  }
2781
2690
  function FieldRefPathInput(props) {
2782
- var _a;
2783
- const documentSchema = (_a = react.useContext(SelectedFieldContext)) == null ? void 0 : _a.documentSchema, { typePath } = react.useContext(AssistTypeContext), ref = react.useRef(null), id = react.useId(), { onChange } = props;
2691
+ const documentSchema = react.useContext(SelectedFieldContext)?.documentSchema, { typePath } = react.useContext(AssistTypeContext), ref = react.useRef(null), id = react.useId(), { onChange } = props;
2784
2692
  react.useEffect(() => {
2785
- var _a2, _b;
2786
- (_b = (_a2 = ref.current) == null ? void 0 : _a2.querySelector("input")) == null || _b.focus();
2693
+ ref.current?.querySelector("input")?.focus();
2787
2694
  }, []);
2788
2695
  const onSelect = react.useCallback((path) => onChange(sanity.set(path)), [onChange]), filter = react.useCallback(
2789
2696
  (field) => {
@@ -2831,15 +2738,14 @@ function ObjectMember({ fieldName, ...props }) {
2831
2738
  }
2832
2739
  const NONE = [];
2833
2740
  function NameField(props) {
2834
- var _a;
2835
- const fieldsetMember = findFieldsetMember(props.members, "appearance"), titleId = react.useId(), members = (_a = fieldsetMember == null ? void 0 : fieldsetMember.fieldSet.members) != null ? _a : NONE, iconMember = findFieldMember(members, "icon"), titleMember = findFieldMember(members, "title"), titlePlaceholder = "Untitled", moddedTitleMember = react.useMemo(() => {
2741
+ const fieldsetMember = findFieldsetMember(props.members, "appearance"), titleId = react.useId(), members = fieldsetMember?.fieldSet.members ?? NONE, iconMember = findFieldMember(members, "icon"), titleMember = findFieldMember(members, "title"), titlePlaceholder = "Untitled", moddedTitleMember = react.useMemo(() => {
2836
2742
  if (titleMember)
2837
2743
  return titleMember.kind === "error" ? titleMember : {
2838
2744
  ...titleMember,
2839
2745
  field: {
2840
- ...titleMember == null ? void 0 : titleMember.field,
2746
+ ...titleMember?.field,
2841
2747
  schemaType: {
2842
- ...titleMember == null ? void 0 : titleMember.field.schemaType,
2748
+ ...titleMember?.field.schemaType,
2843
2749
  placeholder: titlePlaceholder
2844
2750
  }
2845
2751
  }
@@ -2855,21 +2761,18 @@ function NameField(props) {
2855
2761
  ] }) });
2856
2762
  }
2857
2763
  function ShareField(props) {
2858
- var _a;
2859
- const fieldsetMember = findFieldsetMember(props.members, "appearance"), members = (_a = fieldsetMember == null ? void 0 : fieldsetMember.fieldSet.members) != null ? _a : NONE, visibilityMember = findFieldMember(members, "userId");
2764
+ const members = findFieldsetMember(props.members, "appearance")?.fieldSet.members ?? NONE, visibilityMember = findFieldMember(members, "userId");
2860
2765
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: visibilityMember && /* @__PURE__ */ jsxRuntime.jsx(sanity.ObjectInputMember, { ...props, member: visibilityMember }) });
2861
2766
  }
2862
2767
  function InstructionOutputField(props) {
2863
- var _a;
2864
- const { fieldSchema } = (_a = react.useContext(SelectedFieldContext)) != null ? _a : {};
2768
+ const { fieldSchema } = react.useContext(SelectedFieldContext) ?? {};
2865
2769
  return !fieldSchema || !(sanity.isObjectSchemaType(fieldSchema) || sanity.isArrayOfObjectsSchemaType(fieldSchema)) ? null : /* @__PURE__ */ jsxRuntime.jsx(EnabledOutputField, { ...props, fieldSchema, children: props.children });
2866
2770
  }
2867
2771
  function EnabledOutputField({
2868
2772
  fieldSchema,
2869
2773
  ...props
2870
2774
  }) {
2871
- var _a;
2872
- const [open, setOpen] = react.useState(!!((_a = props.value) != null && _a.length)), onExpand = react.useCallback(() => setOpen(!0), []), onCollapse = react.useCallback(() => setOpen(!1), []);
2775
+ const [open, setOpen] = react.useState(!!props.value?.length), onExpand = react.useCallback(() => setOpen(!0), []), onCollapse = react.useCallback(() => setOpen(!1), []);
2873
2776
  return props.renderDefault({
2874
2777
  ...props,
2875
2778
  collapsible: !0,
@@ -2881,18 +2784,16 @@ function EnabledOutputField({
2881
2784
  });
2882
2785
  }
2883
2786
  function InstructionOutputInput(props) {
2884
- var _a;
2885
- const { fieldSchema } = (_a = react.useContext(SelectedFieldContext)) != null ? _a : {};
2787
+ const { fieldSchema } = react.useContext(SelectedFieldContext) ?? {};
2886
2788
  return fieldSchema ? sanity.isObjectSchemaType(fieldSchema) ? /* @__PURE__ */ jsxRuntime.jsx(ObjectOutputInput, { ...props, fieldSchema }) : sanity.isArrayOfObjectsSchemaType(fieldSchema) ? /* @__PURE__ */ jsxRuntime.jsx(ArrayOutputInput, { ...props, fieldSchema }) : null : null;
2887
2789
  }
2888
2790
  function useEmptySelectAllValue(value, allowedValues, onChange) {
2889
2791
  react.useEffect(() => {
2890
- var _a, _b;
2891
- const validValues = value == null ? void 0 : value.filter(
2792
+ const validValues = value?.filter(
2892
2793
  (v) => allowedValues.find(
2893
2794
  (f) => f.name === (v._type === outputFieldTypeName ? v.relativePath : v.type)
2894
2795
  )
2895
- ), valueLength = (_a = value == null ? void 0 : value.length) != null ? _a : 0, validLength = (_b = validValues == null ? void 0 : validValues.length) != null ? _b : 0;
2796
+ ), valueLength = value?.length ?? 0, validLength = validValues?.length ?? 0;
2896
2797
  (!validLength && valueLength || validLength >= allowedValues.length) && onChange(sanity.PatchEvent.from([sanity.unset()]));
2897
2798
  }, [allowedValues, value, onChange]);
2898
2799
  }
@@ -2908,7 +2809,7 @@ function ObjectOutputInput({
2908
2809
  const onSelectChange = react.useCallback(
2909
2810
  (checked, selectedValue) => {
2910
2811
  if (checked)
2911
- if (value != null && value.length)
2812
+ if (value?.length)
2912
2813
  onChange(sanity.PatchEvent.from(sanity.unset([{ _key: selectedValue }])));
2913
2814
  else {
2914
2815
  const items = fields.filter((f) => f.name !== selectedValue).map(
@@ -2931,18 +2832,15 @@ function ObjectOutputInput({
2931
2832
  },
2932
2833
  [onChange, value, fields]
2933
2834
  );
2934
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { space: 2, children: fields.map((field) => {
2935
- var _a;
2936
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { align: "center", gap: 2, children: /* @__PURE__ */ jsxRuntime.jsx(
2937
- Selectable,
2938
- {
2939
- value: field.name,
2940
- title: (_a = field.type.title) != null ? _a : field.name,
2941
- arrayValue: value,
2942
- onChange: onSelectChange
2943
- }
2944
- ) }, field.name);
2945
- }) });
2835
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { space: 2, children: fields.map((field) => /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { align: "center", gap: 2, children: /* @__PURE__ */ jsxRuntime.jsx(
2836
+ Selectable,
2837
+ {
2838
+ value: field.name,
2839
+ title: field.type.title ?? field.name,
2840
+ arrayValue: value,
2841
+ onChange: onSelectChange
2842
+ }
2843
+ ) }, field.name)) });
2946
2844
  }
2947
2845
  function ArrayOutputInput({
2948
2846
  fieldSchema,
@@ -2956,7 +2854,7 @@ function ArrayOutputInput({
2956
2854
  const onSelectChange = react.useCallback(
2957
2855
  (checked, selectedValue) => {
2958
2856
  if (checked)
2959
- if (value != null && value.length)
2857
+ if (value?.length)
2960
2858
  onChange(sanity.PatchEvent.from(sanity.unset([{ _key: selectedValue }])));
2961
2859
  else {
2962
2860
  const items = ofItems.filter((f) => f.name !== selectedValue).map(
@@ -2979,18 +2877,15 @@ function ArrayOutputInput({
2979
2877
  },
2980
2878
  [onChange, value, ofItems]
2981
2879
  );
2982
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { space: 2, children: ofItems.map((itemType) => {
2983
- var _a;
2984
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { children: /* @__PURE__ */ jsxRuntime.jsx(
2985
- Selectable,
2986
- {
2987
- value: itemType.name,
2988
- title: isType(itemType, "block") ? "Text" : (_a = itemType.title) != null ? _a : itemType.name,
2989
- arrayValue: value,
2990
- onChange: onSelectChange
2991
- }
2992
- ) }, itemType.name);
2993
- }) });
2880
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.Stack, { space: 2, children: ofItems.map((itemType) => /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { children: /* @__PURE__ */ jsxRuntime.jsx(
2881
+ Selectable,
2882
+ {
2883
+ value: itemType.name,
2884
+ title: isType(itemType, "block") ? "Text" : itemType.title ?? itemType.name,
2885
+ arrayValue: value,
2886
+ onChange: onSelectChange
2887
+ }
2888
+ ) }, itemType.name)) });
2994
2889
  }
2995
2890
  function Selectable({
2996
2891
  title,
@@ -2998,7 +2893,7 @@ function Selectable({
2998
2893
  value,
2999
2894
  onChange
3000
2895
  }) {
3001
- const checked = !(arrayValue != null && arrayValue.length) || !!(arrayValue != null && arrayValue.find((v) => v._key === value)), handleChange = react.useCallback(() => onChange(checked, value), [onChange, checked, value]);
2896
+ const checked = !arrayValue?.length || !!arrayValue?.find((v) => v._key === value), handleChange = react.useCallback(() => onChange(checked, value), [onChange, checked, value]);
3002
2897
  return /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { gap: 2, align: "flex-start", children: [
3003
2898
  /* @__PURE__ */ jsxRuntime.jsx(ui.Checkbox, { checked, onChange: handleChange }),
3004
2899
  /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { marginTop: 1, onClick: handleChange, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { style: { cursor: "default" }, size: 1, children: title }) })
@@ -3045,9 +2940,8 @@ function PromptInput(props) {
3045
2940
  }
3046
2941
  function useOnlyInlineBlocks(props) {
3047
2942
  react.useEffect(() => {
3048
- var _a;
3049
2943
  let needsFix = !1;
3050
- const val = ((_a = props.value) != null ? _a : []).map((block) => block._type === "block" ? block : (needsFix = !0, sanity.typed({
2944
+ const val = (props.value ?? []).map((block) => block._type === "block" ? block : (needsFix = !0, sanity.typed({
3051
2945
  _key: randomKey(12),
3052
2946
  _type: "block",
3053
2947
  level: 0,
@@ -3066,15 +2960,14 @@ function InstructionsArrayField(props) {
3066
2960
  }
3067
2961
  function InstructionsArrayInput(props) {
3068
2962
  const user = sanity.useCurrentUser(), originalValue = props.value, originalMembers = props.members, value = react.useMemo(
3069
- () => (originalValue != null ? originalValue : []).filter((v) => !v.userId || v.userId === (user == null ? void 0 : user.id)),
2963
+ () => (originalValue ?? []).filter((v) => !v.userId || v.userId === user?.id),
3070
2964
  [originalValue, user]
3071
2965
  ), members = react.useMemo(
3072
- () => (originalMembers != null ? originalMembers : []).filter((v) => {
3073
- var _a;
2966
+ () => (originalMembers ?? []).filter((v) => {
3074
2967
  if (v.kind === "error")
3075
2968
  return !0;
3076
- const value2 = (_a = v == null ? void 0 : v.item) == null ? void 0 : _a.value;
3077
- return !value2.userId || value2.userId === (user == null ? void 0 : user.id);
2969
+ const value2 = v?.item?.value;
2970
+ return !value2.userId || value2.userId === user?.id;
3078
2971
  }),
3079
2972
  [originalMembers, user]
3080
2973
  );
@@ -3083,8 +2976,7 @@ function InstructionsArrayInput(props) {
3083
2976
  function HideReferenceChangedBannerInput(props) {
3084
2977
  const ref = react.useRef(null);
3085
2978
  return react.useEffect(() => {
3086
- var _a;
3087
- const parent = (_a = ref.current) == null ? void 0 : _a.closest('[data-testid="pane-content"]');
2979
+ const parent = ref.current?.closest('[data-testid="pane-content"]');
3088
2980
  if (!parent)
3089
2981
  return;
3090
2982
  const style = document.createElement("style"), parentId = `id-${Math.random()}`.replace(".", "-");
@@ -3131,11 +3023,7 @@ const contextDocumentSchema = sanity.defineType({
3131
3023
  context: "context"
3132
3024
  },
3133
3025
  prepare({ title, context }) {
3134
- var _a;
3135
- const text = context == null ? void 0 : context.flatMap((block) => block == null ? void 0 : block.children).flatMap((child) => {
3136
- var _a2;
3137
- return (_a2 = child == null ? void 0 : child.text) == null ? void 0 : _a2.split(" ");
3138
- }).filter(Boolean), words = (_a = text == null ? void 0 : text.length) != null ? _a : 0;
3026
+ const words = context?.flatMap((block) => block?.children).flatMap((child) => child?.text?.split(" ")).filter(Boolean)?.length ?? 0;
3139
3027
  return {
3140
3028
  title,
3141
3029
  subtitle: `Words: ${words}`,
@@ -3157,11 +3045,10 @@ const contextDocumentSchema = sanity.defineType({
3157
3045
  input: FieldRefPathInput
3158
3046
  },
3159
3047
  validation: (rule) => rule.custom((value, context) => {
3160
- var _a;
3161
3048
  if (!value)
3162
3049
  return "Please select a field";
3163
3050
  try {
3164
- const docId = (_a = context.document) == null ? void 0 : _a._id;
3051
+ const docId = context.document?._id;
3165
3052
  if (!docId)
3166
3053
  return "Field reference cannot be used outside document inspector context. Could not resolve document id.";
3167
3054
  const targetDocType = docId.replace(new RegExp(`^${assistDocumentIdPrefix}`), ""), schema = context.schema.get(targetDocType);
@@ -3252,8 +3139,7 @@ const contextDocumentSchema = sanity.defineType({
3252
3139
  context: "reference.context"
3253
3140
  },
3254
3141
  prepare(select) {
3255
- var _a, _b, _c, _d;
3256
- return select.ref ? (_d = (_c = (_b = (_a = contextDocumentSchema) == null ? void 0 : _a.preview) == null ? void 0 : _b.prepare) == null ? void 0 : _c.call(_b, select)) != null ? _d : select : { title: "No reference selected", media: contextDocumentSchema.icon };
3142
+ return select.ref ? contextDocumentSchema?.preview?.prepare?.(select) ?? select : { title: "No reference selected", media: contextDocumentSchema.icon };
3257
3143
  }
3258
3144
  },
3259
3145
  options: {
@@ -3400,14 +3286,8 @@ const contextDocumentSchema = sanity.defineType({
3400
3286
  field: HiddenFieldTitle,
3401
3287
  input: InstructionVisibility
3402
3288
  },
3403
- initialValue: (params, context) => {
3404
- var _a, _b;
3405
- return (_b = (_a = context.currentUser) == null ? void 0 : _a.id) != null ? _b : "";
3406
- },
3407
- readOnly: (context) => {
3408
- var _a, _b, _c;
3409
- return !!((_a = context.parent) != null && _a.createdById && ((_b = context.parent) == null ? void 0 : _b.createdById) !== ((_c = context.currentUser) == null ? void 0 : _c.id));
3410
- }
3289
+ initialValue: (params, context) => context.currentUser?.id ?? "",
3290
+ readOnly: (context) => !!(context.parent?.createdById && context.parent?.createdById !== context.currentUser?.id)
3411
3291
  }),
3412
3292
  sanity.defineField({
3413
3293
  type: "string",
@@ -3415,10 +3295,7 @@ const contextDocumentSchema = sanity.defineType({
3415
3295
  title: "Created by",
3416
3296
  hidden: !0,
3417
3297
  fieldset: "appearance",
3418
- initialValue: (params, context) => {
3419
- var _a, _b;
3420
- return (_b = (_a = context.currentUser) == null ? void 0 : _a.id) != null ? _b : "";
3421
- }
3298
+ initialValue: (params, context) => context.currentUser?.id ?? ""
3422
3299
  }),
3423
3300
  sanity.defineField({
3424
3301
  type: "array",
@@ -3540,8 +3417,7 @@ const contextDocumentSchema = sanity.defineType({
3540
3417
  ]
3541
3418
  });
3542
3419
  function excludeComments(type) {
3543
- var _a, _b, _c;
3544
- const existingRender = (_a = type == null ? void 0 : type.components) == null ? void 0 : _a.field;
3420
+ const existingRender = type?.components?.field;
3545
3421
  return {
3546
3422
  ...type,
3547
3423
  ..."components" in type ? {
@@ -3555,11 +3431,11 @@ function excludeComments(type) {
3555
3431
  } : {},
3556
3432
  ..."fields" in type ? {
3557
3433
  // recursively disable comments in fields
3558
- fields: (_b = type.fields) == null ? void 0 : _b.map((field) => excludeComments(field))
3434
+ fields: type.fields?.map((field) => excludeComments(field))
3559
3435
  } : {},
3560
3436
  ..."of" in type ? {
3561
3437
  // recursively disable comments in array items
3562
- of: (_c = type.of) == null ? void 0 : _c.map((arrayItemType) => excludeComments(arrayItemType))
3438
+ of: type.of?.map((arrayItemType) => excludeComments(arrayItemType))
3563
3439
  } : {}
3564
3440
  };
3565
3441
  }
@@ -3579,61 +3455,19 @@ const instructionForm = [
3579
3455
  instructionTask,
3580
3456
  contextDocumentSchema
3581
3457
  ];
3582
- function useAssistDocumentContextValue(documentId, documentSchemaType) {
3583
- const { published, draft } = sanity.useEditState(
3584
- sanity.getPublishedId(documentId),
3585
- documentSchemaType.name,
3586
- "low"
3587
- ), assistableDocumentId = (draft == null ? void 0 : draft._id) || (published == null ? void 0 : published._id) || documentId, documentIsNew = !(draft != null && draft._id) && !(published != null && published._id), documentIsAssistable = isDocAssistable(documentSchemaType, published, draft), { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], { openInspector, closeInspector, inspector, onChange: documentOnChange } = structure.useDocumentPane(), assistDocument = useStudioAssistDocument({
3588
- documentId,
3589
- schemaType: documentSchemaType
3590
- });
3591
- return react.useMemo(() => {
3592
- const base = {
3593
- documentId,
3594
- assistableDocumentId,
3595
- documentSchemaType,
3596
- documentIsNew,
3597
- documentIsAssistable,
3598
- openInspector,
3599
- closeInspector,
3600
- inspector,
3601
- documentOnChange,
3602
- selectedPath
3603
- };
3604
- return assistDocument ? {
3605
- ...base,
3606
- loading: !1,
3607
- assistDocument
3608
- } : { ...base, loading: !0, assistDocument: void 0 };
3609
- }, [
3610
- assistDocument,
3611
- documentIsAssistable,
3612
- documentId,
3613
- assistableDocumentId,
3614
- documentSchemaType,
3615
- documentIsNew,
3616
- openInspector,
3617
- closeInspector,
3618
- inspector,
3619
- documentOnChange,
3620
- selectedPath
3621
- ]);
3622
- }
3623
3458
  function useAssistSupported(path, schemaType) {
3624
3459
  return react.useMemo(() => isAssistSupported(schemaType), [schemaType]);
3625
3460
  }
3626
3461
  const translateActions = {
3627
3462
  name: "sanity-assist-translate",
3628
3463
  useAction(props) {
3629
- var _a, _b, _c, _d, _e, _f, _g, _h;
3630
- const { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), {
3464
+ const { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), {
3631
3465
  schemaType: fieldSchemaType,
3632
3466
  path,
3633
3467
  documentId,
3634
3468
  documentSchemaType,
3635
3469
  documentIsAssistable
3636
- } = props, isDocumentLevel = path.length === 0, readOnly = fieldSchemaType.readOnly === !0, docTransTypes = (_b = (_a = config.translate) == null ? void 0 : _a.document) == null ? void 0 : _b.documentTypes, options2 = fieldSchemaType == null ? void 0 : fieldSchemaType.options, addFieldAction = isDocumentLevel || ((_c = options2 == null ? void 0 : options2.aiAssist) == null ? void 0 : _c.translateAction), 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)), documentTranslationEnabled = addFieldAction && documentSchemaType && (!docTransTypes && isAssistSupported(fieldSchemaType) || (docTransTypes == null ? void 0 : docTransTypes.includes(documentSchemaType.name)));
3470
+ } = props, isDocumentLevel = path.length === 0, readOnly = fieldSchemaType.readOnly === !0, docTransTypes = config.translate?.document?.documentTypes, options2 = fieldSchemaType?.options, addFieldAction = isDocumentLevel || options2?.aiAssist?.translateAction, fieldTransEnabled = addFieldAction && documentSchemaType && config.translate?.field?.documentTypes?.includes(documentSchemaType.name), documentTranslationEnabled = addFieldAction && documentSchemaType && (!docTransTypes && isAssistSupported(fieldSchemaType) || docTransTypes?.includes(documentSchemaType.name));
3637
3471
  if (documentSchemaType && (documentTranslationEnabled || fieldTransEnabled)) {
3638
3472
  const { value: documentValue, onChange: documentOnChange, formState } = structure.useDocumentPane(), docRef = react.useRef(documentValue);
3639
3473
  docRef.current = documentValue;
@@ -3641,9 +3475,9 @@ const translateActions = {
3641
3475
  formStateRef.current = formState;
3642
3476
  const translationApi = useTranslate(apiClient), translate = useDraftDelayedTask({
3643
3477
  documentOnChange,
3644
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1,
3478
+ isDocAssistable: documentIsAssistable ?? !1,
3645
3479
  task: translationApi.translate
3646
- }), languagePath = (_h = (_g = config.translate) == null ? void 0 : _g.document) == null ? void 0 : _h.languageField, translateDocumentAction = react.useMemo(() => {
3480
+ }), languagePath = config.translate?.document?.languageField, translateDocumentAction = react.useMemo(() => {
3647
3481
  if (!languagePath || !documentTranslationEnabled)
3648
3482
  return;
3649
3483
  const title = path.length ? "Translate" : "Translate document";
@@ -3655,7 +3489,7 @@ const translateActions = {
3655
3489
  translationApi.loading || !languagePath || !documentId || translate({
3656
3490
  languagePath,
3657
3491
  translatePath: path,
3658
- documentId: documentId != null ? documentId : "",
3492
+ documentId: documentId ?? "",
3659
3493
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
3660
3494
  });
3661
3495
  },
@@ -3672,7 +3506,7 @@ const translateActions = {
3672
3506
  readOnly
3673
3507
  ]), fieldTranslate = useFieldTranslation(), openFieldTranslation = useDraftDelayedTask({
3674
3508
  documentOnChange,
3675
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1,
3509
+ isDocAssistable: documentIsAssistable ?? !1,
3676
3510
  task: fieldTranslate.openFieldTranslation
3677
3511
  }), translateFieldsAction = react.useMemo(
3678
3512
  () => fieldTransEnabled ? {
@@ -3701,7 +3535,7 @@ const translateActions = {
3701
3535
  ]
3702
3536
  );
3703
3537
  return react.useMemo(() => {
3704
- if (status != null && status.initialized)
3538
+ if (status?.initialized)
3705
3539
  return {
3706
3540
  type: "group",
3707
3541
  icon: () => null,
@@ -3716,17 +3550,23 @@ const translateActions = {
3716
3550
  }
3717
3551
  }, ImageContext = react.createContext({});
3718
3552
  function ImageContextProvider(props) {
3719
- var _a, _b;
3720
- const { schemaType, path, value, readOnly } = props, assetRef = (_a = value == null ? void 0 : value.asset) == null ? void 0 : _a._ref, [assetRefState, setAssetRefState] = react.useState(assetRef), { documentId, documentSchemaType } = useAssistDocumentContext(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateCaption } = useGenerateCaption(apiClient), { isSyncing } = sanity.useSyncState(publicId(documentId), documentSchemaType.name), isShowingOlderRevision = !!((_b = structure.usePaneRouter().params) != null && _b.rev);
3553
+ const { schemaType, path, value, readOnly } = props, assetRef = value?.asset?._ref, { selectedReleaseId } = structure.useDocumentPane(), [assetRefState, setAssetRefState] = react.useState(assetRef), { assistableDocumentId, documentSchemaType } = useAssistDocumentContext(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateCaption } = useGenerateCaption(apiClient), { isSyncing } = sanity.useSyncState(
3554
+ sanity.getPublishedId(assistableDocumentId),
3555
+ documentSchemaType.name,
3556
+ selectedReleaseId
3557
+ ), isShowingOlderRevision = !!structure.usePaneRouter().params?.rev;
3721
3558
  react.useEffect(() => {
3722
3559
  const descriptionField = getDescriptionFieldOption(schemaType);
3723
- assetRef && documentId && descriptionField && assetRef !== assetRefState && !isSyncing && !isShowingOlderRevision && !readOnly && (setAssetRefState(assetRef), canUseAssist(status) && generateCaption({ path: sanity.pathToString([...path, descriptionField]), documentId }));
3560
+ assetRef && assistableDocumentId && descriptionField && assetRef !== assetRefState && !isSyncing && !isShowingOlderRevision && !readOnly && (setAssetRefState(assetRef), canUseAssist(status) && generateCaption({
3561
+ path: sanity.pathToString([...path, descriptionField]),
3562
+ documentId: assistableDocumentId
3563
+ }));
3724
3564
  }, [
3725
3565
  schemaType,
3726
3566
  path,
3727
3567
  assetRef,
3728
3568
  assetRefState,
3729
- documentId,
3569
+ assistableDocumentId,
3730
3570
  generateCaption,
3731
3571
  isSyncing,
3732
3572
  status,
@@ -3746,9 +3586,9 @@ function ImageContextProvider(props) {
3746
3586
  const generateCaptionsActions = {
3747
3587
  name: "sanity-assist-generate-captions",
3748
3588
  useAction(props) {
3749
- const pathKey = usePathKey(props.path), { openInspector } = structure.useDocumentPane(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateCaption, loading } = useGenerateCaption(apiClient), imageContext = react.useContext(ImageContext);
3750
- if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageDescriptionPath)) {
3751
- const { documentId } = useAssistDocumentContext();
3589
+ const pathKey = usePathKey(props.path), { openInspector } = structure.useDocumentPane(), { config, status } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateCaption, loading } = useGenerateCaption(apiClient), imageContext = react.useContext(ImageContext);
3590
+ if (imageContext && pathKey === imageContext?.imageDescriptionPath) {
3591
+ const { assistableDocumentId } = useAssistDocumentContext();
3752
3592
  return react.useMemo(() => ({
3753
3593
  type: "action",
3754
3594
  icon: loading ? () => /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { style: { height: 17 }, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, { style: { transform: "translateY(6px)" } }) }) : icons.ImageIcon,
@@ -3762,31 +3602,39 @@ const generateCaptionsActions = {
3762
3602
  });
3763
3603
  return;
3764
3604
  }
3765
- generateCaption({ path: pathKey, documentId: documentId != null ? documentId : "" });
3605
+ generateCaption({ path: pathKey, documentId: assistableDocumentId });
3766
3606
  }
3767
3607
  },
3768
3608
  renderAsButton: !0,
3769
3609
  disabled: loading,
3770
3610
  hidden: !imageContext.assetRef
3771
- }), [generateCaption, pathKey, documentId, loading, imageContext, status, openInspector]);
3611
+ }), [
3612
+ generateCaption,
3613
+ pathKey,
3614
+ assistableDocumentId,
3615
+ loading,
3616
+ imageContext,
3617
+ status,
3618
+ openInspector
3619
+ ]);
3772
3620
  }
3773
3621
  }
3774
3622
  }, generateImagActions = {
3775
3623
  name: "sanity-assist-generate-image",
3776
3624
  useAction(props) {
3777
- const pathKey = usePathKey(props.path), { config } = useAiAssistanceConfig(), apiClient = useApiClient(config == null ? void 0 : config.__customApiClient), { generateImage, loading } = useGenerateImage(apiClient), imageContext = react.useContext(ImageContext);
3778
- if (imageContext && pathKey === (imageContext == null ? void 0 : imageContext.imageInstructionPath)) {
3779
- const { documentId } = useAssistDocumentContext();
3625
+ const pathKey = usePathKey(props.path), { config } = useAiAssistanceConfig(), apiClient = useApiClient(config?.__customApiClient), { generateImage, loading } = useGenerateImage(apiClient), imageContext = react.useContext(ImageContext);
3626
+ if (imageContext && pathKey === imageContext?.imageInstructionPath) {
3627
+ const { assistableDocumentId } = useAssistDocumentContext();
3780
3628
  return react.useMemo(() => ({
3781
3629
  type: "action",
3782
3630
  icon: loading ? () => /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { style: { height: 17 }, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Spinner, { style: { transform: "translateY(6px)" } }) }) : icons.ImageIcon,
3783
3631
  title: "Generate image from prompt",
3784
3632
  onAction: () => {
3785
- loading || generateImage({ path: pathKey, documentId: documentId != null ? documentId : "" });
3633
+ loading || generateImage({ path: pathKey, documentId: assistableDocumentId });
3786
3634
  },
3787
3635
  renderAsButton: !0,
3788
3636
  disabled: loading
3789
- }), [generateImage, pathKey, documentId, loading]);
3637
+ }), [generateImage, pathKey, assistableDocumentId, loading]);
3790
3638
  }
3791
3639
  }
3792
3640
  };
@@ -3806,7 +3654,7 @@ function PrivateIcon() {
3806
3654
  const assistFieldActions = {
3807
3655
  name: "sanity-assist-actions",
3808
3656
  useAction(props) {
3809
- const { schemaType } = props, isDocumentLevel = props.path.length === 0, {
3657
+ const { schemaType } = props, {
3810
3658
  assistDocument,
3811
3659
  documentIsNew,
3812
3660
  documentIsAssistable,
@@ -3815,33 +3663,19 @@ const assistFieldActions = {
3815
3663
  inspector,
3816
3664
  documentOnChange,
3817
3665
  documentSchemaType,
3818
- documentId,
3819
3666
  selectedPath,
3820
3667
  assistableDocumentId
3821
- } = (
3822
- // document field actions do not have access to the document context
3823
- // conditional hook _should_ be safe here since the logical path will be stable
3824
- isDocumentLevel ? (
3825
- // eslint-disable-next-line react-hooks/rules-of-hooks
3826
- useAssistDocumentContextValue(props.documentId, schemaType)
3827
- ) : (
3828
- // eslint-disable-next-line react-hooks/rules-of-hooks
3829
- useAssistDocumentContext()
3830
- )
3831
- ), { value: docValue, formState } = structure.useDocumentPane(), formStateRef = react.useRef(formState);
3668
+ } = useAssistDocumentContext(), { value: docValue, formState } = structure.useDocumentPane(), formStateRef = react.useRef(formState);
3832
3669
  formStateRef.current = formState;
3833
- const currentUser = sanity.useCurrentUser(), isHidden = !assistDocument, pathKey = usePathKey(props.path), typePath = useTypePath(docValue, pathKey), assistDocumentId2 = assistDocument == null ? void 0 : assistDocument._id, assistableDocId = getAssistableDocId(documentSchemaType, documentId), { requestRunInstruction } = useRequestRunInstruction({
3670
+ const currentUser = sanity.useCurrentUser(), isHidden = !assistDocument, pathKey = usePathKey(props.path), typePath = useTypePath(docValue, pathKey), assistDocumentId2 = assistDocument?._id, { requestRunInstruction } = useRequestRunInstruction({
3834
3671
  documentOnChange,
3835
- isDocAssistable: documentIsAssistable != null ? documentIsAssistable : !1
3672
+ isDocAssistable: documentIsAssistable ?? !1
3836
3673
  }), isSelectable = !!useSelectedField(documentSchemaType, typePath), assistSupported = useAssistSupported(props.path, schemaType) && isSelectable && isSchemaAssistEnabled(documentSchemaType) && schemaType.readOnly !== !0, fieldAssist = react.useMemo(
3837
- () => {
3838
- var _a;
3839
- return ((_a = assistDocument == null ? void 0 : assistDocument.fields) != null ? _a : []).find(
3840
- (f) => f.path === typePath || pathKey === documentRootKey && f.path === pathKey
3841
- );
3842
- },
3843
- [assistDocument == null ? void 0 : assistDocument.fields, pathKey, typePath]
3844
- ), fieldAssistKey = fieldAssist == null ? void 0 : fieldAssist._key, isSelected = (inspector == null ? void 0 : inspector.name) === aiInspectorId && pathKey === selectedPath, imageCaptionAction = generateCaptionsActions.useAction(props), imageGenAction = generateImagActions.useAction(props), translateAction = translateActions.useAction(
3674
+ () => (assistDocument?.fields ?? []).find(
3675
+ (f) => f.path === typePath || pathKey === documentRootKey && f.path === pathKey
3676
+ ),
3677
+ [assistDocument?.fields, pathKey, typePath]
3678
+ ), fieldAssistKey = fieldAssist?._key, isSelected = inspector?.name === aiInspectorId && pathKey === selectedPath, imageCaptionAction = generateCaptionsActions.useAction(props), imageGenAction = generateImagActions.useAction(props), translateAction = translateActions.useAction(
3845
3679
  sanity.typed({
3846
3680
  ...props,
3847
3681
  documentId: assistableDocumentId,
@@ -3856,8 +3690,8 @@ const assistFieldActions = {
3856
3690
  [openInspector, closeInspector, isSelected, pathKey]
3857
3691
  ), onInstructionAction = react.useCallback(
3858
3692
  (instruction2) => {
3859
- !pathKey || !fieldAssistKey || !assistDocumentId2 || !assistableDocId || requestRunInstruction({
3860
- documentId: assistableDocId,
3693
+ !pathKey || !fieldAssistKey || !assistDocumentId2 || !assistableDocumentId || requestRunInstruction({
3694
+ documentId: assistableDocumentId,
3861
3695
  assistDocumentId: assistDocumentId2,
3862
3696
  path: pathKey,
3863
3697
  typePath,
@@ -3865,44 +3699,45 @@ const assistFieldActions = {
3865
3699
  conditionalMembers: formStateRef.current ? getConditionalMembers(formStateRef.current) : []
3866
3700
  });
3867
3701
  },
3868
- [requestRunInstruction, assistableDocId, pathKey, typePath, assistDocumentId2, fieldAssistKey]
3702
+ [
3703
+ requestRunInstruction,
3704
+ assistableDocumentId,
3705
+ pathKey,
3706
+ typePath,
3707
+ assistDocumentId2,
3708
+ fieldAssistKey
3709
+ ]
3869
3710
  ), privateInstructions = react.useMemo(
3870
- () => {
3871
- var _a;
3872
- return ((_a = fieldAssist == null ? void 0 : fieldAssist.instructions) == null ? void 0 : _a.filter((i) => i.userId && i.userId === (currentUser == null ? void 0 : currentUser.id))) || [];
3873
- },
3874
- [fieldAssist == null ? void 0 : fieldAssist.instructions, currentUser]
3711
+ () => fieldAssist?.instructions?.filter((i) => i.userId && i.userId === currentUser?.id) || [],
3712
+ [fieldAssist?.instructions, currentUser]
3875
3713
  ), sharedInstructions = react.useMemo(
3876
- () => {
3877
- var _a;
3878
- return ((_a = fieldAssist == null ? void 0 : fieldAssist.instructions) == null ? void 0 : _a.filter((i) => !i.userId)) || [];
3879
- },
3880
- [fieldAssist == null ? void 0 : fieldAssist.instructions]
3714
+ () => fieldAssist?.instructions?.filter((i) => !i.userId) || [],
3715
+ [fieldAssist?.instructions]
3881
3716
  ), instructions = react.useMemo(
3882
3717
  () => [...privateInstructions, ...sharedInstructions],
3883
3718
  [privateInstructions, sharedInstructions]
3884
- ), runInstructionsGroup = react.useMemo(() => instructions != null && instructions.length || imageCaptionAction || translateAction || imageGenAction ? {
3719
+ ), runInstructionsGroup = react.useMemo(() => instructions?.length || imageCaptionAction || translateAction || imageGenAction ? {
3885
3720
  type: "group",
3886
3721
  icon: () => null,
3887
3722
  title: "Run instructions",
3888
3723
  children: [
3889
- ...(instructions == null ? void 0 : instructions.map(
3724
+ ...instructions?.map(
3890
3725
  (instruction2) => instructionItem({
3891
3726
  instruction: instruction2,
3892
- isPrivate: !!(instruction2.userId && instruction2.userId === (currentUser == null ? void 0 : currentUser.id)),
3727
+ isPrivate: !!(instruction2.userId && instruction2.userId === currentUser?.id),
3893
3728
  onInstructionAction,
3894
3729
  hidden: isHidden,
3895
3730
  documentIsNew: !!documentIsNew,
3896
3731
  assistSupported
3897
3732
  })
3898
- )) || [],
3733
+ ) || [],
3899
3734
  imageCaptionAction,
3900
3735
  imageGenAction
3901
3736
  ].filter((a) => !!a),
3902
3737
  expanded: !0
3903
3738
  } : void 0, [
3904
3739
  instructions,
3905
- currentUser == null ? void 0 : currentUser.id,
3740
+ currentUser?.id,
3906
3741
  onInstructionAction,
3907
3742
  isHidden,
3908
3743
  documentIsNew,
@@ -3910,7 +3745,7 @@ const assistFieldActions = {
3910
3745
  imageCaptionAction,
3911
3746
  translateAction,
3912
3747
  imageGenAction
3913
- ]), instructionsLength = (instructions == null ? void 0 : instructions.length) || 0, manageInstructionsItem = react.useMemo(
3748
+ ]), instructionsLength = instructions?.length || 0, manageInstructionsItem = react.useMemo(
3914
3749
  () => ({
3915
3750
  type: "action",
3916
3751
  icon: icons.ControlsIcon,
@@ -3969,30 +3804,24 @@ function instructionItem(props) {
3969
3804
  hidden
3970
3805
  };
3971
3806
  }
3972
- function AssistDocumentContextProvider(props) {
3973
- const { documentId, schemaType } = props, value = useAssistDocumentContextValue(documentId, schemaType);
3974
- return /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentContext.Provider, { value, children: props.children });
3975
- }
3976
3807
  const NO_TASKS = [];
3977
3808
  function useInstructionToaster(documentId, documentSchemaType) {
3978
- const assistDocument = useStudioAssistDocument({ documentId, schemaType: documentSchemaType }), assistDocLoaded = !!assistDocument, currentUser = sanity.useCurrentUser(), toast = ui.useToast(), tasks = assistDocument == null ? void 0 : assistDocument.tasks, previousTasks = react.useRef("initial");
3809
+ const assistDocument = useStudioAssistDocument({ documentId, schemaType: documentSchemaType }), assistDocLoaded = !!assistDocument, currentUser = sanity.useCurrentUser(), toast = ui.useToast(), tasks = assistDocument?.tasks, previousTasks = react.useRef("initial");
3979
3810
  react.useEffect(() => {
3980
- var _a;
3981
3811
  if (assistDocLoaded) {
3982
3812
  if (previousTasks.current !== "initial") {
3983
3813
  const prevTaskByKey = Object.fromEntries(
3984
- ((_a = previousTasks.current) != null ? _a : NO_TASKS).map((run) => [run._key, run])
3985
- ), endedTasks = tasks == null ? void 0 : tasks.filter((task) => task.startedByUserId === (currentUser == null ? void 0 : currentUser.id)).filter((task) => {
3814
+ (previousTasks.current ?? NO_TASKS).map((run) => [run._key, run])
3815
+ );
3816
+ tasks?.filter((task) => task.startedByUserId === currentUser?.id).filter((task) => {
3986
3817
  const prevTask = prevTaskByKey[task._key];
3987
- return !prevTask && task.ended || !(prevTask != null && prevTask.ended) && task.ended;
3988
- }).filter((task) => task.ended && dateFns.isAfter(dateFns.addSeconds(new Date(task.ended), 30), /* @__PURE__ */ new Date()));
3989
- endedTasks == null || endedTasks.forEach((task) => {
3990
- var _a2, _b;
3991
- const title = (_a2 = task.title) != null ? _a2 : getInstructionTitle(task.instruction);
3818
+ return !prevTask && task.ended || !prevTask?.ended && task.ended;
3819
+ }).filter((task) => task.ended && dateFns.isAfter(dateFns.addSeconds(new Date(task.ended), 30), /* @__PURE__ */ new Date()))?.forEach((task) => {
3820
+ const title = task.title ?? getInstructionTitle(task.instruction);
3992
3821
  task.reason === "error" ? toast.push({
3993
3822
  title: `Failed: ${title}`,
3994
3823
  status: "error",
3995
- description: `Instruction failed. ${(_b = task.message) != null ? _b : ""}`,
3824
+ description: `Instruction failed. ${task.message ?? ""}`,
3996
3825
  closable: !0,
3997
3826
  duration: 1e4
3998
3827
  }) : task.reason === "timeout" ? toast.push({
@@ -4018,10 +3847,9 @@ function useInstructionToaster(documentId, documentSchemaType) {
4018
3847
  }, [tasks, previousTasks, toast, currentUser, assistDocLoaded]);
4019
3848
  }
4020
3849
  function AssistDocumentInputWrapper(props) {
4021
- var _a;
4022
3850
  if (!isType(props.schemaType, "document") && props.id !== "root" && props.id !== assistFormId)
4023
3851
  return /* @__PURE__ */ jsxRuntime.jsx(AssistInput, { ...props });
4024
- const documentId = (_a = props.value) == null ? void 0 : _a._id;
3852
+ const documentId = props.value?._id;
4025
3853
  return documentId ? /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentInput, { ...props, documentId }) : props.renderDefault(props);
4026
3854
  }
4027
3855
  function AssistDocumentInput({ documentId, ...props }) {
@@ -4034,33 +3862,23 @@ function AssistDocumentInput({ documentId, ...props }) {
4034
3862
  name: "document"
4035
3863
  }
4036
3864
  }, [props.schemaType]);
4037
- return /* @__PURE__ */ jsxRuntime.jsx(FirstAssistedPathProvider, { members: props.members, children: /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentContextProvider, { schemaType, documentId, children: props.renderDefault({
4038
- ...props,
4039
- schemaType
4040
- }) }) });
3865
+ return /* @__PURE__ */ jsxRuntime.jsx(FirstAssistedPathProvider, { members: props.members, children: props.renderDefault({ ...props, schemaType }) });
4041
3866
  }
4042
3867
  function AssistInput(props) {
4043
3868
  const { zIndex } = ui.useLayer(), { paneKey } = structure.useDocumentPane(), pathKey = usePathKey(props.path);
4044
3869
  return /* @__PURE__ */ jsxRuntime.jsx(ConnectFromRegion, { _key: `${paneKey}_${pathKey}`, zIndex, style: { minWidth: 0 }, children: props.renderDefault(props) });
4045
3870
  }
4046
- function createAssistDocumentPresence(documentId, schemaType) {
3871
+ function createAssistDocumentPresence(documentId) {
4047
3872
  return function() {
4048
- return documentId ? /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentPresence, { documentId, schemaType }) : null;
3873
+ return documentId ? /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentPresence, {}) : null;
4049
3874
  };
4050
3875
  }
4051
- function AssistDocumentPresence(props) {
4052
- const { assistDocument } = useAssistDocumentContextValue(
4053
- props.documentId,
4054
- props.schemaType
4055
- ), anyPresence = react.useMemo(() => {
4056
- var _a, _b, _c, _d;
4057
- 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) => {
4058
- var _a2;
4059
- return (_a2 = run.presence) != null ? _a2 : [];
4060
- }).find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
3876
+ function AssistDocumentPresence() {
3877
+ const { assistDocument } = useAssistDocumentContext(), anyPresence = react.useMemo(() => {
3878
+ const anyPresence2 = assistDocument?.tasks?.filter((run) => !run.ended && !run.reason)?.flatMap((run) => run.presence ?? []).find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4061
3879
  if (anyPresence2)
4062
3880
  return aiPresence(anyPresence2, []);
4063
- 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);
3881
+ const anyRun = assistDocument?.tasks?.filter((run) => !run.ended && !run.reason)?.find((f) => f.started && (/* @__PURE__ */ new Date()).getTime() - new Date(f.started).getTime() < 3e4);
4064
3882
  return anyRun ? aiPresence(
4065
3883
  {
4066
3884
  started: anyRun.started,
@@ -4070,11 +3888,71 @@ function AssistDocumentPresence(props) {
4070
3888
  },
4071
3889
  []
4072
3890
  ) : void 0;
4073
- }, [assistDocument == null ? void 0 : assistDocument.tasks]);
3891
+ }, [assistDocument?.tasks]);
4074
3892
  return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { flex: 1, justify: "flex-end", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { gap: 2, align: "center", children: anyPresence && /* @__PURE__ */ jsxRuntime.jsx(AiFieldPresence, { presence: anyPresence }) }) }) });
4075
3893
  }
3894
+ function useAssistDocumentContextValue(documentId, documentType) {
3895
+ const schema = sanity.useSchema(), documentSchemaType = react.useMemo(() => {
3896
+ const schemaType = schema.get(documentType);
3897
+ if (!schemaType)
3898
+ throw new Error(`Schema type "${documentType}" not found`);
3899
+ return schemaType;
3900
+ }, [documentType, schema]), {
3901
+ openInspector,
3902
+ closeInspector,
3903
+ inspector,
3904
+ onChange: documentOnChange,
3905
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3906
+ // @ts-ignore this is a valid option available in `corel` - Remove after corel is merged to next
3907
+ selectedReleaseId,
3908
+ editState
3909
+ } = structure.useDocumentPane(), { draft, published, version } = editState || {};
3910
+ let assistableDocumentId = version?._id || draft?._id || published?._id;
3911
+ assistableDocumentId || (assistableDocumentId = selectedReleaseId ? sanity.getVersionId(documentId, selectedReleaseId) : documentSchemaType.liveEdit ? documentId : sanity.getDraftId(documentId));
3912
+ const documentIsNew = selectedReleaseId ? !version?._id : !draft?._id && !published?._id, documentIsAssistable = selectedReleaseId ? !!version : isDocAssistable(documentSchemaType, published, draft), { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], assistDocument = useStudioAssistDocument({
3913
+ documentId: assistableDocumentId,
3914
+ schemaType: documentSchemaType
3915
+ });
3916
+ return react.useMemo(() => {
3917
+ const base = {
3918
+ assistableDocumentId,
3919
+ documentSchemaType,
3920
+ documentIsNew,
3921
+ documentIsAssistable,
3922
+ openInspector,
3923
+ closeInspector,
3924
+ inspector,
3925
+ documentOnChange,
3926
+ selectedPath
3927
+ };
3928
+ return assistDocument ? {
3929
+ ...base,
3930
+ loading: !1,
3931
+ assistDocument
3932
+ } : { ...base, loading: !0, assistDocument: void 0 };
3933
+ }, [
3934
+ assistDocument,
3935
+ documentIsAssistable,
3936
+ assistableDocumentId,
3937
+ documentSchemaType,
3938
+ documentIsNew,
3939
+ openInspector,
3940
+ closeInspector,
3941
+ inspector,
3942
+ documentOnChange,
3943
+ selectedPath
3944
+ ]);
3945
+ }
3946
+ function AssistDocumentContextProvider(props) {
3947
+ const { documentId, documentType } = props, value = useAssistDocumentContextValue(documentId, documentType);
3948
+ return /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentContext.Provider, { value, children: props.children });
3949
+ }
3950
+ function AssistDocumentLayout(props) {
3951
+ const { documentId, documentType } = props;
3952
+ return /* @__PURE__ */ jsxRuntime.jsx(AssistDocumentContextProvider, { documentType, documentId, children: props.renderDefault(props) });
3953
+ }
4076
3954
  const assist = sanity.definePlugin((config) => {
4077
- const configWithDefaults = config != null ? config : {};
3955
+ const configWithDefaults = config ?? {};
4078
3956
  return {
4079
3957
  name: packageName,
4080
3958
  schema: {
@@ -4098,7 +3976,10 @@ const assist = sanity.definePlugin((config) => {
4098
3976
  if (schemaType === assistDocumentTypeName)
4099
3977
  return [];
4100
3978
  const docSchema = schema.get(schemaType);
4101
- return docSchema && sanity.isObjectSchemaType(docSchema) && isSchemaAssistEnabled(docSchema) ? [...prev, createAssistDocumentPresence(documentId, docSchema)] : prev;
3979
+ return docSchema && sanity.isObjectSchemaType(docSchema) && isSchemaAssistEnabled(docSchema) ? [...prev, createAssistDocumentPresence(documentId)] : prev;
3980
+ },
3981
+ components: {
3982
+ unstable_layout: AssistDocumentLayout
4102
3983
  }
4103
3984
  },
4104
3985
  studio: {