@sanity/assist
Version:
You create the instructions; Sanity AI Assist does the rest.
1,112 lines • 211 kB
JavaScript
import { FormBuilder, FormCallbacksProvider, FormFieldHeaderText, FormInput, MemberFieldError, ObjectInputMember, PatchEvent, PerspectiveProvider, PresenceOverlay, StatusButton, VirtualizerScrollInstanceProvider, createPatchChannel, defineArrayMember, defineField, definePlugin, defineType, fromMutationPatches, getDraftId, getPublishedId, getVersionFromId, getVersionId, insert, isArrayOfObjectsSchemaType, isArraySchemaType, isDocumentSchemaType, isKeySegment, isObjectSchemaType, isRecord, isVersionId, pathToString, set, setIfMissing, stringToPath, typed, unset, useClient, useColorSchemeValue, useCurrentUser, useDocumentPresence, useDocumentStore, useEditState, useFormCallbacks, usePerspective, useSchema, useSyncState, useWorkspaceSchemaId } from "sanity";
import { c } from "react/compiler-runtime";
import { Autocomplete, Box, Breadcrumbs, Button, Card, Checkbox, Container, Dialog, ErrorBoundary, Flex, Label, Menu, MenuButton, MenuItem, Popover, Radio, Spinner, Stack, Switch, Text, TextArea, ThemeProvider, Tooltip, focusFirstDescendant, rgba, useClickOutside, useGlobalKeyDown, useLayer, useTheme, useToast } from "@sanity/ui";
import { createContext, isValidElement, useCallback, useContext, useEffect, useEffectEvent, useId, useMemo, useReducer, useRef, useState } from "react";
import { DocumentInspectorHeader, DocumentPaneProvider, useDocumentPane, usePaneRouter } from "sanity/structure";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { addSeconds, formatDistanceToNow, isAfter, minutesToMilliseconds } from "date-fns";
import { BlockContentIcon } from "@sanity/icons/BlockContent";
import { BlockquoteIcon } from "@sanity/icons/Blockquote";
import { DocumentIcon } from "@sanity/icons/Document";
import { ImageIcon } from "@sanity/icons/Image";
import { LinkIcon } from "@sanity/icons/Link";
import { OlistIcon } from "@sanity/icons/Olist";
import { StringIcon } from "@sanity/icons/String";
import { extractWithPath } from "@sanity/mutator";
import { PlayIcon } from "@sanity/icons/Play";
import { keyframes, styled } from "styled-components";
import { purple } from "@sanity/color";
import { SparklesIcon } from "@sanity/icons/Sparkles";
import { ArrowRightIcon } from "@sanity/icons/ArrowRight";
import { CloseIcon } from "@sanity/icons/Close";
import { RetryIcon } from "@sanity/icons/Retry";
import { catchError, distinctUntilChanged, filter, mergeMap, share, take, tap } from "rxjs/operators";
import { SearchIcon } from "@sanity/icons/Search";
import { CheckmarkCircleIcon } from "@sanity/icons/CheckmarkCircle";
import { ClockIcon } from "@sanity/icons/Clock";
import { CloseCircleIcon } from "@sanity/icons/CloseCircle";
import { ErrorOutlineIcon } from "@sanity/icons/ErrorOutline";
import { SyncIcon } from "@sanity/icons/Sync";
import get from "lodash-es/get.js";
import { Icon, icons } from "@sanity/icons";
import { ControlsIcon } from "@sanity/icons/Controls";
import { TranslateIcon } from "@sanity/icons/Translate";
import { LockIcon } from "@sanity/icons/Lock";
import { CodeIcon } from "@sanity/icons/Code";
import { ComposeIcon } from "@sanity/icons/Compose";
import { ThListIcon } from "@sanity/icons/ThList";
import { ArrowLeftIcon } from "@sanity/icons/ArrowLeft";
import { DocumentTextIcon } from "@sanity/icons/DocumentText";
import { TokenIcon } from "@sanity/icons/Token";
import isEqual from "react-fast-compare";
import { defer, delay, merge, of, partition, switchMap, throwError } from "rxjs";
import { exhaustMapToWithTrailing } from "rxjs-exhaustmap-with-trailing";
function hasOverflowScroll(el) {
let overflow = getComputedStyle(el).overflow;
return overflow.includes("auto") || overflow.includes("hidden") || overflow.includes("scroll");
}
function useRegionRects() {
let $ = c(13), ref = useRef(null), [relativeBoundsRect, setRelativeBoundsRect] = useState(null), [relativeElementRect, setRelativeElementRect] = useState(null), t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
x: 0,
y: 0
}, $[0] = t0) : t0 = $[0];
let [boundsScroll, setBoundsScroll] = useState(t0), t1;
$[1] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
x: 0,
y: 0
}, $[1] = t1) : t1 = $[1];
let [scroll, setScroll] = useState(t1), boundsScrollXRef = useRef(0), boundsScrollYRef = useRef(0), elementScrollXRef = useRef(0), elementScrollYRef = useRef(0), t2, t3;
$[2] === Symbol.for("react.memo_cache_sentinel") ? (t2 = () => {
let el = ref.current;
if (!el) return;
let scrollParents = [], parent = el.parentElement;
for (; parent && parent !== document.body;) hasOverflowScroll(parent) && scrollParents.push(parent), parent = parent.parentElement;
let handleResize = function() {
let boundsRect = scrollParents[0]?.getBoundingClientRect() || {
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight
}, domRect = el.getBoundingClientRect();
setRelativeBoundsRect({
x: boundsRect.x + boundsScrollXRef.current,
y: boundsRect.y + boundsScrollYRef.current,
w: boundsRect.width,
h: boundsRect.height
}), setRelativeElementRect({
x: domRect.x + elementScrollXRef.current,
y: domRect.y + elementScrollYRef.current,
w: domRect.width,
h: domRect.height
});
}, handleScroll = function() {
let scrollX = window.scrollX, scrollY = window.scrollY;
for (let scrollParent_0 of scrollParents) scrollX += scrollParent_0.scrollLeft, scrollY += scrollParent_0.scrollTop;
let scrollParent_1 = scrollParents[0];
boundsScrollXRef.current = scrollX - (scrollParent_1?.scrollLeft || window.scrollX), boundsScrollYRef.current = scrollY - (scrollParent_1?.scrollTop || window.scrollY), setBoundsScroll({
x: boundsScrollXRef.current,
y: boundsScrollYRef.current
}), elementScrollXRef.current = scrollX, elementScrollYRef.current = scrollY, setScroll({
x: scrollX,
y: scrollY
});
};
window.addEventListener("scroll", handleScroll, { passive: !0 });
let ro = new ResizeObserver(handleResize);
ro.observe(el);
for (let scrollParent_2 of scrollParents) scrollParent_2.addEventListener("scroll", handleScroll, { passive: !0 }), ro.observe(scrollParent_2);
return handleScroll(), () => {
ro.unobserve(el);
for (let scrollParent_3 of scrollParents) ro.unobserve(scrollParent_3), scrollParent_3.removeEventListener("scroll", handleScroll);
ro.disconnect(), window.removeEventListener("scroll", handleScroll);
};
}, t3 = [], $[2] = t2, $[3] = t3) : (t2 = $[2], t3 = $[3]), useEffect(t2, t3);
let t4;
$[4] !== boundsScroll || $[5] !== relativeBoundsRect ? (t4 = relativeBoundsRect && {
x: relativeBoundsRect.x - boundsScroll.x,
y: relativeBoundsRect.y - boundsScroll.y,
w: relativeBoundsRect.w,
h: relativeBoundsRect.h
}, $[4] = boundsScroll, $[5] = relativeBoundsRect, $[6] = t4) : t4 = $[6];
let bounds = t4, t5;
$[7] !== relativeElementRect || $[8] !== scroll ? (t5 = relativeElementRect && {
x: relativeElementRect.x - scroll.x,
y: relativeElementRect.y - scroll.y,
w: relativeElementRect.w,
h: relativeElementRect.h
}, $[7] = relativeElementRect, $[8] = scroll, $[9] = t5) : t5 = $[9];
let element = t5, t6;
return $[10] !== bounds || $[11] !== element ? (t6 = {
bounds,
element,
ref
}, $[10] = bounds, $[11] = element, $[12] = t6) : t6 = $[12], t6;
}
function ConnectorRegion(props) {
let $ = c(13), children, onRectsChange, restProps;
$[0] === props ? (children = $[1], onRectsChange = $[2], restProps = $[3]) : ({children, onRectsChange, ...restProps} = props, $[0] = props, $[1] = children, $[2] = onRectsChange, $[3] = restProps);
let { bounds, element, ref } = useRegionRects(), t0, t1;
$[4] !== bounds || $[5] !== element || $[6] !== onRectsChange ? (t0 = () => {
onRectsChange?.(bounds && element ? {
bounds,
element
} : null);
}, t1 = [
bounds,
element,
onRectsChange
], $[4] = bounds, $[5] = element, $[6] = onRectsChange, $[7] = t0, $[8] = t1) : (t0 = $[7], t1 = $[8]), useEffect(t0, t1);
let t2;
return $[9] !== children || $[10] !== ref || $[11] !== restProps ? (t2 = /* @__PURE__ */ jsx("div", {
...restProps,
ref,
children
}), $[9] = children, $[10] = ref, $[11] = restProps, $[12] = t2) : t2 = $[12], t2;
}
const ConnectorsStoreContext = createContext(null);
function useConnectorsStore() {
let store = useContext(ConnectorsStoreContext);
if (!store) throw Error("Missing connectors store context");
return store;
}
function ConnectFromRegion(props) {
let $ = c(24), children, key, restProps, zIndex;
$[0] === props ? (children = $[1], key = $[2], restProps = $[3], zIndex = $[4]) : ({children, _key: key, zIndex, ...restProps} = props, $[0] = props, $[1] = children, $[2] = key, $[3] = restProps, $[4] = zIndex);
let store = useConnectorsStore(), [rects, setRects] = useState(null), t0;
$[5] !== key || $[6] !== store.from || $[7] !== zIndex ? (t0 = () => store.from.subscribe(key, { zIndex }), $[5] = key, $[6] = store.from, $[7] = zIndex, $[8] = t0) : t0 = $[8];
let t1;
$[9] !== key || $[10] !== store || $[11] !== zIndex ? (t1 = [
key,
store,
zIndex
], $[9] = key, $[10] = store, $[11] = zIndex, $[12] = t1) : t1 = $[12], useEffect(t0, t1);
let t2;
$[13] !== key || $[14] !== rects || $[15] !== store.from ? (t2 = () => {
rects && store.from.next(key, rects);
}, $[13] = key, $[14] = rects, $[15] = store.from, $[16] = t2) : t2 = $[16];
let t3;
$[17] !== key || $[18] !== rects || $[19] !== store ? (t3 = [
key,
rects,
store
], $[17] = key, $[18] = rects, $[19] = store, $[20] = t3) : t3 = $[20], useEffect(t2, t3);
let t4;
return $[21] !== children || $[22] !== restProps ? (t4 = /* @__PURE__ */ jsx(ConnectorRegion, {
...restProps,
onRectsChange: setRects,
children
}), $[21] = children, $[22] = restProps, $[23] = t4) : t4 = $[23], t4;
}
function createConnectorsStore() {
let configKeys = [], fieldKeys = [], channels = {
from: /* @__PURE__ */ new Map(),
to: /* @__PURE__ */ new Map()
}, payloads = {
from: /* @__PURE__ */ new Map(),
to: /* @__PURE__ */ new Map()
}, observers = [];
function notifyObservers() {
let connectors = [];
for (let key of configKeys) {
let toRects = channels.to.get(key), toPayload = payloads.from.get(key), fromRects = channels.from.get(key), fromPayload = payloads.from.get(key);
toRects && fromRects && connectors.push({
key,
from: {
...fromRects,
payload: fromPayload
},
to: {
...toRects,
payload: toPayload
}
});
}
for (let observer of observers) observer(connectors);
}
return {
to: {
subscribe(key, payload) {
return channels.to.set(key, null), payloads.to.set(key, payload), configKeys.push(key), () => {
channels.to.delete(key), payloads.to.delete(key);
let idx = configKeys.indexOf(key);
idx > -1 && configKeys.splice(idx, 1), notifyObservers();
};
},
next(key, rects) {
channels.to.set(key, rects), fieldKeys.includes(key) && notifyObservers();
}
},
connectors: { subscribe(observer) {
return observers.push(observer), () => {
let idx = observers.indexOf(observer);
idx > -1 && observers.splice(idx, 1);
};
} },
from: {
subscribe(key, payload) {
return channels.from.set(key, null), payloads.from.set(key, payload), fieldKeys.push(key), () => {
channels.from.delete(key), payloads.from.delete(key);
let idx = fieldKeys.indexOf(key);
idx > -1 && fieldKeys.splice(idx, 1), notifyObservers();
};
},
next(key, rects) {
channels.from.set(key, rects), configKeys.includes(key) && notifyObservers();
}
}
};
}
function ConnectorsProvider(props) {
let $ = c(6), { children, onConnectorsChange } = props, t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = createConnectorsStore(), $[0] = t0) : t0 = $[0];
let store = t0, t1, t2;
$[1] === onConnectorsChange ? (t1 = $[2], t2 = $[3]) : (t1 = () => onConnectorsChange && store.connectors.subscribe(onConnectorsChange), t2 = [onConnectorsChange, store], $[1] = onConnectorsChange, $[2] = t1, $[3] = t2), useEffect(t1, t2);
let t3;
return $[4] === children ? t3 = $[5] : (t3 = /* @__PURE__ */ jsx(ConnectorsStoreContext.Provider, {
value: store,
children
}), $[4] = children, $[5] = t3), t3;
}
function getConnectorLinePoint(options, rect, bounds) {
let centerY = rect.y + rect.h / 2, isAbove = rect.y + rect.h < bounds.y + options.arrow.marginY, isBelow = rect.y > bounds.y + bounds.h - options.arrow.marginY;
return {
bounds,
x: rect.x,
y: centerY,
centerY,
startY: rect.y + options.path.marginY,
endY: rect.y + rect.h - options.path.marginY,
isAbove,
isBelow,
outOfBounds: isAbove || isBelow
};
}
function mapConnectorToLine(options, connector) {
let fromBounds = {
y: connector.from.bounds.y + options.arrow.threshold,
x: connector.from.bounds.x,
w: connector.from.bounds.w,
h: connector.from.bounds.h - options.arrow.threshold * 2
}, from = getConnectorLinePoint(options, connector.from.element, fromBounds);
from.x = connector.from.element.x + connector.from.element.w;
let fromBottom = fromBounds.y + fromBounds.h, toBounds = {
y: connector.to.bounds.y + options.arrow.threshold,
x: connector.to.bounds.x,
w: connector.to.bounds.w,
h: connector.to.bounds.h - options.arrow.threshold * 2
}, toBottom = toBounds.y + toBounds.h, to = getConnectorLinePoint(options, connector.to.element, toBounds), maxStartY = Math.max(to.startY, from.startY);
return from.y = Math.min(maxStartY, from.endY), from.y < toBounds.y ? from.y = Math.min(toBounds.y, from.endY) : from.y > toBottom && (from.y = Math.max(toBottom, from.startY)), to.y = Math.min(maxStartY, to.endY), to.y < fromBounds.y ? to.y = Math.min(fromBounds.y, to.endY) : to.y > fromBottom && (to.y = Math.max(fromBottom, to.startY)), from.y = Math.min(Math.max(from.y, fromBounds.y), fromBottom), to.y = Math.min(Math.max(to.y, toBounds.y), toBottom), {
from,
to
};
}
const assistDocumentIdPrefix = "sanity.assist.schemaType.", assistDocumentStatusIdPrefix = "sanity.assist.status.", assistDocumentTypeName = "sanity.assist.schemaType.annotations", assistFieldTypeName = "sanity.assist.schemaType.field", userInputTypeName = "sanity.assist.instruction.userInput", contextDocumentTypeName = "assist.instruction.context", assistTasksStatusTypeName = "sanity.assist.task.status", instructionTaskTypeName = "sanity.assist.instructionTask", fieldPresenceTypeName = "sanity.assist.instructionTask.presence", assistSerializedTypeName = "sanity.assist.serialized.type", assistSerializedFieldTypeName = "sanity.assist.serialized.field", fieldPathParam = "pathKey", instructionParam = "instruction", documentRootKey = "<document>";
function usePathKey(path) {
let $ = c(2), t0;
return $[0] === path ? t0 = $[1] : (t0 = getPathKey(path), $[0] = path, $[1] = t0), t0;
}
function getPathKey(path) {
return path.length ? Array.isArray(path) ? pathToString(path) : path : documentRootKey;
}
function getInstructionTitle(instruction) {
return instruction?.title ?? "Untitled";
}
function isDefined(t) {
return t != null;
}
function isPortableTextArray(type) {
return type.of.find((t) => isType(t, "block"));
}
/**
* Returns true if the `schemaType` or any of its parent types (`schemaType.type`)` has `name` equal
* to `typeName`.
*
* Useful for checking if `schemaType` is a type alias of `ìmage`, `code` or similar.
*/
function isType(schemaType, typeName) {
return schemaType.name === typeName ? !0 : schemaType.type ? isType(schemaType.type, typeName) : !1;
}
function isImage(schemaType) {
return isType(schemaType, "image");
}
function getDescriptionFieldOption(schemaType) {
if (!schemaType) return;
let descriptionField = schemaType.options?.aiAssist?.imageDescriptionField;
return typeof descriptionField == "string" ? {
path: descriptionField,
updateOnImageChange: !0
} : descriptionField ? {
path: descriptionField.path,
updateOnImageChange: descriptionField.updateOnImageChange ?? !0
} : getDescriptionFieldOption(schemaType.type);
}
function getImageInstructionFieldOption(schemaType) {
return schemaType ? schemaType.options?.aiAssist?.imageInstructionField || getImageInstructionFieldOption(schemaType.type) : void 0;
}
function isSchemaAssistEnabled(type) {
return !type.options?.aiAssist?.exclude;
}
function isAssistSupported(type) {
return !isSchemaAssistEnabled(type) || isDisabled(type) ? !1 : type.jsonType === "array" ? !type.of.every((t) => isDisabled(t)) : type.jsonType === "object" ? !type.fields.every((field) => isDisabled(field.type)) || isType(type, "image") : !0;
}
function isDisabled(type) {
return !isSchemaAssistEnabled(type) || isUnsupportedType(type);
}
function isUnsupportedType(type) {
return type.name === "sanity.imageCrop" || type.name === "sanity.imageHotspot" || isType(type, "globalDocumentReference") || isType(type, "reference") && !(type?.options)?.aiAssist?.embeddingsIndex || isType(type, "crossDatasetReference") || isType(type, "file");
}
const FirstAssistedPathContext = createContext(void 0);
function FirstAssistedPathProvider(props) {
let $ = c(5), { members } = props, t0;
if ($[0] !== members) {
let firstAssisted = members.find(_temp$15);
t0 = firstAssisted?.field.path ? pathToString(firstAssisted?.field.path) : void 0, $[0] = members, $[1] = t0;
} else t0 = $[1];
let firstAssistedPath = t0, t1;
return $[2] !== firstAssistedPath || $[3] !== props.children ? (t1 = /* @__PURE__ */ jsx(FirstAssistedPathContext.Provider, {
value: firstAssistedPath,
children: props.children
}), $[2] = firstAssistedPath, $[3] = props.children, $[4] = t1) : t1 = $[4], t1;
}
function _temp$15(member) {
return member.kind === "field" && isAssistSupported(member.field.schemaType);
}
const releaseAnnouncementUrl = "https://www.sanity.io/blog/sanity-ai-assist-announcement?utm_source=sanity-assist-plugin&utm_medium=organic_social&utm_campaign=ai-assist&utm_content=", packageName = "@sanity/assist", pluginTitle = "Sanity AI Assist", pluginTitleShort = "AI Assist", maxHistoryVisibilityMs = minutesToMilliseconds(30), illegalIdChars = /[^a-zA-Z0-9._-]/g;
function assistDocumentId(documentType) {
return `${assistDocumentIdPrefix}${documentType}`.replace(illegalIdChars, "_");
}
function assistTasksStatusId(documentId) {
return isVersionId(documentId) ? `${assistDocumentStatusIdPrefix}${getVersionFromId(documentId)}.${getPublishedId(documentId)}` : `${assistDocumentStatusIdPrefix}${getPublishedId(documentId)}`;
}
function useDocumentState(id, docType) {
let state = useEditState(id, docType);
return state.draft || state.published;
}
function useStudioAssistDocument(t0) {
let $ = c(15), { documentId, schemaType, initDoc } = t0, documentTypeName = schemaType.name, currentUser = useCurrentUser(), t1;
$[0] === documentTypeName ? t1 = $[1] : (t1 = assistDocumentId(documentTypeName), $[0] = documentTypeName, $[1] = t1);
let assistDocument = useDocumentState(t1, assistDocumentTypeName), t2 = documentId ?? "", t3;
$[2] === t2 ? t3 = $[3] : (t3 = assistTasksStatusId(t2), $[2] = t2, $[3] = t3);
let assistTasksStatus = useDocumentState(t3, assistTasksStatusTypeName), t4;
$[4] === Symbol.for("react.memo_cache_sentinel") ? (t4 = { apiVersion: "2023-01-01" }, $[4] = t4) : t4 = $[4];
let client = useClient(t4), t5, t6;
$[5] !== assistDocument || $[6] !== client || $[7] !== documentTypeName || $[8] !== initDoc ? (t5 = () => {
!assistDocument && initDoc && client.createIfNotExists({
_id: assistDocumentId(documentTypeName),
_type: assistDocumentTypeName
}).catch(_temp$14);
}, t6 = [
client,
assistDocument,
documentTypeName,
initDoc
], $[5] = assistDocument, $[6] = client, $[7] = documentTypeName, $[8] = initDoc, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), useEffect(t5, t6);
let t7;
bb0: {
if (!assistDocument) {
t7 = void 0;
break bb0;
}
let t8;
if ($[11] !== assistDocument || $[12] !== assistTasksStatus?.tasks || $[13] !== currentUser?.id) {
let tasks = assistTasksStatus?.tasks ?? [], fields = (assistDocument?.fields ?? []).map((assistField) => ({
...assistField,
tasks: tasks.filter((task) => task.path === assistField.path),
instructions: assistField.instructions?.filter((p) => !p.userId || p.userId === currentUser?.id).map((instruction) => asStudioInstruction(instruction, tasks))
}));
t8 = typed({
...assistDocument,
tasks: tasks?.map((task_0) => {
let instruction_0 = fields.find((f) => f.path === task_0.path)?.instructions?.find((i) => i._key === task_0.instructionKey);
return {
...task_0,
instruction: instruction_0
};
}),
fields
}), $[11] = assistDocument, $[12] = assistTasksStatus?.tasks, $[13] = currentUser?.id, $[14] = t8;
} else t8 = $[14];
t7 = t8;
}
return t7;
}
function _temp$14() {}
function asStudioInstruction(instruction, run) {
return {
...instruction,
tasks: run.filter((task) => task.instructionKey === instruction._key).filter((task) => task.started && (/* @__PURE__ */ new Date()).getTime() - new Date(task.started).getTime() < maxHistoryVisibilityMs)
};
}
const NO_TASKS = [];
function useInstructionToaster(documentId, documentSchemaType) {
let $ = c(13), t0;
$[0] !== documentId || $[1] !== documentSchemaType ? (t0 = {
documentId,
schemaType: documentSchemaType
}, $[0] = documentId, $[1] = documentSchemaType, $[2] = t0) : t0 = $[2];
let assistDocument = useStudioAssistDocument(t0), assistDocLoaded = !!assistDocument, currentUser = useCurrentUser(), toast = useToast(), tasks = assistDocument?.tasks, previousTasks = useRef("initial"), t1;
$[3] !== assistDocLoaded || $[4] !== currentUser?.id || $[5] !== tasks || $[6] !== toast ? (t1 = () => {
if (assistDocLoaded) {
if (previousTasks.current !== "initial") {
let prevTaskByKey = Object.fromEntries((previousTasks.current ?? NO_TASKS).map(_temp$13));
(tasks?.filter((task) => task.startedByUserId === currentUser?.id).filter((task_0) => {
let prevTask = prevTaskByKey[task_0._key];
return !prevTask && task_0.ended || !prevTask?.ended && task_0.ended;
}).filter(_temp2$7))?.forEach((task_2) => {
let title = task_2.title ?? getInstructionTitle(task_2.instruction);
task_2.reason === "error" ? toast.push({
title: `Failed: ${title}`,
status: "error",
description: `Instruction failed. ${task_2.message ?? ""}`,
closable: !0,
duration: 1e4
}) : task_2.reason === "timeout" ? toast.push({
title: `Timeout: ${title}`,
status: "error",
description: "Instruction timed out.",
closable: !0
}) : task_2.reason === "success" ? toast.push({
title: `Success: ${title}`,
status: "success",
description: "Instruction completed.",
closable: !0
}) : task_2.reason === "aborted" && toast.push({
title: `Canceled: ${title}`,
status: "warning",
description: "Instruction canceled.",
closable: !0
});
});
}
previousTasks.current = tasks;
}
}, $[3] = assistDocLoaded, $[4] = currentUser?.id, $[5] = tasks, $[6] = toast, $[7] = t1) : t1 = $[7];
let t2;
$[8] !== assistDocLoaded || $[9] !== currentUser || $[10] !== tasks || $[11] !== toast ? (t2 = [
tasks,
previousTasks,
toast,
currentUser,
assistDocLoaded
], $[8] = assistDocLoaded, $[9] = currentUser, $[10] = tasks, $[11] = toast, $[12] = t2) : t2 = $[12], useEffect(t1, t2);
}
function _temp2$7(task_1) {
return task_1.ended && isAfter(addSeconds(new Date(task_1.ended), 30), /* @__PURE__ */ new Date());
}
function _temp$13(run) {
return [run._key, run];
}
function AssistDocumentInputWrapper(props) {
let $ = c(7);
if (!isType(props.schemaType, "document") && props.id !== "root" && props.id !== "assist") {
let t0;
return $[0] === props ? t0 = $[1] : (t0 = /* @__PURE__ */ jsx(AssistInput, { ...props }), $[0] = props, $[1] = t0), t0;
}
let documentId = props.value?._id;
if (!documentId) {
let t0;
return $[2] === props ? t0 = $[3] : (t0 = props.renderDefault(props), $[2] = props, $[3] = t0), t0;
}
let t0 = props, t1;
return $[4] !== documentId || $[5] !== t0 ? (t1 = /* @__PURE__ */ jsx(AssistDocumentInput, {
...t0,
documentId
}), $[4] = documentId, $[5] = t0, $[6] = t1) : t1 = $[6], t1;
}
function AssistDocumentInput(t0) {
let $ = c(14), documentId, props;
$[0] === t0 ? (documentId = $[1], props = $[2]) : ({documentId, ...props} = t0, $[0] = t0, $[1] = documentId, $[2] = props), useInstructionToaster(documentId, props.schemaType);
let t1;
bb0: {
if (props.schemaType.name !== "sanity.assist.schemaType.annotations") {
t1 = props.schemaType;
break bb0;
}
let t2;
$[3] === props.schemaType.type ? t2 = $[4] : (t2 = {
...props.schemaType.type,
name: "document"
}, $[3] = props.schemaType.type, $[4] = t2);
let t3;
$[5] !== props.schemaType || $[6] !== t2 ? (t3 = {
...props.schemaType,
type: t2
}, $[5] = props.schemaType, $[6] = t2, $[7] = t3) : t3 = $[7], t1 = t3;
}
let schemaType = t1, t2 = props.members, t3;
$[8] !== props || $[9] !== schemaType ? (t3 = props.renderDefault({
...props,
schemaType
}), $[8] = props, $[9] = schemaType, $[10] = t3) : t3 = $[10];
let t4;
return $[11] !== props.members || $[12] !== t3 ? (t4 = /* @__PURE__ */ jsx(FirstAssistedPathProvider, {
members: t2,
children: t3
}), $[11] = props.members, $[12] = t3, $[13] = t4) : t4 = $[13], t4;
}
function AssistInput(props) {
let $ = c(7), { zIndex } = useLayer(), { paneKey } = useDocumentPane(), t0 = `${paneKey}_${usePathKey(props.path)}`, t1;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = { minWidth: 0 }, $[0] = t1) : t1 = $[0];
let t2;
$[1] === props ? t2 = $[2] : (t2 = props.renderDefault(props), $[1] = props, $[2] = t2);
let t3;
return $[3] !== t0 || $[4] !== t2 || $[5] !== zIndex ? (t3 = /* @__PURE__ */ jsx(ConnectFromRegion, {
_key: t0,
zIndex,
style: t1,
children: t2
}), $[3] = t0, $[4] = t2, $[5] = zIndex, $[6] = t3) : t3 = $[6], t3;
}
const AssistDocumentContext = createContext(void 0);
function useAssistDocumentContext() {
let context = useContext(AssistDocumentContext);
if (!context) throw Error("AssistDocumentContext value is missing");
return context;
}
const AiAssistanceConfigContext = createContext({});
function useAiAssistanceConfig() {
let context = useContext(AiAssistanceConfigContext);
if (!context) throw Error("Missing AiAssistanceConfigContext");
return context;
}
function useSerializedTypes() {
return useAiAssistanceConfig().serializedTypes;
}
function getTypeIcon(schemaType) {
let t = schemaType;
for (; t;) {
if (t.icon) return t.icon;
t = t.type;
}
return isType(schemaType, "slug") ? LinkIcon : isType(schemaType, "image") ? ImageIcon : schemaType.jsonType === "array" && isPortableTextArray(schemaType) ? BlockContentIcon : schemaType.jsonType === "array" ? OlistIcon : schemaType.jsonType === "object" ? BlockquoteIcon : schemaType.jsonType === "string" ? StringIcon : DocumentIcon;
}
function asFieldRefsByTypePath(fieldRefs) {
return fieldRefs.reduce((acc, ref) => ({
...acc,
[ref.key]: ref
}), {});
}
function getDocumentFieldRef(schemaType) {
return {
key: documentRootKey,
icon: schemaType.icon ?? DocumentIcon,
title: "The entire document",
path: [],
schemaType
};
}
function getFieldRefs(schemaType, parent, depth = 0) {
return depth >= 6 ? [] : schemaType.fields.filter((f) => !f.name.startsWith("_")).flatMap((field) => {
let path = parent ? [...parent.path, field.name] : [field.name], title = field.type.title ?? field.name, fieldRef = {
key: patchableKey(pathToString(path)),
path,
title: parent ? [parent.title, title].join(" / ") : title,
schemaType: field.type,
icon: getTypeIcon(field.type)
}, fields = field.type.jsonType === "object" ? getFieldRefs(field.type, fieldRef, depth + 1) : [], syntheticFields = field.type.jsonType === "array" ? getSyntheticFields(field.type, fieldRef, depth + 1) : [];
return isAssistSupported(field.type) ? [
fieldRef,
...fields,
...syntheticFields
] : [...fields, ...syntheticFields];
});
}
function getSyntheticFields(schemaType, parent, depth = 0) {
return depth >= 6 ? [] : schemaType.of.filter((itemType) => !isType(itemType, "block")).flatMap((itemType) => {
let segment = { _key: itemType.name }, title = itemType.title ?? itemType.name, path = parent ? [...parent.path, segment] : [segment], fieldRef = {
key: patchableKey(pathToString(path)),
path,
title: parent ? [parent.title, title].join(" / ") : title,
schemaType: itemType,
icon: getTypeIcon(itemType),
synthetic: !0
}, fields = itemType.jsonType === "object" ? getFieldRefs(itemType, fieldRef, depth + 1) : [];
return isAssistSupported(itemType) ? [fieldRef, ...fields] : fields;
});
}
function getTypePath(doc, pathString) {
if (!pathString) return;
let path = stringToPath(pathString), currentPath = [], valid = !0, syntheticPath = path.map((segment) => {
if (currentPath.push(segment), isKeySegment(segment)) {
let match = extractWithPath(pathToString(currentPath), doc)[0], value = match?.value;
if (match && value && typeof value == "object" && "_type" in value) return { _key: value._type };
valid = !1;
}
return segment;
});
return valid ? patchableKey(pathToString(syntheticPath)) : void 0;
}
/**
* mutator crashes if path contains certain letters
* @param pathKey
*/
function patchableKey(pathKey) {
return pathKey.replace(/[=]=/g, ":").replace(/[[\]]/g, "|").replace(/"/g, "");
}
function useTypePath(doc, pathString) {
let $ = c(3), t0;
return $[0] !== doc || $[1] !== pathString ? (t0 = getTypePath(doc, pathString), $[0] = doc, $[1] = pathString, $[2] = t0) : t0 = $[2], t0;
}
function useSelectedField(documentSchemaType, path) {
let $ = c(6), { getFieldRefs } = useAiAssistanceConfig(), t0;
$[0] !== documentSchemaType || $[1] !== getFieldRefs ? (t0 = documentSchemaType && isObjectSchemaType(documentSchemaType) ? [getDocumentFieldRef(documentSchemaType), ...getFieldRefs(documentSchemaType.name)] : [], $[0] = documentSchemaType, $[1] = getFieldRefs, $[2] = t0) : t0 = $[2];
let selectableFields = t0, t1;
return $[3] !== path || $[4] !== selectableFields ? (t1 = path ? selectableFields?.find((f) => f.key === path) : void 0, $[3] = path, $[4] = selectableFields, $[5] = t1) : t1 = $[5], t1;
}
function getFieldTitle(field) {
let schemaType = field?.schemaType;
return field?.title ?? schemaType?.title ?? schemaType?.name ?? "Untitled";
}
function useAiPaneRouter() {
let $ = c(5), paneRouter = usePaneRouter(), t0;
$[0] === paneRouter.params ? t0 = $[1] : (t0 = paneRouter.params ?? {}, $[0] = paneRouter.params, $[1] = t0);
let t1;
return $[2] !== paneRouter || $[3] !== t0 ? (t1 = {
...paneRouter,
params: t0
}, $[2] = paneRouter, $[3] = t0, $[4] = t1) : t1 = $[4], t1;
}
const basePath = "/assist/tasks/instruction", API_VERSION_WITH_EXTENDED_TYPES = "2025-04-01";
function canUseAssist(status) {
return status?.enabled && status.initialized && status.validToken;
}
function useApiClient(customApiClient) {
let $ = c(4), t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = { apiVersion: API_VERSION_WITH_EXTENDED_TYPES }, $[0] = t0) : t0 = $[0];
let client = useClient(t0), t1;
return $[1] !== client || $[2] !== customApiClient ? (t1 = customApiClient ? customApiClient(client) : client, $[1] = client, $[2] = customApiClient, $[3] = t1) : t1 = $[3], t1;
}
function useTranslate(apiClient) {
let $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t1) => {
let { documentId, languagePath, styleguide, translatePath, fieldLanguageMap, conditionalMembers } = t1;
return setLoading(!0), async function() {
return apiClient.request({
method: "POST",
url: `/assist/tasks/translate/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
documentId,
types,
languagePath,
userStyleguide: await styleguide(),
fieldLanguageMap,
conditionalMembers,
translatePath: translatePath.length === 0 ? documentRootKey : pathToString(translatePath),
userId: user?.id
}
});
}().catch((e) => {
throw toast.push({
status: "error",
title: "Translate failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
let translate = t0, t1;
return $[5] !== loading || $[6] !== translate ? (t1 = {
translate,
loading
}, $[5] = loading, $[6] = translate, $[7] = t1) : t1 = $[7], t1;
}
function useGenerateCaption(apiClient) {
let $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t1) => {
let { path, documentId } = t1;
return setLoading(!0), apiClient.request({
method: "POST",
url: `/assist/tasks/generate-caption/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
path,
documentId,
types,
userId: user?.id
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Generate image description failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
let generateCaption = t0, t1;
return $[5] !== generateCaption || $[6] !== loading ? (t1 = {
generateCaption,
loading
}, $[5] = generateCaption, $[6] = loading, $[7] = t1) : t1 = $[7], t1;
}
function useGenerateImage(apiClient) {
let $ = c(8), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), toast = useToast(), t0;
$[0] !== apiClient || $[1] !== toast || $[2] !== types || $[3] !== user?.id ? (t0 = (t1) => {
let { path, documentId } = t1;
return setLoading(!0), apiClient.request({
method: "POST",
url: `/assist/tasks/generate-image/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
path,
documentId,
types,
userId: user?.id
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Generate image from prompt failed",
description: e.message
}), setLoading(!1), e;
}).finally(() => {
setTimeout(() => {
setLoading(!1);
}, 2e3);
});
}, $[0] = apiClient, $[1] = toast, $[2] = types, $[3] = user?.id, $[4] = t0) : t0 = $[4];
let generateImage = t0, t1;
return $[5] !== generateImage || $[6] !== loading ? (t1 = {
generateImage,
loading
}, $[5] = generateImage, $[6] = loading, $[7] = t1) : t1 = $[7], t1;
}
function useGetInstructStatus(apiClient) {
let [loading, setLoading] = useState(!0);
return {
loading,
getInstructStatus: useCallback(async () => {
setLoading(!0);
let projectId = apiClient.config().projectId;
try {
return await apiClient.request({
method: "GET",
url: `${basePath}/${apiClient.config().dataset}/status?projectId=${projectId}`
});
} finally {
setLoading(!1);
}
}, [setLoading, apiClient])
};
}
function useInitInstruct(apiClient) {
let $ = c(5), [loading, setLoading] = useState(!1), t0;
$[0] === apiClient ? t0 = $[1] : (t0 = () => (setLoading(!0), apiClient.request({
method: "GET",
url: `${basePath}/${apiClient.config().dataset}/init?projectId=${apiClient.config().projectId}`
}).finally(() => {
setLoading(!1);
})), $[0] = apiClient, $[1] = t0);
let initInstruct = t0, t1;
return $[2] !== initInstruct || $[3] !== loading ? (t1 = {
loading,
initInstruct
}, $[2] = initInstruct, $[3] = loading, $[4] = t1) : t1 = $[4], t1;
}
function useRunInstructionApi(apiClient) {
let $ = c(9), toast = useToast(), [loading, setLoading] = useState(!1), user = useCurrentUser(), types = useSerializedTypes(), { config: t0 } = useAiAssistanceConfig(), { assist: assistConfig } = t0, t1;
$[0] !== apiClient || $[1] !== assistConfig || $[2] !== toast || $[3] !== types || $[4] !== user ? (t1 = (request) => {
if (!user) {
toast.push({
status: "error",
title: "Unable to get user for instruction."
});
return;
}
setLoading(!0);
let { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions(), defaultLocaleSettings = {
timeZone,
locale
}, localeSettings = assistConfig?.localeSettings?.({
user,
defaultSettings: defaultLocaleSettings
}) ?? defaultLocaleSettings;
return apiClient.request({
method: "POST",
url: `${basePath}/${apiClient.config().dataset}?projectId=${apiClient.config().projectId}`,
body: {
...request,
types,
userId: user?.id,
localeSettings,
maxPathDepth: assistConfig?.maxPathDepth
}
}).catch((e) => {
throw toast.push({
status: "error",
title: "Instruction failed",
description: e.message
}), e;
}).finally(() => {
setLoading(!1);
});
}, $[0] = apiClient, $[1] = assistConfig, $[2] = toast, $[3] = types, $[4] = user, $[5] = t1) : t1 = $[5];
let runInstruction = t1, t2;
return $[6] !== loading || $[7] !== runInstruction ? (t2 = {
runInstruction,
loading
}, $[6] = loading, $[7] = runInstruction, $[8] = t2) : t2 = $[8], t2;
}
const NO_INPUT = {}, RunInstructionContext = createContext({
runInstruction: () => {},
getUserInput: async () => void 0,
instructionLoading: !1
});
function useRunInstruction() {
return useContext(RunInstructionContext);
}
function isUserInputBlock(block) {
return block._type === userInputTypeName;
}
function RunInstructionProvider(props) {
let $ = c(33), { config } = useAiAssistanceConfig(), { runInstruction: runInstructionRequest, loading } = useRunInstructionApi(useApiClient(config?.__customApiClient)), id = useId(), [inputs, setInputs] = useState(NO_INPUT), [runRequest, setRunRequest] = useState(), [resolveUserInput, setResolveUserInput] = useState(), t0;
$[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = async (t1) => {
let { title, inputs: inputs_0 } = t1, userInputBlocks = inputs_0.map(_temp$12);
if (userInputBlocks.length) return setRunRequest({
dialogTitle: title,
userInputBlocks
}), new Promise((resolve) => {
setResolveUserInput(() => resolve);
});
}, $[0] = t0) : t0 = $[0];
let getUserInput = t0, t1;
$[1] !== loading || $[2] !== runInstructionRequest ? (t1 = (req) => {
if (loading) return;
let { instruction, ...request } = req, instructionKey = instruction._key, userInputBlocks_0 = instruction?.prompt?.flatMap(_temp2$6).filter(isUserInputBlock);
if (!userInputBlocks_0?.length) {
runInstructionRequest({
...request,
instructionKey,
userTexts: void 0
});
return;
}
setRunRequest({
...req,
userInputBlocks: userInputBlocks_0
});
}, $[1] = loading, $[2] = runInstructionRequest, $[3] = t1) : t1 = $[3];
let runInstruction = t1, t2;
$[4] === resolveUserInput ? t2 = $[5] : (t2 = () => {
setRunRequest(void 0), setInputs(NO_INPUT), resolveUserInput && resolveUserInput(void 0), setResolveUserInput(void 0);
}, $[4] = resolveUserInput, $[5] = t2);
let close = t2, t3;
$[6] !== close || $[7] !== inputs || $[8] !== resolveUserInput || $[9] !== runInstructionRequest || $[10] !== runRequest ? (t3 = () => {
if (runRequest) if ("instruction" in runRequest) {
let { instruction: instruction_0, userInputBlocks: _, ...request_0 } = runRequest;
runInstructionRequest({
...request_0,
instructionKey: instruction_0._key,
userTexts: Object.entries(inputs).map(_temp3$4)
});
} else {
let userInputs = Object.values(inputs).map((input_0, i_0) => {
let userInputBlock = runRequest.userInputBlocks[i_0];
return {
input: {
id: userInputBlock._key,
title: userInputBlock.message ?? "",
description: userInputBlock.description
},
result: input_0
};
});
resolveUserInput?.(userInputs), setResolveUserInput(void 0);
}
close();
}, $[6] = close, $[7] = inputs, $[8] = resolveUserInput, $[9] = runInstructionRequest, $[10] = runRequest, $[11] = t3) : t3 = $[11];
let runWithInput = t3, open = !!runRequest;
runRequest?.userInputBlocks;
let t4;
$[12] === inputs ? t4 = $[13] : (t4 = Object.entries(inputs).filter(_temp4$2), $[12] = inputs, $[13] = t4);
let runDisabled = (runRequest?.userInputBlocks?.length ?? 0) > t4.length, t5;
$[14] === Symbol.for("react.memo_cache_sentinel") ? (t5 = { width: "100%" }, $[14] = t5) : t5 = $[14];
let t6;
$[15] !== runDisabled || $[16] !== runWithInput ? (t6 = /* @__PURE__ */ jsx(Button, {
text: "Run instruction",
onClick: runWithInput,
tone: "primary",
icon: PlayIcon,
style: t5,
disabled: runDisabled
}), $[15] = runDisabled, $[16] = runWithInput, $[17] = t6) : t6 = $[17];
let runButton = t6, t7;
$[18] !== loading || $[19] !== runInstruction ? (t7 = {
runInstruction,
getUserInput,
instructionLoading: loading
}, $[18] = loading, $[19] = runInstruction, $[20] = t7) : t7 = $[20];
let contextValue = t7, t8;
$[21] !== close || $[22] !== id || $[23] !== inputs || $[24] !== open || $[25] !== runButton || $[26] !== runDisabled || $[27] !== runRequest ? (t8 = open ? /* @__PURE__ */ jsx(Dialog, {
id,
open,
onClose: close,
width: 1,
header: "dialogTitle" in runRequest ? runRequest.dialogTitle : getInstructionTitle(runRequest?.instruction),
footer: /* @__PURE__ */ jsx(Flex, {
justify: "space-between",
padding: 2,
flex: 1,
children: runDisabled ? /* @__PURE__ */ jsx(Tooltip, {
content: /* @__PURE__ */ jsx(Flex, {
padding: 2,
children: /* @__PURE__ */ jsx(Text, { children: "Unable to run instruction. All fields must have a value." })
}),
placement: "top",
children: /* @__PURE__ */ jsx(Flex, {
flex: 1,
children: runButton
})
}) : runButton
}),
children: /* @__PURE__ */ jsx(Stack, {
padding: 4,
gap: 2,
children: runRequest?.userInputBlocks?.map((block_0, i_1) => /* @__PURE__ */ jsx(UserInput, {
block: block_0,
autoFocus: i_1 === 0,
inputs,
setInputs
}, block_0._key))
})
}) : null, $[21] = close, $[22] = id, $[23] = inputs, $[24] = open, $[25] = runButton, $[26] = runDisabled, $[27] = runRequest, $[28] = t8) : t8 = $[28];
let t9;
return $[29] !== contextValue || $[30] !== props.children || $[31] !== t8 ? (t9 = /* @__PURE__ */ jsxs(RunInstructionContext.Provider, {
value: contextValue,
children: [t8, props.children]
}), $[29] = contextValue, $[30] = props.children, $[31] = t8, $[32] = t9) : t9 = $[32], t9;
}
function _temp4$2(t0) {
let [, value_0] = t0;
return !!value_0;
}
function _temp3$4(t0) {
let [key, value] = t0;
return {
blockKey: key,
userInput: value
};
}
function _temp2$6(block) {
return block._type === "block" ? block.children.filter(isUserInputBlock) : [block];
}
function _temp$12(input, i) {
return {
_type: userInputTypeName,
_key: input.id ?? `${i}`,
message: input.title,
description: input.description
};
}
function UserInput(props) {
let $ = c(16), { block, autoFocus, setInputs, inputs } = props, key = block._key, textAreaRef = useRef(null), t0;
$[0] !== key || $[1] !== setInputs ? (t0 = (e) => {
setInputs((current) => ({
...current,
[key]: (e.currentTarget ?? e.target).value
}));
}, $[0] = key, $[1] = setInputs, $[2] = t0) : t0 = $[2];
let onChange = t0, value = inputs[key], t1, t2;
$[3] === autoFocus ? (t1 = $[4], t2 = $[5]) : (t1 = () => {
autoFocus && setTimeout(() => textAreaRef.current?.focus(), 0);
}, t2 = [autoFocus], $[3] = autoFocus, $[4] = t1, $[5] = t2), useEffect(t1, t2);
let t3 = block?.message ?? "Provide more context", t4;
$[6] !== block.description || $[7] !== t3 ? (t4 = /* @__PURE__ */ jsx(FormFieldHeaderText, {
title: t3,
description: block.description
}), $[6] = block.description, $[7] = t3, $[8] = t4) : t4 = $[8];
let t5;
$[9] === Symbol.for("react.memo_cache_sentinel") ? (t5 = { resize: "vertical" }, $[9] = t5) : t5 = $[9];
let t6;
$[10] !== onChange || $[11] !== value ? (t6 = /* @__PURE__ */ jsx(TextArea, {
ref: textAreaRef,
rows: 4,
value,
onChange,
style: t5
}), $[10] = onChange, $[11] = value, $[12] = t6) : t6 = $[12];
let t7;
return $[13] !== t4 || $[14] !== t6 ? (t7 = /* @__PURE__ */ jsxs(Stack, {
padding: 2,
gap: 3,
children: [t4, t6]
}), $[13] = t4, $[14] = t6, $[15] = t7) : t7 = $[15], t7;
}
function isDocAssistable(documentSchemaType, published, draft) {
return !!(documentSchemaType.liveEdit ? published : draft);
}
function useRequestRunInstruction(args) {
let $ = c(6), { runInstruction, instructionLoading } = useRunInstruction(), t0;
$[0] !== args || $[1] !== runInstruction ? (t0 = {
...args,
task: runInstruction
}, $[0] = args, $[1] = runInstruction, $[2] = t0) : t0 = $[2];
let requestRunInstruction = useDraftDelayedTask(t0), t1;
return $[3] !== instructionLoading || $[4] !== requestRunInstruction ? (t1 = {
instructionLoading,
requestRunInstruction
}, $[3] = instructionLoading, $[4] = requestRunInstruction, $[5] = t1) : t1 = $[5], t1;
}
/**
* Ensures that the current document is a draft before running task
*/
function useDraftDelayedTask(args) {
let $ = c(7), { documentOnChange, isDocAssistable, task } = args, [queuedArgs, setQueuedArgs] = useState(void 0), t0, t1;
$[0] !== isDocAssistable || $[1] !== queuedArgs || $[2] !== task ? (t0 = () => {
queuedArgs && isDocAssistable && (task(queuedArgs), setQueuedArgs(void 0));
}, t1 = [
queuedArgs,
isDocAssistable,
task
], $[0] = isDocAssistable, $[1] = queuedArgs, $[2] = task, $[3] = t0, $[4] = t1) : (t0 = $[3], t1 = $[4]), useEffect(t0, t1);
let t2;
return $[5] === documentOnChange ? t2 = $[6] : (t2 = (taskArgs) => {
documentOnChange(PatchEvent.from([unset(["_force_document_creation"])])), setQueuedArgs(taskArgs);
}, $[5] = documentOnChange, $[6] = t2), t2;
}
function useAssistDocumentContextValue(documentId, documentType) {
let $ = c(47), schema = useSchema(), { getFieldRefs, getFieldRefsByTypePath } = useAiAssistanceConfig(), t0, t1;
$[0] !== documentType || $[1] !== schema ? (t1 = schema.get(documentType), $[0] = documentType, $[1] = schema, $[2] = t1) : t1 = $[2];
let schemaType = t1;
if (!schemaType) throw Error(`Schema type "${documentType}" not found`);
t0 = schemaType;
let documentSchemaType = t0, t2;
$[3] !== documentType || $[4] !== getFieldRefs ? (t2 = getFieldRefs(documentType), $[3] = documentType, $[4] = getFieldRefs, $[5] = t2) : t2 = $[5];
let t3;
$[6] !== documentType || $[7] !== getFieldRefsByTypePath ? (t3 = getFieldRefsByTypePath(documentType), $[6] = documentType, $[7] = getFieldRefsByTypePath, $[8] = t3) : t3 = $[8];
let t4;
$[9] !== t2 || $[10] !== t3 ? (t4 = {
fieldRefs: t2,
fieldRefsByTypePath: t3
}, $[9] = t2, $[10] = t3, $[11] = t4) : t4 = $[11];
let { fieldRefs, fieldRefsByTypePath } = t4, { openInspector, closeInspector, inspector, onChange: documentOnChange, editState } = useDocumentPane(), { selectedReleaseId } = usePerspective(), t5;
$[12] === editState ? t5 = $[13] : (t5 = editState || {}, $[12] = editState, $[13] = t5);
let { draft, published, version } = t5, t6;
$[14] !== documentId || $[15] !== documentSchemaType || $[16] !== selectedReleaseId ? (t6 = selectedReleaseId ? getVersionId(documentId, selectedReleaseId) : documentSchemaType.liveEdit ? documentId : getDraftId(documentId), $[14] = documentId, $[15] = documentSchemaType, $[16] = selectedReleaseId, $[17] = t6) : t6 = $[17];
let assistableDocumentId = t6, documentIsNew = selectedReleaseId ? !version?._id : !draft?._id && !published?._id, t7;
$[18] !== documentSchemaType || $[19] !== draft || $[20] !== published || $[21] !== selectedReleaseId || $[22] !== version ? (t7 = selectedReleaseId ? !!version : isDocAssistable(documentSchemaType, published, draft), $[18] = documentSchemaType, $[19] = draft, $[20] = published, $[21] = selectedReleaseId, $[22] = version, $[23] = t7) : t7 = $[23];
let documentIsAssistable = t7, { params } = useAiPaneRouter(), selectedPath = params[fieldPathParam], t8;
$[24] !== assistableDocumentId || $[25] !== documentSchemaType ? (t8 = {
documentId: assistableDocumentId,
schemaType: documentSchemaType
}, $[24] = assistableDocumentId, $[25] = documentSchemaType, $[26] = t8) : t8 = $[26];
let assistDocument = useStudioAssistDocument(t8), { syntheticTasks, addSyntheticTask, removeSyntheticTask } = useSyntheticTasks(assistableDocumentId), t9;
bb0: {
let t10;
$[27] !== addSyntheticTask || $[28] !== assistableDocumentId || $[29] !== closeInspector || $[30] !== documentIsAssistable || $[31] !== documentIsNew || $[32] !== documentOnChange || $[33] !== documentSchemaType || $[34] !== fieldRefs || $[35] !== fieldRefsByTypePath || $[36] !== inspector || $[37] !== openInspector || $[38] !== removeSyntheticTask || $[39] !== selectedPath || $[40] !== syntheticTasks ? (t10 = {
assistableDocumentId,
documentSchemaType,
documentIsNew,
documentIsAssistable,
openInspector,
closeInspector,
inspector,
documentOnChange,
selectedPath,
syntheticTasks,
addSyntheticTask,
removeSyntheticTask,
fieldRefs,
fieldRefsByTypePath
}, $[27] = addSyntheticTask, $[28] = assistableDocumentId, $[29] = closeInspector, $[30] = documentIsAssistable, $[31] = documentIsNew, $[32] = documentOnChange, $[33] = documentSchemaType, $[34] = fieldRefs, $[35] = fieldRefsByTypePath, $[36] = inspector, $[37] = openInspector, $[38] = removeSyntheticTask, $[39] = selectedPath, $[40] = syntheticTasks, $[41] = t10) : t10 = $[41];
let base = t10;
if (!assistDocument) {
let t11;
$[42] === base ? t11 = $[43] : (t11 = {
...base,
loading: !0,
assistDocument: void 0
}, $[42] = base, $[43] = t11), t9 = t11;
break bb0;
}
let t11;
$[44] !== assistDocument || $[45] !== base ? (t11 = {
...base,
loading: !1,
assistDocument
}, $[44] = assistDocument, $[45] = base, $[46] = t11) : t11 = $[46], t9