@sanity/assist 4.4.3 → 4.4.5

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.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { pathToString, getVersionFromId, getPublishedId, isVersionId, useEditState, useCurrentUser, useClient, typed, isObjectSchemaType, stringToPath, isKeySegment, isArraySchemaType, useSchema, FormFieldHeaderText, PatchEvent, unset, getVersionId, getDraftId, useColorSchemeValue, useFormCallbacks, useDocumentStore, useDocumentPresence, createPatchChannel, FormBuilder, fromMutationPatches, StatusButton, PresenceOverlay, VirtualizerScrollInstanceProvider, isDocumentSchemaType, useSyncState, set, useWorkspaceSchemaId, MemberFieldError, FormCallbacksProvider, FormInput, setIfMissing, insert, ObjectInputMember, isArrayOfObjectsSchemaType, defineType, defineField, defineArrayMember, definePlugin } from "sanity";
2
+ import { pathToString, getVersionFromId, getPublishedId, isVersionId, useEditState, useCurrentUser, useClient, typed, isObjectSchemaType, stringToPath, isKeySegment, FormFieldHeaderText, PatchEvent, unset, isArraySchemaType, useSchema, getVersionId, getDraftId, useColorSchemeValue, useFormCallbacks, useDocumentStore, useDocumentPresence, createPatchChannel, FormBuilder, fromMutationPatches, StatusButton, PresenceOverlay, VirtualizerScrollInstanceProvider, isDocumentSchemaType, useSyncState, set, useWorkspaceSchemaId, MemberFieldError, FormCallbacksProvider, FormInput, setIfMissing, insert, ObjectInputMember, isArrayOfObjectsSchemaType, defineType, defineField, defineArrayMember, definePlugin } from "sanity";
3
3
  import { useToast, useLayer, Dialog, Stack, Flex, Tooltip, Text, TextArea, Button, Badge, Popover, Card, Box, ErrorBoundary, focusFirstDescendant, Spinner, Container, Autocomplete, Breadcrumbs, useClickOutside, useGlobalKeyDown, useTheme, rgba, Radio, Checkbox, ThemeProvider, MenuButton, Menu, MenuItem, Switch, Label } from "@sanity/ui";
4
4
  import { useRef, useState, useEffect, useMemo, createContext, useContext, useCallback, useId, forwardRef, createElement, useReducer } from "react";
5
5
  import { useDocumentPane, usePaneRouter, DocumentInspectorHeader, DocumentPaneProvider } from "sanity/structure";
@@ -518,128 +518,6 @@ function AiAssistanceConfigProvider(props) {
518
518
  }), [config, status, init, statusLoading, initLoading, error]);
519
519
  return /* @__PURE__ */ jsx(AiAssistanceConfigContext.Provider, { value: context, children });
520
520
  }
