@sanity/assist 1.0.8 → 1.0.9
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/README.md +3 -0
- package/dist/index.esm.js +4 -4
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/assistInspector/helpers.ts +1 -1
- package/src/fieldActions/assistFieldActions.tsx +4 -2
- package/src/helpers/assistSupported.ts +15 -5
- package/src/schemas/serialize/serializeSchema.test.ts +26 -0
- package/src/schemas/serialize/serializeSchema.ts +2 -0
package/README.md
CHANGED
|
@@ -160,6 +160,9 @@ The following types are not supported, and behave as excluded types:
|
|
|
160
160
|
* [Image](https://www.sanity.io/docs/image-type) (supported when image has custom fields)
|
|
161
161
|
* [File](https://www.sanity.io/docs/file-type) (never supported, even when file has custom fields)
|
|
162
162
|
|
|
163
|
+
Types and fields with `hidden` or `readonly` with a truthy value (`true` or `function`) are not supported.
|
|
164
|
+
(Hidden and readOnly fields can be referenced in instructions still)
|
|
165
|
+
|
|
163
166
|
Fields with these types will not be changed by the assistant, do not have AI Assist actions, and cannot be referenced in instructions.
|
|
164
167
|
|
|
165
168
|
Objects where all fields are excluded or unsupported and arrays where all member types are excluded or unsupported
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var _templateObject,_templateObject2,_templateObject3,_templateObject4,_templateObject5,_templateObject6,_templateObject7,_templateObject8,_templateObject9,_templateObject10;function _taggedTemplateLiteral(strings,raw){if(!raw){raw=strings.slice(0);}return Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}));}import{jsx,jsxs,Fragment}from'react/jsx-runtime';import{useClient,typed,useSchema,useDocumentStore,useDocumentPresence,createPatchChannel,FormBuilder,fromMutationPatches,pathToString,isObjectSchemaType,useEditState,useCurrentUser,useValidationStatus,StatusButton,FormFieldHeaderText,PatchEvent,unset,PresenceOverlay,VirtualizerScrollInstanceProvider,stringToPath,isKeySegment,useColorSchemeValue,isArraySchemaType,useFormCallbacks,set,FormCallbacksProvider,FormInput,setIfMissing,insert,ObjectInputMember,defineType,defineField,defineArrayMember,getPublishedId,definePlugin}from'sanity';import{Card,Stack,Box,Button,Spinner,Flex,Label,focusFirstDescendant,Text,useClickOutside,Popover,useLayer,useGlobalKeyDown,useToast,Dialog,Tooltip,TextArea,Container,Badge,useTheme,rgba as rgba$1,ThemeProvider,ErrorBoundary,Switch,MenuButton,Menu,MenuItem,Breadcrumbs,Autocomplete}from'@sanity/ui';import*as React from'react';import React__default,{useState,useRef,useEffect,useMemo,useCallback,createContext,useContext,createElement,useReducer,forwardRef,useId,useLayoutEffect,useInsertionEffect}from'react';import{SyncIcon,DocumentIcon,LinkIcon,ImageIcon,BlockContentIcon,OlistIcon,BlockquoteIcon,StringIcon,ErrorOutlineIcon,CheckmarkCircleIcon,CloseCircleIcon,ClockIcon,PlayIcon,SparklesIcon,RetryIcon,ArrowRightIcon,CloseIcon,CheckmarkIcon,ArrowLeftIcon,icons,SearchIcon,TokenIcon,DocumentTextIcon,ThListIcon,CodeIcon,ComposeIcon,LockIcon,ControlsIcon}from'@sanity/icons';import{mergeMap,share,take,filter as filter$1,distinctUntilChanged,catchError,tap}from'rxjs/operators';import isEqual from'react-fast-compare';import{throwError,of,partition,merge,switchMap,delay as delay$1,defer}from'rxjs';import{exhaustMapToWithTrailing}from'rxjs-exhaustmap-with-trailing';import{useDocumentPane,usePaneRouter,DocumentInspectorHeader,DocumentPaneProvider}from'sanity/desk';const assistDocumentIdPrefix="sanity.assist.schemaType.";const assistDocumentStatusIdPrefix="sanity.assist.status.";const assistSchemaIdPrefix="sanity.assist.schema.";const assistDocumentTypeName="sanity.assist.schemaType.annotations";const assistFieldTypeName="sanity.assist.schemaType.field";const instructionTypeName="sanity.assist.instruction";const promptTypeName="sanity.assist.instruction.prompt";const userInputTypeName="sanity.assist.instruction.userInput";const instructionContextTypeName="sanity.assist.instruction.context";const fieldReferenceTypeName="sanity.assist.instruction.fieldRef";const contextDocumentTypeName="assist.instruction.context";const assistTasksStatusTypeName="sanity.assist.task.status";const instructionTaskTypeName="sanity.assist.instructionTask";const fieldPresenceTypeName="sanity.assist.instructionTask.presence";const assistSerializedTypeName="sanity.assist.serialized.type";const assistSerializedFieldTypeName="sanity.assist.serialized.field";const fieldPathParam="pathKey";const instructionParam="instruction";const documentRootKey="<document>";const fetch=(client,query,params,options)=>defer(()=>// getVersionedClient(options.apiVersion)
|
|
2
2
|
client.observable.fetch(query,params,{tag:options.tag,filterResponse:true}));const listen=(client,query,params,options)=>defer(()=>// getVersionedClient(options.apiVersion)
|
|
3
|
-
client.listen(query,params,{events:["welcome","mutation","reconnect"],includeResult:false,visibility:"query",tag:options.tag}));function isWelcomeEvent(event){return event.type==="welcome";}const listenQuery=function(client,query){let params=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};let options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};const fetchQuery=typeof query==="string"?query:query.fetch;const listenerQuery=typeof query==="string"?query:query.listen;const fetchOnce$=fetch(client,fetchQuery,params,options);const events$=listen(client,listenerQuery,params,options).pipe(mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&!isWelcomeEvent(ev)){return throwError(new Error(ev.type==="reconnect"?"Could not establish EventSource connection":"Received unexpected type of first event \"".concat(ev.type,"\"")));}return of(ev);}),share());const[welcome$,mutationAndReconnect$]=partition(events$,isWelcomeEvent);const isRelevantEvent=event=>{if(!options.transitions||event.type!=="mutation"){return true;}return options.transitions.includes(event.transition);};return merge(welcome$.pipe(take(1)),mutationAndReconnect$.pipe(filter$1(isRelevantEvent),switchMap(event=>merge(of(event),of(event).pipe(delay$1(options.throttleTime||1e3)))))).pipe(exhaustMapToWithTrailing(fetchOnce$));};const DEFAULT_PARAMS={};const DEFAULT_OPTIONS={apiVersion:"v2022-05-09"};function useListeningQuery(query){let params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_PARAMS;let options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_OPTIONS;const[loading,setLoading]=useState(true);const[error,setError]=useState(false);const[data,setData]=useState(null);const subscription=useRef(null);const client=useClient({apiVersion:"v2022-05-09"});useEffect(()=>{if(query){subscription.current=listenQuery(client,query,params,options).pipe(distinctUntilChanged(isEqual),catchError(err=>{console.error(err);setError(err);setLoading(false);setData(null);return err;})).subscribe(documents=>{setData(current=>isEqual(current,documents)?current:documents);setLoading(false);setError(false);});}return()=>{return subscription.current?subscription.current.unsubscribe():void 0;};},[query,params,options,client]);return{loading,error,data};}const hiddenTypes=["any","array","block","boolean","crossDatasetReference","date","datetime","document","email","file","image","number","object","reference","span","string","text","url","slug","geopoint","sanity.assetSourceData","sanity.imageAsset","sanity.fileAsset","sanity.imageCrop","sanity.imageHotspot","sanity.imageMetadata","sanity.imageDimensions","sanity.imagePalette","sanity.imagePaletteSwatch",assistSerializedTypeName,assistSerializedFieldTypeName,"sanity-agent.job.document"];function isPortableTextArray(type){return type.of.find(t=>isType(t,"block"));}function isType(schemaType,typeName){if(schemaType.name===typeName){return true;}if(!schemaType.type){return false;}return isType(schemaType.type,typeName);}function isSchemaAssistEnabled(type){var _a,_b;return!((_b=(_a=type.options)==null?void 0:_a.aiWritingAssistance)==null?void 0:_b.exclude);}function isAssistSupported(type){if(!isSchemaAssistEnabled(type)){return false;}if(
|
|
4
|
-
...((options==null?void 0:options.leanFormat)?{}:{_id:"".concat(assistSchemaIdPrefix).concat(schemaType.name),_type:assistSerializedTypeName}),name:schemaType.name,title:schemaType.title,type:schemaType.type.name,...getBaseFields(schema,schemaType,schemaType.type.name,options)};return removeUndef(baseSchema);}function getBaseFields(schema,type,typeName,options){var _a,_b,_c;const imagePromptField=(_a=type.options)==null?void 0:_a.imagePromptField;return removeUndef({options:imagePromptField?{imagePromptField}:void 0,values:type.jsonType==="string"&&((_b=type==null?void 0:type.options)==null?void 0:_b.list)?(_c=type==null?void 0:type.options)==null?void 0:_c.list.map(v=>{var _a2;return typeof v==="string"?v:(_a2=v.value)!=null?_a2:"".concat(v.title);}):void 0,of:"of"in type&&typeName==="array"?arrayOf(type,schema,options):void 0,to:"to"in type&&typeName==="reference"?refToTypeNames(type):void 0,fields:"fields"in type&&inlineTypes.includes(typeName)?serializeFields(schema,type,options):void 0});}function serializeFields(schema,schemaType,options){return schemaType.fields.filter(f=>{var _a,_b;return!["sanity.imageHotspot","sanity.imageCrop"].includes((_b=(_a=f.type)==null?void 0:_a.name)!=null?_b:"");}).filter(f=>isAssistSupported(f.type)).map(field=>serializeMember(schema,field.type,field.name,options));}function serializeMember(schema,type,name,options){var _a,_b;const typeNameExists=!!schema.get(type==null?void 0:type.name);const typeName=typeNameExists?type.name:(_b=(_a=type.type)==null?void 0:_a.name)!=null?_b:"";return removeUndef({...((options==null?void 0:options.leanFormat)?{}:{_type:assistSerializedFieldTypeName}),name,type:typeName,title:type.title,...getBaseFields(schema,type,typeName,options)});}function arrayOf(arrayType,schema,options){return arrayType.of.filter(type=>isAssistSupported(type)).map(t=>{return serializeMember(schema,t,t.name,options);});}function refToTypeNames(type){return type.to.map(t=>({type:typed(t.name)}));}function removeUndef(obj){Object.keys(obj).forEach(key=>obj[key]===void 0?delete obj[key]:{});return obj;}const NO_DATA=[];const defaultTitle="Sync schema";function SchemaTypeTool(){const schema=useSchema();const client=useClient({apiVersion:"2023-01-01"});const[saving,setSaving]=useState(false);const[syncTitle,setSyncTitle]=useState(defaultTitle);const{data}=useListeningQuery("*[_type==$type] | order(_type)",{type:assistSerializedTypeName});const types=useMemo(()=>{return serializeSchema(schema);},[schema]);const storeTypes=useCallback(()=>{setSaving(true);let canSave=true;async function store(){setSyncTitle("Syncing 0/".concat(types.length));const transaction=client.transaction();for(let i=0;i<types.length;i++){if(!canSave){break;}const type=types[i];await transaction.createOrReplace(type);if(i>0&&i%50===0){await transaction.commit();transaction.reset();setSyncTitle("Syncing ".concat(i,"/").concat(types.length));}}await transaction.commit();}store().catch(console.error).finally(()=>{setSaving(false);setSyncTitle(defaultTitle);});return()=>{canSave=false;setSaving(false);setSyncTitle(defaultTitle);};},[types,client,setSaving,setSyncTitle]);return/* @__PURE__ */jsx(Card,{padding:4,overflow:"auto",style:{height:"calc(100vh - 81px)"},children:/* @__PURE__ */jsxs(Stack,{space:4,children:[/* @__PURE__ */jsx(Box,{children:/* @__PURE__ */jsx(Button,{icon:saving?/* @__PURE__ */jsx(Spinner,{style:{marginTop:5}}):SyncIcon,text:syncTitle,disabled:saving,onClick:storeTypes})}),/* @__PURE__ */jsxs(Flex,{gap:2,children:[/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Studio schema"}),/* @__PURE__ */jsx("ul",{children:types.map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]}),/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Stored schema"}),/* @__PURE__ */jsx("ul",{children:(data!=null?data:NO_DATA).map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]})]})]})});}function SchemaEntry(_ref2){let{schemaStub}=_ref2;const out=useMemo(()=>JSON.stringify(schemaStub,null,2),[schemaStub]);return/* @__PURE__ */jsx("pre",{children:out});}const aiInspectorId="ai-assistance";const preventDefault=ev=>ev.preventDefault();function DocumentForm(props){var _a;const{collapsedFieldSets,collapsedPaths,displayed:value,documentId,documentType,editState,formState,onBlur,onChange,onFocus,onPathOpen,onSetActiveFieldGroup,onSetCollapsedFieldSet,onSetCollapsedPath,ready,validation}=useDocumentPane();const documentStore=useDocumentStore();const presence=useDocumentPresence(documentId);const patchChannel=useMemo(()=>createPatchChannel(),[]);const isLocked=(_a=editState==null?void 0:editState.transactionSyncLock)==null?void 0:_a.enabled;useEffect(()=>{const sub=documentStore.pair.documentEvents(documentId,documentType).pipe(tap(event=>{if(event.type==="mutation"){patchChannel.publish(prepareMutationEvent(event));}if(event.type==="rebase"){patchChannel.publish(prepareRebaseEvent(event));}})).subscribe();return()=>{sub.unsubscribe();};},[documentId,documentStore,documentType,patchChannel]);const hasRev=Boolean(value==null?void 0:value._rev);useEffect(()=>{if(hasRev){patchChannel.publish({type:"mutation",patches:[],snapshot:value});}},[hasRev]);const formRef=useRef(null);useEffect(()=>{focusFirstDescendant(formRef.current);},[]);if(isLocked){return/* @__PURE__ */jsx(Box,{as:"form",...props,ref:formRef,children:/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"Please hold tight while the document is synced. This usually happens right after the document has been published, and it shouldn\u2019t take more than a few seconds"})})});}return/* @__PURE__ */jsx(Box,{as:"form",...props,onSubmit:preventDefault,ref:formRef,children:ready?formState===null?/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"This form is hidden"})}):/* @__PURE__ */jsx(FormBuilder,{__internal_patchChannel:patchChannel,collapsedFieldSets,collapsedPaths,focusPath:formState.focusPath,changed:formState.changed,focused:formState.focused,groups:formState.groups,id:"root",members:formState.members,onChange,onFieldGroupSelect:onSetActiveFieldGroup,onPathBlur:onBlur,onPathFocus:onFocus,onPathOpen,onSetFieldSetCollapsed:onSetCollapsedFieldSet,onSetPathCollapsed:onSetCollapsedPath,presence,readOnly:formState.readOnly,schemaType:formState.schemaType,validation,value:formState.value}):/* @__PURE__ */jsxs(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:[/* @__PURE__ */jsx(Spinner,{muted:true}),/* @__PURE__ */jsx(Box,{marginTop:3,children:/* @__PURE__ */jsx(Text,{align:"center",muted:true,size:1,children:"Loading document"})})]})});}function prepareMutationEvent(event){const patches=event.mutations.map(mut=>mut.patch).filter(Boolean);return{type:"mutation",snapshot:event.document,patches:fromMutationPatches(event.origin,patches)};}function prepareRebaseEvent(event){const remotePatches=event.remoteMutations.map(mut=>mut.patch).filter(Boolean);const localPatches=event.localMutations.map(mut=>mut.patch).filter(Boolean);return{type:"rebase",snapshot:event.document,patches:fromMutationPatches("remote",remotePatches).concat(fromMutationPatches("local",localPatches))};}const SelectedFieldContext=createContext(void 0);const SelectedFieldContextProvider=SelectedFieldContext.Provider;const maxDepth$1=4;function getTypeIcon(schemaType){let t=schemaType;while(t){if(t.icon)return t.icon;t=t.type;}if(isType(schemaType,"slug"))return LinkIcon;if(isType(schemaType,"image"))return ImageIcon;if(schemaType.jsonType==="array"&&isPortableTextArray(schemaType))return BlockContentIcon;if(schemaType.jsonType==="array")return OlistIcon;if(schemaType.jsonType==="object")return BlockquoteIcon;if(schemaType.jsonType==="string")return StringIcon;return DocumentIcon;}function getFieldRefsWithDocument(schemaType){var _a;const fields=getFieldRefs(schemaType);return[{key:documentRootKey,icon:(_a=schemaType.icon)!=null?_a:DocumentIcon,title:"The entire document",path:[],schemaType},...fields];}function getFieldRefs(schemaType,parent){let depth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;if(depth>=maxDepth$1){return[];}return schemaType.fields.filter(f=>!f.name.startsWith("_")).flatMap(field=>{var _a;const path=parent?[...parent.path,field.name]:[field.name];const title=(_a=field.type.title)!=null?_a:field.name;const fieldRef={key:pathToString(path),path,title:parent?[parent.title,title].join(" / "):title,schemaType:field.type,icon:getTypeIcon(field.type)};const fields=field.type.jsonType==="object"?getFieldRefs(field.type,fieldRef,depth+1):[];if(!isAssistSupported(field.type)){return fields;}return[fieldRef,...fields];});}function useSelectedField(documentSchemaType,path){const selectableFields=useMemo(()=>documentSchemaType&&isObjectSchemaType(documentSchemaType)?getFieldRefsWithDocument(documentSchemaType):[],[documentSchemaType]);return useMemo(()=>{return path?selectableFields==null?void 0:selectableFields.find(f=>f.key===path):void 0;},[selectableFields,path]);}function getFieldTitle(field){var _a,_b;const schemaType=field==null?void 0:field.schemaType;return(_b=(_a=schemaType==null?void 0:schemaType.title)!=null?_a:schemaType==null?void 0:schemaType.name)!=null?_b:"Untitled";}function useAiPaneRouter(){const paneRouter=usePaneRouter();return useMemo(()=>{var _a;return{...paneRouter,params:(_a=paneRouter.params)!=null?_a:{}};},[paneRouter]);}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}var reactIs$2={exports:{}};var reactIs_production_min$1={};/**
|
|
3
|
+
client.listen(query,params,{events:["welcome","mutation","reconnect"],includeResult:false,visibility:"query",tag:options.tag}));function isWelcomeEvent(event){return event.type==="welcome";}const listenQuery=function(client,query){let params=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};let options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};const fetchQuery=typeof query==="string"?query:query.fetch;const listenerQuery=typeof query==="string"?query:query.listen;const fetchOnce$=fetch(client,fetchQuery,params,options);const events$=listen(client,listenerQuery,params,options).pipe(mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&!isWelcomeEvent(ev)){return throwError(new Error(ev.type==="reconnect"?"Could not establish EventSource connection":"Received unexpected type of first event \"".concat(ev.type,"\"")));}return of(ev);}),share());const[welcome$,mutationAndReconnect$]=partition(events$,isWelcomeEvent);const isRelevantEvent=event=>{if(!options.transitions||event.type!=="mutation"){return true;}return options.transitions.includes(event.transition);};return merge(welcome$.pipe(take(1)),mutationAndReconnect$.pipe(filter$1(isRelevantEvent),switchMap(event=>merge(of(event),of(event).pipe(delay$1(options.throttleTime||1e3)))))).pipe(exhaustMapToWithTrailing(fetchOnce$));};const DEFAULT_PARAMS={};const DEFAULT_OPTIONS={apiVersion:"v2022-05-09"};function useListeningQuery(query){let params=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_PARAMS;let options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_OPTIONS;const[loading,setLoading]=useState(true);const[error,setError]=useState(false);const[data,setData]=useState(null);const subscription=useRef(null);const client=useClient({apiVersion:"v2022-05-09"});useEffect(()=>{if(query){subscription.current=listenQuery(client,query,params,options).pipe(distinctUntilChanged(isEqual),catchError(err=>{console.error(err);setError(err);setLoading(false);setData(null);return err;})).subscribe(documents=>{setData(current=>isEqual(current,documents)?current:documents);setLoading(false);setError(false);});}return()=>{return subscription.current?subscription.current.unsubscribe():void 0;};},[query,params,options,client]);return{loading,error,data};}const hiddenTypes=["any","array","block","boolean","crossDatasetReference","date","datetime","document","email","file","image","number","object","reference","span","string","text","url","slug","geopoint","sanity.assetSourceData","sanity.imageAsset","sanity.fileAsset","sanity.imageCrop","sanity.imageHotspot","sanity.imageMetadata","sanity.imageDimensions","sanity.imagePalette","sanity.imagePaletteSwatch",assistSerializedTypeName,assistSerializedFieldTypeName,"sanity-agent.job.document"];function isPortableTextArray(type){return type.of.find(t=>isType(t,"block"));}function isType(schemaType,typeName){if(schemaType.name===typeName){return true;}if(!schemaType.type){return false;}return isType(schemaType.type,typeName);}function isSchemaAssistEnabled(type){var _a,_b;return!((_b=(_a=type.options)==null?void 0:_a.aiWritingAssistance)==null?void 0:_b.exclude);}function isAssistSupported(type){let allowReadonlyHidden=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!isSchemaAssistEnabled(type)){return false;}if(isDisabled(type,allowReadonlyHidden)){return false;}if(type.jsonType==="array"){const unsupportedArray=type.of.every(t=>isDisabled(t,allowReadonlyHidden));return!unsupportedArray;}if(type.jsonType==="object"){const unsupportedObject=type.fields.every(field=>isDisabled(field.type,allowReadonlyHidden));return!unsupportedObject;}return true;}function isDisabled(type,allowReadonlyHidden){const readonlyHidden=!!type.readOnly||!!type.hidden;return!isSchemaAssistEnabled(type)||isUnsupportedType(type)||!allowReadonlyHidden&&readonlyHidden;}function isUnsupportedType(type){return type.jsonType==="number"||type.name==="sanity.imageCrop"||type.name==="sanity.imageHotspot"||isType(type,"reference")||isType(type,"crossDatasetReference")||isType(type,"slug")||isType(type,"url")||isType(type,"date")||isType(type,"datetime")||isType(type,"file");}const inlineTypes=["document","object","image","file"];function serializeSchema(schema,options){const list=schema.getTypeNames().filter(t=>!(hiddenTypes.includes(t)||t.startsWith("sanity."))).map(t=>schema.get(t)).filter(t=>!!t).filter(t=>!t.hidden&&!t.readOnly).map(t=>getSchemaStub(t,schema,options)).filter(t=>{if("to"in t&&t.to&&!t.to.length){return false;}if("of"in t&&t.of&&!t.of.length){return false;}if("fields"in t&&t.fields&&!t.fields.length){return false;}return true;});list.sort((a,b)=>{var _a,_b;return((_a=a==null?void 0:a.name)!=null?_a:"").localeCompare((_b=b==null?void 0:b.name)!=null?_b:"");});return list;}function getSchemaStub(schemaType,schema,options){var _a;if(!((_a=schemaType.type)==null?void 0:_a.name)){console.error("Missing type name",schemaType.type);throw new Error("Type is missing name!");}const baseSchema={// we dont need type or id when we send using POST, so leave these out to save bandwidth
|
|
4
|
+
...((options==null?void 0:options.leanFormat)?{}:{_id:"".concat(assistSchemaIdPrefix).concat(schemaType.name),_type:assistSerializedTypeName}),name:schemaType.name,title:schemaType.title,type:schemaType.type.name,...getBaseFields(schema,schemaType,schemaType.type.name,options)};return removeUndef(baseSchema);}function getBaseFields(schema,type,typeName,options){var _a,_b,_c;const imagePromptField=(_a=type.options)==null?void 0:_a.imagePromptField;return removeUndef({options:imagePromptField?{imagePromptField}:void 0,values:type.jsonType==="string"&&((_b=type==null?void 0:type.options)==null?void 0:_b.list)?(_c=type==null?void 0:type.options)==null?void 0:_c.list.map(v=>{var _a2;return typeof v==="string"?v:(_a2=v.value)!=null?_a2:"".concat(v.title);}):void 0,of:"of"in type&&typeName==="array"?arrayOf(type,schema,options):void 0,to:"to"in type&&typeName==="reference"?refToTypeNames(type):void 0,fields:"fields"in type&&inlineTypes.includes(typeName)?serializeFields(schema,type,options):void 0});}function serializeFields(schema,schemaType,options){return schemaType.fields.filter(f=>{var _a,_b;return!["sanity.imageHotspot","sanity.imageCrop"].includes((_b=(_a=f.type)==null?void 0:_a.name)!=null?_b:"");}).filter(f=>isAssistSupported(f.type)).filter(f=>!f.type.hidden&&!f.type.readOnly).map(field=>serializeMember(schema,field.type,field.name,options));}function serializeMember(schema,type,name,options){var _a,_b;const typeNameExists=!!schema.get(type==null?void 0:type.name);const typeName=typeNameExists?type.name:(_b=(_a=type.type)==null?void 0:_a.name)!=null?_b:"";return removeUndef({...((options==null?void 0:options.leanFormat)?{}:{_type:assistSerializedFieldTypeName}),name,type:typeName,title:type.title,...getBaseFields(schema,type,typeName,options)});}function arrayOf(arrayType,schema,options){return arrayType.of.filter(type=>isAssistSupported(type)).map(t=>{return serializeMember(schema,t,t.name,options);});}function refToTypeNames(type){return type.to.map(t=>({type:typed(t.name)}));}function removeUndef(obj){Object.keys(obj).forEach(key=>obj[key]===void 0?delete obj[key]:{});return obj;}const NO_DATA=[];const defaultTitle="Sync schema";function SchemaTypeTool(){const schema=useSchema();const client=useClient({apiVersion:"2023-01-01"});const[saving,setSaving]=useState(false);const[syncTitle,setSyncTitle]=useState(defaultTitle);const{data}=useListeningQuery("*[_type==$type] | order(_type)",{type:assistSerializedTypeName});const types=useMemo(()=>{return serializeSchema(schema);},[schema]);const storeTypes=useCallback(()=>{setSaving(true);let canSave=true;async function store(){setSyncTitle("Syncing 0/".concat(types.length));const transaction=client.transaction();for(let i=0;i<types.length;i++){if(!canSave){break;}const type=types[i];await transaction.createOrReplace(type);if(i>0&&i%50===0){await transaction.commit();transaction.reset();setSyncTitle("Syncing ".concat(i,"/").concat(types.length));}}await transaction.commit();}store().catch(console.error).finally(()=>{setSaving(false);setSyncTitle(defaultTitle);});return()=>{canSave=false;setSaving(false);setSyncTitle(defaultTitle);};},[types,client,setSaving,setSyncTitle]);return/* @__PURE__ */jsx(Card,{padding:4,overflow:"auto",style:{height:"calc(100vh - 81px)"},children:/* @__PURE__ */jsxs(Stack,{space:4,children:[/* @__PURE__ */jsx(Box,{children:/* @__PURE__ */jsx(Button,{icon:saving?/* @__PURE__ */jsx(Spinner,{style:{marginTop:5}}):SyncIcon,text:syncTitle,disabled:saving,onClick:storeTypes})}),/* @__PURE__ */jsxs(Flex,{gap:2,children:[/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Studio schema"}),/* @__PURE__ */jsx("ul",{children:types.map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]}),/* @__PURE__ */jsxs(Stack,{space:2,children:[/* @__PURE__ */jsx(Label,{children:"Stored schema"}),/* @__PURE__ */jsx("ul",{children:(data!=null?data:NO_DATA).map(type=>/* @__PURE__ */jsx("li",{children:/* @__PURE__ */jsx(SchemaEntry,{schemaStub:type})},type.name))})]})]})]})});}function SchemaEntry(_ref2){let{schemaStub}=_ref2;const out=useMemo(()=>JSON.stringify(schemaStub,null,2),[schemaStub]);return/* @__PURE__ */jsx("pre",{children:out});}const aiInspectorId="ai-assistance";const preventDefault=ev=>ev.preventDefault();function DocumentForm(props){var _a;const{collapsedFieldSets,collapsedPaths,displayed:value,documentId,documentType,editState,formState,onBlur,onChange,onFocus,onPathOpen,onSetActiveFieldGroup,onSetCollapsedFieldSet,onSetCollapsedPath,ready,validation}=useDocumentPane();const documentStore=useDocumentStore();const presence=useDocumentPresence(documentId);const patchChannel=useMemo(()=>createPatchChannel(),[]);const isLocked=(_a=editState==null?void 0:editState.transactionSyncLock)==null?void 0:_a.enabled;useEffect(()=>{const sub=documentStore.pair.documentEvents(documentId,documentType).pipe(tap(event=>{if(event.type==="mutation"){patchChannel.publish(prepareMutationEvent(event));}if(event.type==="rebase"){patchChannel.publish(prepareRebaseEvent(event));}})).subscribe();return()=>{sub.unsubscribe();};},[documentId,documentStore,documentType,patchChannel]);const hasRev=Boolean(value==null?void 0:value._rev);useEffect(()=>{if(hasRev){patchChannel.publish({type:"mutation",patches:[],snapshot:value});}},[hasRev]);const formRef=useRef(null);useEffect(()=>{focusFirstDescendant(formRef.current);},[]);if(isLocked){return/* @__PURE__ */jsx(Box,{as:"form",...props,ref:formRef,children:/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"Please hold tight while the document is synced. This usually happens right after the document has been published, and it shouldn\u2019t take more than a few seconds"})})});}return/* @__PURE__ */jsx(Box,{as:"form",...props,onSubmit:preventDefault,ref:formRef,children:ready?formState===null?/* @__PURE__ */jsx(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsx(Text,{size:1,children:"This form is hidden"})}):/* @__PURE__ */jsx(FormBuilder,{__internal_patchChannel:patchChannel,collapsedFieldSets,collapsedPaths,focusPath:formState.focusPath,changed:formState.changed,focused:formState.focused,groups:formState.groups,id:"root",members:formState.members,onChange,onFieldGroupSelect:onSetActiveFieldGroup,onPathBlur:onBlur,onPathFocus:onFocus,onPathOpen,onSetFieldSetCollapsed:onSetCollapsedFieldSet,onSetPathCollapsed:onSetCollapsedPath,presence,readOnly:formState.readOnly,schemaType:formState.schemaType,validation,value:formState.value}):/* @__PURE__ */jsxs(Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:[/* @__PURE__ */jsx(Spinner,{muted:true}),/* @__PURE__ */jsx(Box,{marginTop:3,children:/* @__PURE__ */jsx(Text,{align:"center",muted:true,size:1,children:"Loading document"})})]})});}function prepareMutationEvent(event){const patches=event.mutations.map(mut=>mut.patch).filter(Boolean);return{type:"mutation",snapshot:event.document,patches:fromMutationPatches(event.origin,patches)};}function prepareRebaseEvent(event){const remotePatches=event.remoteMutations.map(mut=>mut.patch).filter(Boolean);const localPatches=event.localMutations.map(mut=>mut.patch).filter(Boolean);return{type:"rebase",snapshot:event.document,patches:fromMutationPatches("remote",remotePatches).concat(fromMutationPatches("local",localPatches))};}const SelectedFieldContext=createContext(void 0);const SelectedFieldContextProvider=SelectedFieldContext.Provider;const maxDepth$1=4;function getTypeIcon(schemaType){let t=schemaType;while(t){if(t.icon)return t.icon;t=t.type;}if(isType(schemaType,"slug"))return LinkIcon;if(isType(schemaType,"image"))return ImageIcon;if(schemaType.jsonType==="array"&&isPortableTextArray(schemaType))return BlockContentIcon;if(schemaType.jsonType==="array")return OlistIcon;if(schemaType.jsonType==="object")return BlockquoteIcon;if(schemaType.jsonType==="string")return StringIcon;return DocumentIcon;}function getFieldRefsWithDocument(schemaType){var _a;const fields=getFieldRefs(schemaType);return[{key:documentRootKey,icon:(_a=schemaType.icon)!=null?_a:DocumentIcon,title:"The entire document",path:[],schemaType},...fields];}function getFieldRefs(schemaType,parent){let depth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;if(depth>=maxDepth$1){return[];}return schemaType.fields.filter(f=>!f.name.startsWith("_")).flatMap(field=>{var _a;const path=parent?[...parent.path,field.name]:[field.name];const title=(_a=field.type.title)!=null?_a:field.name;const fieldRef={key:pathToString(path),path,title:parent?[parent.title,title].join(" / "):title,schemaType:field.type,icon:getTypeIcon(field.type)};const fields=field.type.jsonType==="object"?getFieldRefs(field.type,fieldRef,depth+1):[];if(!isAssistSupported(field.type,true)){return fields;}return[fieldRef,...fields];});}function useSelectedField(documentSchemaType,path){const selectableFields=useMemo(()=>documentSchemaType&&isObjectSchemaType(documentSchemaType)?getFieldRefsWithDocument(documentSchemaType):[],[documentSchemaType]);return useMemo(()=>{return path?selectableFields==null?void 0:selectableFields.find(f=>f.key===path):void 0;},[selectableFields,path]);}function getFieldTitle(field){var _a,_b;const schemaType=field==null?void 0:field.schemaType;return(_b=(_a=schemaType==null?void 0:schemaType.title)!=null?_a:schemaType==null?void 0:schemaType.name)!=null?_b:"Untitled";}function useAiPaneRouter(){const paneRouter=usePaneRouter();return useMemo(()=>{var _a;return{...paneRouter,params:(_a=paneRouter.params)!=null?_a:{}};},[paneRouter]);}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}var reactIs$2={exports:{}};var reactIs_production_min$1={};/**
|
|
5
5
|
* @license React
|
|
6
6
|
* react-is.production.min.js
|
|
7
7
|
*
|
|
@@ -2324,10 +2324,10 @@ function getRandomValues(typedArray){return window.crypto.getRandomValues(typedA
|
|
|
2324
2324
|
type:"object",//workaround for using object and not document
|
|
2325
2325
|
...{liveEdit:true},name:assistDocumentTypeName,title:"AI Document",components:{input:AssistDocumentForm,field:props=>{return props.renderDefault({...props,title:""});}},fields:[defineField({type:"string",name:"title",title:"Title"}),defineField({type:"array",name:"fields",title:"Fields",of:[{type:fieldInstructions.name}]})],preview:{select:{title:"title"}}});const instructionTask=defineType({type:"object",name:instructionTaskTypeName,title:"Instruction task",fields:[defineField({type:"string",name:"path",title:"Path"}),defineField({type:"string",name:"instructionKey",title:"Instruction key"}),defineField({type:"datetime",name:"started",title:"Started"}),defineField({type:"datetime",name:"updated",title:"Updated"}),defineField({type:"string",name:"info",title:"Info"})]});const documentInstructionStatus=defineType({//NOTE: this is a document type. Using object here ensures it does not appear in structure menus
|
|
2326
2326
|
type:"object",//workaround for using object and not document
|
|
2327
|
-
...{liveEdit:true},name:assistTasksStatusTypeName,title:"Document instruction status",fields:[defineField({type:"array",name:"tasks",title:"Tasks",of:[{type:instructionTask.name}]})]});const schemaTypes=[fieldInstructions,assistDocumentSchema,prompt,fieldReference,instruction,documentInstructionStatus,instructionTask,contextDocumentSchema,userInput,promptContext];function useAssistSupported(path,schemaType){return useMemo(()=>path.every(p=>typeof p==="string")&&isAssistSupported(schemaType),[path,schemaType]);}function useAssistDocumentContextValue(documentId,documentSchemaType){const{published,draft}=useEditState(getPublishedId(documentId),documentSchemaType.name,"low");const assistableDocumentId=(draft==null?void 0:draft._id)||(published==null?void 0:published._id)||documentId;const documentIsNew=Boolean(!(draft==null?void 0:draft._id)&&!(published==null?void 0:published._id));const documentIsAssistable=isDocAssistable(documentSchemaType,published,draft);const{params}=useAiPaneRouter();const selectedPath=params[fieldPathParam];const{openInspector,closeInspector,inspector,onChange:documentOnChange}=useDocumentPane();const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const value=useMemo(()=>{const base={documentId,assistableDocumentId,documentSchemaType,documentIsNew,documentIsAssistable,openInspector,closeInspector,inspector,documentOnChange,selectedPath};if(!assistDocument){return{...base,loading:true,assistDocument:void 0};}return{...base,loading:false,assistDocument};},[assistDocument,documentIsAssistable,documentId,assistableDocumentId,documentSchemaType,documentIsNew,openInspector,closeInspector,inspector,documentOnChange,selectedPath]);return value;}function PrivateIcon(){return/* @__PURE__ */jsx(Tooltip,{content:/* @__PURE__ */jsx(Text,{size:1,style:{whiteSpace:"nowrap"},children:"Only visible to you"}),fallbackPlacements:["bottom"],padding:2,placement:"top",portal:true,children:/* @__PURE__ */jsx(LockIcon,{})});}function node(node2){return node2;}const assistFieldActions={name:"sanity-assist-actions",useAction(props){const assistSupported=useAssistSupported(props.path,
|
|
2327
|
+
...{liveEdit:true},name:assistTasksStatusTypeName,title:"Document instruction status",fields:[defineField({type:"array",name:"tasks",title:"Tasks",of:[{type:instructionTask.name}]})]});const schemaTypes=[fieldInstructions,assistDocumentSchema,prompt,fieldReference,instruction,documentInstructionStatus,instructionTask,contextDocumentSchema,userInput,promptContext];function useAssistSupported(path,schemaType){return useMemo(()=>path.every(p=>typeof p==="string")&&isAssistSupported(schemaType),[path,schemaType]);}function useAssistDocumentContextValue(documentId,documentSchemaType){const{published,draft}=useEditState(getPublishedId(documentId),documentSchemaType.name,"low");const assistableDocumentId=(draft==null?void 0:draft._id)||(published==null?void 0:published._id)||documentId;const documentIsNew=Boolean(!(draft==null?void 0:draft._id)&&!(published==null?void 0:published._id));const documentIsAssistable=isDocAssistable(documentSchemaType,published,draft);const{params}=useAiPaneRouter();const selectedPath=params[fieldPathParam];const{openInspector,closeInspector,inspector,onChange:documentOnChange}=useDocumentPane();const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const value=useMemo(()=>{const base={documentId,assistableDocumentId,documentSchemaType,documentIsNew,documentIsAssistable,openInspector,closeInspector,inspector,documentOnChange,selectedPath};if(!assistDocument){return{...base,loading:true,assistDocument:void 0};}return{...base,loading:false,assistDocument};},[assistDocument,documentIsAssistable,documentId,assistableDocumentId,documentSchemaType,documentIsNew,openInspector,closeInspector,inspector,documentOnChange,selectedPath]);return value;}function PrivateIcon(){return/* @__PURE__ */jsx(Tooltip,{content:/* @__PURE__ */jsx(Text,{size:1,style:{whiteSpace:"nowrap"},children:"Only visible to you"}),fallbackPlacements:["bottom"],padding:2,placement:"top",portal:true,children:/* @__PURE__ */jsx(LockIcon,{})});}function node(node2){return node2;}const assistFieldActions={name:"sanity-assist-actions",useAction(props){const{schemaType}=props;const assistSupported=useAssistSupported(props.path,schemaType);const isDocumentLevel=props.path.length===0;const{assistDocument,documentIsNew,documentIsAssistable,openInspector,closeInspector,inspector,documentOnChange,documentSchemaType,documentId,selectedPath}=// document field actions do not have access to the document context
|
|
2328
2328
|
// conditional hook _should_ be safe here since the logical path will be stable
|
|
2329
2329
|
isDocumentLevel?// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
2330
|
-
useAssistDocumentContextValue(props.documentId,
|
|
2330
|
+
useAssistDocumentContextValue(props.documentId,schemaType):// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
2331
2331
|
useAssistDocumentContext();const currentUser=useCurrentUser();const isHidden=!assistDocument;const pathKey=usePathKey(props.path);const assistDocumentId=assistDocument==null?void 0:assistDocument._id;const assistableDocId=getAssistableDocId(documentSchemaType,documentId);const{requestRunInstruction}=useRequestRunInstruction({documentOnChange,isDocAssistable:documentIsAssistable!=null?documentIsAssistable:false});const fieldAssist=useMemo(()=>{var _a;return((_a=assistDocument==null?void 0:assistDocument.fields)!=null?_a:[]).find(f=>f.path==pathKey);},[assistDocument==null?void 0:assistDocument.fields,pathKey]);const fieldAssistKey=fieldAssist==null?void 0:fieldAssist._key;const isInspectorOpen=(inspector==null?void 0:inspector.name)===aiInspectorId;const isPathSelected=pathKey===selectedPath;const isSelected=isInspectorOpen&&isPathSelected;const manageInstructions=useCallback(()=>isSelected?closeInspector(aiInspectorId):openInspector(aiInspectorId,{[fieldPathParam]:pathKey,[instructionParam]:void 0}),[openInspector,closeInspector,isSelected,pathKey]);const onInstructionAction=useCallback(instruction=>{if(!pathKey||!fieldAssistKey||!assistDocumentId||!assistableDocId){return;}requestRunInstruction({documentId:assistableDocId,assistDocumentId,path:pathKey,instruction});},[requestRunInstruction,assistableDocId,pathKey,assistDocumentId,fieldAssistKey]);const privateInstructions=useMemo(()=>{var _a;return((_a=fieldAssist==null?void 0:fieldAssist.instructions)==null?void 0:_a.filter(i=>i.userId&&i.userId===(currentUser==null?void 0:currentUser.id)))||[];},[fieldAssist==null?void 0:fieldAssist.instructions,currentUser]);const sharedInstructions=useMemo(()=>{var _a;return((_a=fieldAssist==null?void 0:fieldAssist.instructions)==null?void 0:_a.filter(i=>!i.userId))||[];},[fieldAssist==null?void 0:fieldAssist.instructions]);const instructions=useMemo(()=>[...privateInstructions,...sharedInstructions],[privateInstructions,sharedInstructions]);const runInstructionsGroup=useMemo(()=>{return(instructions==null?void 0:instructions.length)?node({type:"group",icon:()=>null,title:"Run instructions",children:instructions.map(instruction=>instructionItem({instruction,isPrivate:Boolean(instruction.userId&&instruction.userId===(currentUser==null?void 0:currentUser.id)),onInstructionAction,hidden:isHidden,documentIsNew:!!documentIsNew,assistSupported})),expanded:true}):void 0;},[instructions,currentUser==null?void 0:currentUser.id,onInstructionAction,isHidden,documentIsNew,assistSupported]);const instructionsLength=(instructions==null?void 0:instructions.length)||0;const manageInstructionsItem=useMemo(()=>node({type:"action",icon:ControlsIcon,title:"Manage instructions",onAction:manageInstructions,selected:isSelected}),[manageInstructions,isSelected]);const group=useMemo(()=>node({type:"group",icon:SparklesIcon,title:pluginTitleShort,children:[runInstructionsGroup,/* documentIsNew && {
|
|
2332
2332
|
type: 'action',
|
|
2333
2333
|
disabled: true,
|