@sanity/assist 1.0.7 → 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/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';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)}}));}Object.defineProperty(exports,'__esModule',{value:true});var jsxRuntime=require('react/jsx-runtime');var sanity=require('sanity');var ui=require('@sanity/ui');var React=require('react');var icons=require('@sanity/icons');var operators=require('rxjs/operators');var isEqual=require('react-fast-compare');var rxjs=require('rxjs');var rxjsExhaustmapWithTrailing=require('rxjs-exhaustmap-with-trailing');var desk=require('sanity/desk');function _interopDefaultCompat(e){return e&&typeof e==='object'&&'default'in e?e:{default:e};}function _interopNamespaceCompat(e){if(e&&typeof e==='object'&&'default'in e)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k];}});}});}n.default=e;return Object.freeze(n);}var React__namespace=/*#__PURE__*/_interopNamespaceCompat(React);var isEqual__default=/*#__PURE__*/_interopDefaultCompat(isEqual);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)=>rxjs.defer(()=>// getVersionedClient(options.apiVersion)
2
2
  client.observable.fetch(query,params,{tag:options.tag,filterResponse:true}));const listen=(client,query,params,options)=>rxjs.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(operators.mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&!isWelcomeEvent(ev)){return rxjs.throwError(new Error(ev.type==="reconnect"?"Could not establish EventSource connection":"Received unexpected type of first event \"".concat(ev.type,"\"")));}return rxjs.of(ev);}),operators.share());const[welcome$,mutationAndReconnect$]=rxjs.partition(events$,isWelcomeEvent);const isRelevantEvent=event=>{if(!options.transitions||event.type!=="mutation"){return true;}return options.transitions.includes(event.transition);};return rxjs.merge(welcome$.pipe(operators.take(1)),mutationAndReconnect$.pipe(operators.filter(isRelevantEvent),rxjs.switchMap(event=>rxjs.merge(rxjs.of(event),rxjs.of(event).pipe(rxjs.delay(options.throttleTime||1e3)))))).pipe(rxjsExhaustmapWithTrailing.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]=React.useState(true);const[error,setError]=React.useState(false);const[data,setData]=React.useState(null);const subscription=React.useRef(null);const client=sanity.useClient({apiVersion:"v2022-05-09"});React.useEffect(()=>{if(query){subscription.current=listenQuery(client,query,params,options).pipe(operators.distinctUntilChanged(isEqual__default.default),operators.catchError(err=>{console.error(err);setError(err);setLoading(false);setData(null);return err;})).subscribe(documents=>{setData(current=>isEqual__default.default(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(isUnsupportedType(type)){return false;}if(type.jsonType==="array"){const unsupportedArray=type.of.every(t=>isUnsupportedType(t));return!unsupportedArray;}if(type.jsonType==="object"){const unsupportedObject=type.fields.every(field=>isUnsupportedType(field.type));return!unsupportedObject;}return true;}function isUnsupportedType(type){return!isSchemaAssistEnabled(type)||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).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)).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:sanity.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=sanity.useSchema();const client=sanity.useClient({apiVersion:"2023-01-01"});const[saving,setSaving]=React.useState(false);const[syncTitle,setSyncTitle]=React.useState(defaultTitle);const{data}=useListeningQuery("*[_type==$type] | order(_type)",{type:assistSerializedTypeName});const types=React.useMemo(()=>{return serializeSchema(schema);},[schema]);const storeTypes=React.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__ */jsxRuntime.jsx(ui.Card,{padding:4,overflow:"auto",style:{height:"calc(100vh - 81px)"},children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:saving?/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{style:{marginTop:5}}):icons.SyncIcon,text:syncTitle,disabled:saving,onClick:storeTypes})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:2,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Label,{children:"Studio schema"}),/* @__PURE__ */jsxRuntime.jsx("ul",{children:types.map(type=>/* @__PURE__ */jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsx(SchemaEntry,{schemaStub:type})},type.name))})]}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Label,{children:"Stored schema"}),/* @__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))})]})]})]})});}function SchemaEntry(_ref2){let{schemaStub}=_ref2;const out=React.useMemo(()=>JSON.stringify(schemaStub,null,2),[schemaStub]);return/* @__PURE__ */jsxRuntime.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}=desk.useDocumentPane();const documentStore=sanity.useDocumentStore();const presence=sanity.useDocumentPresence(documentId);const patchChannel=React.useMemo(()=>sanity.createPatchChannel(),[]);const isLocked=(_a=editState==null?void 0:editState.transactionSyncLock)==null?void 0:_a.enabled;React.useEffect(()=>{const sub=documentStore.pair.documentEvents(documentId,documentType).pipe(operators.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);React.useEffect(()=>{if(hasRev){patchChannel.publish({type:"mutation",patches:[],snapshot:value});}},[hasRev]);const formRef=React.useRef(null);React.useEffect(()=>{ui.focusFirstDescendant(formRef.current);},[]);if(isLocked){return/* @__PURE__ */jsxRuntime.jsx(ui.Box,{as:"form",...props,ref:formRef,children:/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsxRuntime.jsx(ui.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__ */jsxRuntime.jsx(ui.Box,{as:"form",...props,onSubmit:preventDefault,ref:formRef,children:ready?formState===null?/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"This form is hidden"})}):/* @__PURE__ */jsxRuntime.jsx(sanity.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__ */jsxRuntime.jsxs(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:[/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{muted:true}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{marginTop:3,children:/* @__PURE__ */jsxRuntime.jsx(ui.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:sanity.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:sanity.fromMutationPatches("remote",remotePatches).concat(sanity.fromMutationPatches("local",localPatches))};}const SelectedFieldContext=React.createContext(void 0);const SelectedFieldContextProvider=SelectedFieldContext.Provider;function getTypeIcon(schemaType){let t=schemaType;while(t){if(t.icon)return t.icon;t=t.type;}if(isType(schemaType,"slug"))return icons.LinkIcon;if(isType(schemaType,"image"))return icons.ImageIcon;if(schemaType.jsonType==="array"&&isPortableTextArray(schemaType))return icons.BlockContentIcon;if(schemaType.jsonType==="array")return icons.OlistIcon;if(schemaType.jsonType==="object")return icons.BlockquoteIcon;if(schemaType.jsonType==="string")return icons.StringIcon;return icons.DocumentIcon;}function getFieldRefsWithDocument(schemaType){var _a;const fields=getFieldRefs(schemaType);return[{key:documentRootKey,icon:(_a=schemaType.icon)!=null?_a:icons.DocumentIcon,title:"The entire document",path:[],schemaType},...fields];}function getFieldRefs(schemaType,parent){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:sanity.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):[];if(!isAssistSupported(field.type)){return fields;}return[fieldRef,...fields];});}function useSelectedField(documentSchemaType,path){const selectableFields=React.useMemo(()=>documentSchemaType&&sanity.isObjectSchemaType(documentSchemaType)?getFieldRefsWithDocument(documentSchemaType):[],[documentSchemaType]);return React.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=desk.usePaneRouter();return React.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(operators.mergeMap((ev,i)=>{const isFirst=i===0;if(isFirst&&!isWelcomeEvent(ev)){return rxjs.throwError(new Error(ev.type==="reconnect"?"Could not establish EventSource connection":"Received unexpected type of first event \"".concat(ev.type,"\"")));}return rxjs.of(ev);}),operators.share());const[welcome$,mutationAndReconnect$]=rxjs.partition(events$,isWelcomeEvent);const isRelevantEvent=event=>{if(!options.transitions||event.type!=="mutation"){return true;}return options.transitions.includes(event.transition);};return rxjs.merge(welcome$.pipe(operators.take(1)),mutationAndReconnect$.pipe(operators.filter(isRelevantEvent),rxjs.switchMap(event=>rxjs.merge(rxjs.of(event),rxjs.of(event).pipe(rxjs.delay(options.throttleTime||1e3)))))).pipe(rxjsExhaustmapWithTrailing.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]=React.useState(true);const[error,setError]=React.useState(false);const[data,setData]=React.useState(null);const subscription=React.useRef(null);const client=sanity.useClient({apiVersion:"v2022-05-09"});React.useEffect(()=>{if(query){subscription.current=listenQuery(client,query,params,options).pipe(operators.distinctUntilChanged(isEqual__default.default),operators.catchError(err=>{console.error(err);setError(err);setLoading(false);setData(null);return err;})).subscribe(documents=>{setData(current=>isEqual__default.default(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:sanity.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=sanity.useSchema();const client=sanity.useClient({apiVersion:"2023-01-01"});const[saving,setSaving]=React.useState(false);const[syncTitle,setSyncTitle]=React.useState(defaultTitle);const{data}=useListeningQuery("*[_type==$type] | order(_type)",{type:assistSerializedTypeName});const types=React.useMemo(()=>{return serializeSchema(schema);},[schema]);const storeTypes=React.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__ */jsxRuntime.jsx(ui.Card,{padding:4,overflow:"auto",style:{height:"calc(100vh - 81px)"},children:/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:4,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Box,{children:/* @__PURE__ */jsxRuntime.jsx(ui.Button,{icon:saving?/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{style:{marginTop:5}}):icons.SyncIcon,text:syncTitle,disabled:saving,onClick:storeTypes})}),/* @__PURE__ */jsxRuntime.jsxs(ui.Flex,{gap:2,children:[/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Label,{children:"Studio schema"}),/* @__PURE__ */jsxRuntime.jsx("ul",{children:types.map(type=>/* @__PURE__ */jsxRuntime.jsx("li",{children:/* @__PURE__ */jsxRuntime.jsx(SchemaEntry,{schemaStub:type})},type.name))})]}),/* @__PURE__ */jsxRuntime.jsxs(ui.Stack,{space:2,children:[/* @__PURE__ */jsxRuntime.jsx(ui.Label,{children:"Stored schema"}),/* @__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))})]})]})]})});}function SchemaEntry(_ref2){let{schemaStub}=_ref2;const out=React.useMemo(()=>JSON.stringify(schemaStub,null,2),[schemaStub]);return/* @__PURE__ */jsxRuntime.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}=desk.useDocumentPane();const documentStore=sanity.useDocumentStore();const presence=sanity.useDocumentPresence(documentId);const patchChannel=React.useMemo(()=>sanity.createPatchChannel(),[]);const isLocked=(_a=editState==null?void 0:editState.transactionSyncLock)==null?void 0:_a.enabled;React.useEffect(()=>{const sub=documentStore.pair.documentEvents(documentId,documentType).pipe(operators.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);React.useEffect(()=>{if(hasRev){patchChannel.publish({type:"mutation",patches:[],snapshot:value});}},[hasRev]);const formRef=React.useRef(null);React.useEffect(()=>{ui.focusFirstDescendant(formRef.current);},[]);if(isLocked){return/* @__PURE__ */jsxRuntime.jsx(ui.Box,{as:"form",...props,ref:formRef,children:/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsxRuntime.jsx(ui.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__ */jsxRuntime.jsx(ui.Box,{as:"form",...props,onSubmit:preventDefault,ref:formRef,children:ready?formState===null?/* @__PURE__ */jsxRuntime.jsx(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,children:"This form is hidden"})}):/* @__PURE__ */jsxRuntime.jsx(sanity.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__ */jsxRuntime.jsxs(ui.Flex,{align:"center",direction:"column",height:"fill",justify:"center",padding:3,sizing:"border",children:[/* @__PURE__ */jsxRuntime.jsx(ui.Spinner,{muted:true}),/* @__PURE__ */jsxRuntime.jsx(ui.Box,{marginTop:3,children:/* @__PURE__ */jsxRuntime.jsx(ui.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:sanity.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:sanity.fromMutationPatches("remote",remotePatches).concat(sanity.fromMutationPatches("local",localPatches))};}const SelectedFieldContext=React.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 icons.LinkIcon;if(isType(schemaType,"image"))return icons.ImageIcon;if(schemaType.jsonType==="array"&&isPortableTextArray(schemaType))return icons.BlockContentIcon;if(schemaType.jsonType==="array")return icons.OlistIcon;if(schemaType.jsonType==="object")return icons.BlockquoteIcon;if(schemaType.jsonType==="string")return icons.StringIcon;return icons.DocumentIcon;}function getFieldRefsWithDocument(schemaType){var _a;const fields=getFieldRefs(schemaType);return[{key:documentRootKey,icon:(_a=schemaType.icon)!=null?_a:icons.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:sanity.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=React.useMemo(()=>documentSchemaType&&sanity.isObjectSchemaType(documentSchemaType)?getFieldRefsWithDocument(documentSchemaType):[],[documentSchemaType]);return React.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=desk.usePaneRouter();return React.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:[sanity.defineField({type:"string",name:"title",title:"Title"}),sanity.defineField({type:"array",name:"fields",title:"Fields",of:[{type:fieldInstructions.name}]})],preview:{select:{title:"title"}}});const instructionTask=sanity.defineType({type:"object",name:instructionTaskTypeName,title:"Instruction task",fields:[sanity.defineField({type:"string",name:"path",title:"Path"}),sanity.defineField({type:"string",name:"instructionKey",title:"Instruction key"}),sanity.defineField({type:"datetime",name:"started",title:"Started"}),sanity.defineField({type:"datetime",name:"updated",title:"Updated"}),sanity.defineField({type:"string",name:"info",title:"Info"})]});const documentInstructionStatus=sanity.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:[sanity.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 React.useMemo(()=>path.every(p=>typeof p==="string")&&isAssistSupported(schemaType),[path,schemaType]);}function useAssistDocumentContextValue(documentId,documentSchemaType){const{published,draft}=sanity.useEditState(sanity.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}=desk.useDocumentPane();const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const value=React.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__ */jsxRuntime.jsx(ui.Tooltip,{content:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,style:{whiteSpace:"nowrap"},children:"Only visible to you"}),fallbackPlacements:["bottom"],padding:2,placement:"top",portal:true,children:/* @__PURE__ */jsxRuntime.jsx(icons.LockIcon,{})});}function node(node2){return node2;}const assistFieldActions={name:"sanity-assist-actions",useAction(props){const assistSupported=useAssistSupported(props.path,props.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
2327
+ ...{liveEdit:true},name:assistTasksStatusTypeName,title:"Document instruction status",fields:[sanity.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 React.useMemo(()=>path.every(p=>typeof p==="string")&&isAssistSupported(schemaType),[path,schemaType]);}function useAssistDocumentContextValue(documentId,documentSchemaType){const{published,draft}=sanity.useEditState(sanity.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}=desk.useDocumentPane();const assistDocument=useStudioAssistDocument({documentId,schemaType:documentSchemaType});const value=React.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__ */jsxRuntime.jsx(ui.Tooltip,{content:/* @__PURE__ */jsxRuntime.jsx(ui.Text,{size:1,style:{whiteSpace:"nowrap"},children:"Only visible to you"}),fallbackPlacements:["bottom"],padding:2,placement:"top",portal:true,children:/* @__PURE__ */jsxRuntime.jsx(icons.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,props.schemaType):// eslint-disable-next-line react-hooks/rules-of-hooks
2330
+ useAssistDocumentContextValue(props.documentId,schemaType):// eslint-disable-next-line react-hooks/rules-of-hooks
2331
2331
  useAssistDocumentContext();const currentUser=sanity.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=React.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=React.useCallback(()=>isSelected?closeInspector(aiInspectorId):openInspector(aiInspectorId,{[fieldPathParam]:pathKey,[instructionParam]:void 0}),[openInspector,closeInspector,isSelected,pathKey]);const onInstructionAction=React.useCallback(instruction=>{if(!pathKey||!fieldAssistKey||!assistDocumentId||!assistableDocId){return;}requestRunInstruction({documentId:assistableDocId,assistDocumentId,path:pathKey,instruction});},[requestRunInstruction,assistableDocId,pathKey,assistDocumentId,fieldAssistKey]);const privateInstructions=React.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=React.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=React.useMemo(()=>[...privateInstructions,...sharedInstructions],[privateInstructions,sharedInstructions]);const runInstructionsGroup=React.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=React.useMemo(()=>node({type:"action",icon:icons.ControlsIcon,title:"Manage instructions",onAction:manageInstructions,selected:isSelected}),[manageInstructions,isSelected]);const group=React.useMemo(()=>node({type:"group",icon:icons.SparklesIcon,title:pluginTitleShort,children:[runInstructionsGroup,/* documentIsNew && {
2332
2332
  type: 'action',
2333
2333
  disabled: true,