521
- const hiddenTypes = [
522
- "any",
523
- "array",
524
- "block",
525
- "boolean",
526
- "crossDatasetReference",
527
- "date",
528
- "datetime",
529
- "document",
530
- "email",
531
- "file",
532
- "globalDocumentReference",
533
- "image",
534
- "number",
535
- "object",
536
- "reference",
537
- "span",
538
- "string",
539
- "text",
540
- "url",
541
- "slug",
542
- "geopoint",
543
- "sanity.assetSourceData",
544
- "sanity.imageAsset",
545
- "sanity.fileAsset",
546
- "sanity.imageCrop",
547
- "sanity.imageHotspot",
548
- "sanity.imageMetadata",
549
- "sanity.imageDimensions",
550
- "sanity.imagePalette",
551
- "sanity.imagePaletteSwatch",
552
- assistSerializedTypeName,
553
- assistSerializedFieldTypeName,
554
- "sanity-agent.job.document"
555
- ], inlineTypes = ["document", "object", "image", "file"];
556
- function serializeSchema(schema, options2) {
557
- 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));
558
- return list.sort((a, b) => (a?.name ?? "").localeCompare(b?.name ?? "")), list;
559
- }
560
- function getSchemaStub(schemaType, schema, options2) {
561
- if (!schemaType.type?.name)
562
- throw console.error("Missing type name", schemaType.type), new Error("Type is missing name!");
563
- const baseSchema = {
564
- // we dont need type or id when we send using POST, so leave these out to save bandwidth
565
- ...options2?.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
566
- name: schemaType.name,
567
- title: schemaType.title,
568
- type: schemaType.type.name,
569
- ...getBaseFields(schema, schemaType, schemaType.type.name, options2)
570
- };
571
- return removeUndef(baseSchema);
572
- }
573
- function getBaseFields(schema, type, typeName, options2) {
574
- const schemaOptions = removeUndef({
575
- imagePromptField: type.options?.aiAssist?.imageInstructionField,
576
- embeddingsIndex: type.options?.aiAssist?.embeddingsIndex
577
- });
578
- return removeUndef({
579
- options: Object.keys(schemaOptions).length ? schemaOptions : void 0,
580
- values: Array.isArray(type?.options?.list) ? type?.options?.list.map(
581
- (v) => typeof v == "string" ? v : v.value ?? `${v.title}`
582
- ) : void 0,
583
- of: "of" in type && typeName === "array" ? arrayOf(type, schema, options2) : void 0,
584
- to: "to" in type && typeName === "reference" ? refToTypeNames(type) : void 0,
585
- fields: "fields" in type && inlineTypes.includes(typeName) ? serializeFields(schema, type, options2) : void 0,
586
- annotations: typeName === "block" && "fields" in type ? serializeAnnotations(type, schema, options2) : void 0,
587
- inlineOf: typeName === "block" && "fields" in type ? serializeInlineOf(type, schema, options2) : void 0,
588
- hidden: typeof type.hidden == "function" ? "function" : type.hidden ? !0 : void 0,
589
- readOnly: typeof type.readOnly == "function" ? "function" : type.readOnly ? !0 : void 0
590
- });
591
- }
592
- function serializeFields(schema, schemaType, options2) {
593
- return (schemaType.fieldsets ? schemaType.fieldsets.flatMap(
594
- (fs) => fs.single ? fs.field : fs.fields.map((f) => ({
595
- ...f,
596
- type: {
597
- ...f.type,
598
- // if fieldset is (conditionally) hidden, the field must be considered the same way
599
- // ie, if the field does not show up in conditionalMembers, it is hidden
600
- // regardless of weather or not it is the field function or the fieldset function that hides it
601
- hidden: typeof fs.hidden == "function" ? fs.hidden : fs.hidden ? !0 : f.type.hidden
602
- }
603
- }))
604
- ) : 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));
605
- }
606
- function serializeMember(schema, type, name, options2) {
607
- const typeName = schema.get(type?.name) ? type.name : type.type?.name ?? "";
608
- return removeUndef({
609
- ...options2?.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
610
- name,
611
- type: typeName,
612
- title: type.title,
613
- ...getBaseFields(schema, type, typeName, options2)
614
- });
615
- }
616
- function serializeInlineOf(blockSchemaType, schema, options2) {
617
- const childrenType = blockSchemaType.fields.find((f) => f.name === "children")?.type;
618
- if (!(!childrenType || !isArraySchemaType(childrenType)))
619
- return arrayOf(
620
- {
621
- of: childrenType.of.filter((t) => !isType(t, "span"))
622
- },
623
- schema,
624
- options2
625
- );
626
- }
627
- function serializeAnnotations(blockSchemaType, schema, options2) {
628
- const marksType = blockSchemaType.fields.find((f) => f.name === "markDefs")?.type;
629
- if (!(!marksType || !isArraySchemaType(marksType)))
630
- return arrayOf(marksType, schema, options2);
631
- }
632
- function arrayOf(arrayType, schema, options2) {
633
- return arrayType.of.filter((type) => isAssistSupported(type)).map((t) => serializeMember(schema, t, t.name, options2));
634
- }
635
- function refToTypeNames(type) {
636
- return type.to.map((t) => ({
637
- type: typed(t.name)
638
- }));
639
- }
640
- function removeUndef(obj) {
641
- return Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {}), obj;
642
- }
643
521
  const basePath = "/assist/tasks/instruction", API_VERSION_WITH_EXTENDED_TYPES = "2025-04-01";
644
522
  function canUseAssist(status) {
645
523
  return status?.enabled && status.initialized && status.validToken;
@@ -652,7 +530,7 @@ function useApiClient(customApiClient) {
652
530
  );
653
531
  }
654
532
  function useTranslate(apiClient) {
655
- const [loading, setLoading] = useState(!1), user = useCurrentUser(), schema = useSchema(), types = useMemo(() => serializeSchema(schema, { leanFormat: !0 }), [schema]), toast = useToast(), translate = useCallback(
533
+ const [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), translate = useCallback(
656
534
  ({
657
535
  documentId,
658
536
  languagePath,
@@ -701,7 +579,7 @@ function useTranslate(apiClient) {
701
579
  );
702
580
  }
703
581
  function useGenerateCaption(apiClient) {
704
- const [loading, setLoading] = useState(!1), user = useCurrentUser(), schema = useSchema(), types = useMemo(() => serializeSchema(schema, { leanFormat: !0 }), [schema]), toast = useToast(), generateCaption = useCallback(
582
+ const [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), generateCaption = useCallback(
705
583
  ({ path, documentId }) => (setLoading(!0), apiClient.request({
706
584
  method: "POST",
707
585
  url: `/assist/tasks/generate-caption/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
@@ -733,7 +611,7 @@ function useGenerateCaption(apiClient) {
733
611
  );
734
612
  }
735
613
  function useGenerateImage(apiClient) {
736
- const [loading, setLoading] = useState(!1), user = useCurrentUser(), schema = useSchema(), types = useMemo(() => serializeSchema(schema, { leanFormat: !0 }), [schema]), toast = useToast(), generateImage = useCallback(
614
+ const [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), generateImage = useCallback(
737
615
  ({ path, documentId }) => (setLoading(!0), apiClient.request({
738
616
  method: "POST",
739
617
  url: `/assist/tasks/generate-image/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
@@ -795,7 +673,7 @@ function useInitInstruct(apiClient) {
795
673
  };
796
674
  }
797
675
  function useRunInstructionApi(apiClient) {
798
- const toast = useToast(), [loading, setLoading] = useState(!1), user = useCurrentUser(), schema = useSchema(), types = useMemo(() => serializeSchema(schema, { leanFormat: !0 }), [schema]), {
676
+ const toast = useToast(), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), {
799
677
  config: { assist: assistConfig }
800
678
  } = useAiAssistanceConfig(), runInstruction = useCallback(
801
679
  (request) => {
@@ -1018,13 +896,144 @@ function useDraftDelayedTask(args) {
1018
896
  [setQueuedArgs, documentOnChange]
1019
897
  );
1020
898
  }
899
+ const hiddenTypes = [
900
+ "any",
901
+ "array",
902
+ "block",
903
+ "boolean",
904
+ "crossDatasetReference",
905
+ "date",
906
+ "datetime",
907
+ "document",
908
+ "email",
909
+ "file",
910
+ "globalDocumentReference",
911
+ "image",
912
+ "number",
913
+ "object",
914
+ "reference",
915
+ "span",
916
+ "string",
917
+ "text",
918
+ "url",
919
+ "slug",
920
+ "geopoint",
921
+ "sanity.assetSourceData",
922
+ "sanity.imageAsset",
923
+ "sanity.fileAsset",
924
+ "sanity.imageCrop",
925
+ "sanity.imageHotspot",
926
+ "sanity.imageMetadata",
927
+ "sanity.imageDimensions",
928
+ "sanity.imagePalette",
929
+ "sanity.imagePaletteSwatch",
930
+ assistSerializedTypeName,
931
+ assistSerializedFieldTypeName,
932
+ "sanity-agent.job.document"
933
+ ], inlineTypes = ["document", "object", "image", "file"];
934
+ function serializeSchema(schema, options2) {
935
+ 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));
936
+ return list.sort((a, b) => (a?.name ?? "").localeCompare(b?.name ?? "")), list;
937
+ }
938
+ function getSchemaStub(schemaType, schema, options2) {
939
+ if (!schemaType.type?.name)
940
+ throw console.error("Missing type name", schemaType.type), new Error("Type is missing name!");
941
+ const baseSchema = {
942
+ // we dont need type or id when we send using POST, so leave these out to save bandwidth
943
+ ...options2?.leanFormat ? {} : { _id: `${assistSchemaIdPrefix}${schemaType.name}`, _type: assistSerializedTypeName },
944
+ name: schemaType.name,
945
+ title: schemaType.title,
946
+ type: schemaType.type.name,
947
+ ...getBaseFields(schema, schemaType, schemaType.type.name, options2)
948
+ };
949
+ return removeUndef(baseSchema);
950
+ }
951
+ function getBaseFields(schema, type, typeName, options2) {
952
+ const schemaOptions = removeUndef({
953
+ imagePromptField: type.options?.aiAssist?.imageInstructionField,
954
+ embeddingsIndex: type.options?.aiAssist?.embeddingsIndex
955
+ });
956
+ return removeUndef({
957
+ options: Object.keys(schemaOptions).length ? schemaOptions : void 0,
958
+ values: Array.isArray(type?.options?.list) ? type?.options?.list.map(
959
+ (v) => typeof v == "string" ? v : v.value ?? `${v.title}`
960
+ ) : void 0,
961
+ of: "of" in type && typeName === "array" ? arrayOf(type, schema, options2) : void 0,
962
+ to: "to" in type && typeName === "reference" ? refToTypeNames(type) : void 0,
963
+ fields: "fields" in type && inlineTypes.includes(typeName) ? serializeFields(schema, type, options2) : void 0,
964
+ annotations: typeName === "block" && "fields" in type ? serializeAnnotations(type, schema, options2) : void 0,
965
+ inlineOf: typeName === "block" && "fields" in type ? serializeInlineOf(type, schema, options2) : void 0,
966
+ hidden: typeof type.hidden == "function" ? "function" : type.hidden ? !0 : void 0,
967
+ readOnly: typeof type.readOnly == "function" ? "function" : type.readOnly ? !0 : void 0
968
+ });
969
+ }
970
+ function serializeFields(schema, schemaType, options2) {
971
+ return (schemaType.fieldsets ? schemaType.fieldsets.flatMap(
972
+ (fs) => fs.single ? fs.field : fs.fields.map((f) => ({
973
+ ...f,
974
+ type: {
975
+ ...f.type,
976
+ // if fieldset is (conditionally) hidden, the field must be considered the same way
977
+ // ie, if the field does not show up in conditionalMembers, it is hidden
978
+ // regardless of weather or not it is the field function or the fieldset function that hides it
979
+ hidden: typeof fs.hidden == "function" ? fs.hidden : fs.hidden ? !0 : f.type.hidden
980
+ }
981
+ }))
982
+ ) : 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));
983
+ }
984
+ function serializeMember(schema, type, name, options2) {
985
+ const typeName = schema.get(type?.name) ? type.name : type.type?.name ?? "";
986
+ return removeUndef({
987
+ ...options2?.leanFormat ? {} : { _type: assistSerializedFieldTypeName },
988
+ name,
989
+ type: typeName,
990
+ title: type.title,
991
+ ...getBaseFields(schema, type, typeName, options2)
992
+ });
993
+ }
994
+ function serializeInlineOf(blockSchemaType, schema, options2) {
995
+ const childrenType = blockSchemaType.fields.find((f) => f.name === "children")?.type;
996
+ if (!(!childrenType || !isArraySchemaType(childrenType)))
997
+ return arrayOf(
998
+ {
999
+ of: childrenType.of.filter((t) => !isType(t, "span"))
1000
+ },
1001
+ schema,
1002
+ options2
1003
+ );
1004
+ }
1005
+ function serializeAnnotations(blockSchemaType, schema, options2) {
1006
+ const marksType = blockSchemaType.fields.find((f) => f.name === "markDefs")?.type;
1007
+ if (!(!marksType || !isArraySchemaType(marksType)))
1008
+ return arrayOf(marksType, schema, options2);
1009
+ }
1010
+ function arrayOf(arrayType, schema, options2) {
1011
+ return arrayType.of.filter((type) => isAssistSupported(type)).map((t) => serializeMember(schema, t, t.name, options2));
1012
+ }
1013
+ function refToTypeNames(type) {
1014
+ return type.to.map((t) => ({
1015
+ type: typed(t.name)
1016
+ }));
1017
+ }
1018
+ function removeUndef(obj) {
1019
+ return Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {}), obj;
1020
+ }
1021
+ function useSerializedTypes() {
1022
+ return useAssistDocumentContext().serializedTypes;
1023
+ }
1021
1024
  function useAssistDocumentContextValue(documentId, documentType) {
1022
1025
  const schema = useSchema(), documentSchemaType = useMemo(() => {
1023
1026
  const schemaType = schema.get(documentType);
1024
1027
  if (!schemaType)
1025
1028
  throw new Error(`Schema type "${documentType}" not found`);
1026
1029
  return schemaType;
1027
- }, [documentType, schema]), {
1030
+ }, [documentType, schema]), serializedTypes = useMemo(() => serializeSchema(schema, { leanFormat: !0 }), [schema]), { fieldRefs, fieldRefsByTypePath } = useMemo(() => {
1031
+ const fieldRefs2 = getFieldRefs(documentSchemaType), fieldRefsByTypePath2 = asFieldRefsByTypePath(fieldRefs2);
1032
+ return {
1033
+ fieldRefs: fieldRefs2,
1034
+ fieldRefsByTypePath: fieldRefsByTypePath2
1035
+ };
1036
+ }, [documentSchemaType]), {
1028
1037
  openInspector,
1029
1038
  closeInspector,
1030
1039
  inspector,
@@ -1036,7 +1045,7 @@ function useAssistDocumentContextValue(documentId, documentType) {
1036
1045
  } = useDocumentPane(), { draft, published, version } = editState || {}, assistableDocumentId = selectedReleaseId ? getVersionId(documentId, selectedReleaseId) : documentSchemaType.liveEdit ? documentId : getDraftId(documentId), documentIsNew = selectedReleaseId ? !version?._id : !draft?._id && !published?._id, documentIsAssistable = selectedReleaseId ? !!version : isDocAssistable(documentSchemaType, published, draft), { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], assistDocument = useStudioAssistDocument({
1037
1046
  documentId: assistableDocumentId,
1038
1047
  schemaType: documentSchemaType
1039
- }), { syntheticTasks, addSyntheticTask, removeSyntheticTask } = useSyntheticTasks(assistableDocumentId), fieldRefs = getFieldRefs(documentSchemaType), fieldRefsByTypePath = asFieldRefsByTypePath(fieldRefs);
1048
+ }), { syntheticTasks, addSyntheticTask, removeSyntheticTask } = useSyntheticTasks(assistableDocumentId);
1040
1049
  return useMemo(() => {
1041
1050
  const base = {
1042
1051
  assistableDocumentId,
@@ -1052,7 +1061,8 @@ function useAssistDocumentContextValue(documentId, documentType) {
1052
1061
  addSyntheticTask,
1053
1062
  removeSyntheticTask,
1054
1063
  fieldRefs,
1055
- fieldRefsByTypePath
1064
+ fieldRefsByTypePath,
1065
+ serializedTypes
1056
1066
  };
1057
1067
  return assistDocument ? {
1058
1068
  ...base,
@@ -1072,7 +1082,10 @@ function useAssistDocumentContextValue(documentId, documentType) {
1072
1082
  selectedPath,
1073
1083
  syntheticTasks,
1074
1084
  addSyntheticTask,
1075
- removeSyntheticTask
1085
+ removeSyntheticTask,
1086
+ fieldRefs,
1087
+ fieldRefsByTypePath,
1088
+ serializedTypes
1076
1089
  ]);
1077
1090
  }
1078
1091
  function useSyntheticTasks(assistableDocumentId) {