@sanity/sdk 3.17.0-next.20261126182834 → 3.17.0
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/_exports/_internal.js +2 -2
- package/dist/_exports/collaboration.js +2 -2
- package/dist/{buildCommentThreads-aYpLzq0R.js → buildCommentThreads-YikCB5T5.js} +2 -2
- package/dist/{buildCommentThreads-aYpLzq0R.js.map → buildCommentThreads-YikCB5T5.js.map} +1 -1
- package/dist/index.js +3 -3
- package/dist/{commentFieldPath-DuhAgFcL.js → types-C8dSHL5E.js} +2 -1
- package/dist/types-C8dSHL5E.js.map +1 -0
- package/dist/{version-CttzAzl5.js → version-C4jlyyUU.js} +3 -3
- package/dist/{version-CttzAzl5.js.map → version-C4jlyyUU.js.map} +1 -1
- package/package.json +1 -1
- package/dist/commentFieldPath-DuhAgFcL.js.map +0 -1
|
@@ -4,8 +4,8 @@ import { C as isNetworkFailure, I as getClientErrorApiBody, T as DocumentInacces
|
|
|
4
4
|
import { a as getDashboardMessageBus, c as MessageBusError, d as resetMessageBus, f as workerMessages, h as randomUuid, i as resolveTopic, m as randomId, o as isDashboardEnvironment, r as getTopicState, s as requireDashboardMessageBus, t as TopicError, u as installMessageBus } from "../topicStore-CKBdgAz7.js";
|
|
5
5
|
import { i as pickProperties, n as isObject, t as isDeepEqual } from "../object-CxXlSVg7.js";
|
|
6
6
|
import { n as getClient } from "../clientStore-eysItBQl.js";
|
|
7
|
-
import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "../
|
|
8
|
-
import { B as ActionError, C as favoriteScope, E as toFavoriteDocument, G as getProjectAccessErrorDetails, a as parseQueryKey, f as getUsersKey, m as parseUsersKey, n as version, q as getSignInMethodLabel, r as getQueryKey, t as CORE_SDK_VERSION, x as PreferenceError } from "../version-
|
|
7
|
+
import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "../types-C8dSHL5E.js";
|
|
8
|
+
import { B as ActionError, C as favoriteScope, E as toFavoriteDocument, G as getProjectAccessErrorDetails, a as parseQueryKey, f as getUsersKey, m as parseUsersKey, n as version, q as getSignInMethodLabel, r as getQueryKey, t as CORE_SDK_VERSION, x as PreferenceError } from "../version-C4jlyyUU.js";
|
|
9
9
|
import { ClientError, ConnectionFailedError, ServerError, isTimeoutError } from "@sanity/client";
|
|
10
10
|
import { EMPTY, catchError, defer, distinctUntilChanged, map, merge } from "rxjs";
|
|
11
11
|
import "@sanity/types";
|
|
@@ -3,8 +3,8 @@ import { a as getClientAuthState, b as retryOnCredentialChange, i as getAuthStat
|
|
|
3
3
|
import { h as randomUuid, m as randomId } from "../topicStore-CKBdgAz7.js";
|
|
4
4
|
import { r as omitProperty } from "../object-CxXlSVg7.js";
|
|
5
5
|
import { r as getClientState } from "../clientStore-eysItBQl.js";
|
|
6
|
-
import { t as toCommentFieldPath } from "../
|
|
7
|
-
import { a as compareProjectOrganization, o as observeAppOrganizationId, r as project, t as buildCommentThreads } from "../buildCommentThreads-
|
|
6
|
+
import { t as toCommentFieldPath } from "../types-C8dSHL5E.js";
|
|
7
|
+
import { a as compareProjectOrganization, o as observeAppOrganizationId, r as project, t as buildCommentThreads } from "../buildCommentThreads-YikCB5T5.js";
|
|
8
8
|
import "@sanity/client";
|
|
9
9
|
import { EMPTY, NEVER, Observable, ReplaySubject, catchError, defer, distinctUntilChanged, filter, first, firstValueFrom, groupBy, map, merge, mergeMap, of, pairwise, partition, race, share, startWith, switchMap, take, tap, throwError } from "rxjs";
|
|
10
10
|
import "@sanity/types";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { v as buildQuery } from "./authStore-CinLcYHr.js";
|
|
2
2
|
import { a as getDashboardMessageBus, n as getDashboardOrganizationId, r as getTopicState } from "./topicStore-CKBdgAz7.js";
|
|
3
3
|
import { r as getClientState } from "./clientStore-eysItBQl.js";
|
|
4
|
-
import { n as defineFetcher } from "./
|
|
4
|
+
import { n as defineFetcher } from "./types-C8dSHL5E.js";
|
|
5
5
|
import { defer, filter, map, switchMap } from "rxjs";
|
|
6
6
|
/**
|
|
7
7
|
* The organization the app itself belongs to, as opposed to the one that owns
|
|
@@ -193,4 +193,4 @@ function buildCommentThreads(comments) {
|
|
|
193
193
|
}
|
|
194
194
|
export { compareProjectOrganization as a, projects as i, threadComments as n, observeAppOrganizationId as o, project as r, buildCommentThreads as t };
|
|
195
195
|
|
|
196
|
-
//# sourceMappingURL=buildCommentThreads-
|
|
196
|
+
//# sourceMappingURL=buildCommentThreads-YikCB5T5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildCommentThreads-aYpLzq0R.js","names":["API_VERSION"],"sources":["../src/organization/appOrganization.ts","../src/project/organizationVerification.ts","../src/projects/projects.ts","../src/project/project.ts","../src/comments/buildCommentThreads.ts"],"sourcesContent":["import {defer, filter, map, type Observable} from 'rxjs'\n\nimport {getDashboardMessageBus} from '../dashboard/messageBus/store'\nimport {getDashboardOrganizationId, getTopicState} from '../dashboard/messageBus/topicStore'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {type OrganizationBase} from './organization'\n\n/** What the `organizations.current` topic publishes, `null` when none is selected. */\ntype CurrentOrganization = Pick<OrganizationBase, 'id' | 'name' | 'slug'> | null\n\n/**\n * The organization the app itself belongs to, as opposed to the one that owns\n * any particular resource.\n *\n * Inside the Dashboard this arrives with the app, from whichever runtime is\n * hosting it. Outside it, `organizationId` on the `SanityConfig` says so.\n * Emits `undefined` when neither has one, leaving the caller to decide whether\n * that is fatal.\n *\n * @remarks\n * On a message bus this waits for the host's first `organizations.current`\n * publish, with no deadline: a host that never publishes leaves comment reads\n * and organization-scoped user lists unresolved rather than failing. Waiting is\n * deliberate, since resolving against the config first would point a read at one\n * organization and then another. The topic is shared, so a failure another\n * reader's `resolveTopic` records on it errors this stream too.\n *\n * @internal\n */\nexport function observeAppOrganizationId(instance: SanityInstance): Observable<string | undefined> {\n return observeDashboardOrganizationId(instance).pipe(\n map((organizationId) => organizationId ?? instance.config.organizationId),\n )\n}\n\n/**\n * The Dashboard's current organization, or `undefined` when the app is not\n * running in one.\n *\n * Both Dashboard runtimes are covered, the same way `getDashboardOrganizationId`\n * covers them: the topic once this instance has a bus connection, and `_context`\n * otherwise. The connection is read per subscription rather than once at module\n * scope, because the host installs the bus and may not have run by the time this\n * module is first imported.\n */\nfunction observeDashboardOrganizationId(instance: SanityInstance): Observable<string | undefined> {\n return defer(() => {\n if (!getDashboardMessageBus(instance)) {\n return getDashboardOrganizationId(instance).observable\n }\n\n return getTopicState(instance, 'organizations.current').observable.pipe(\n // `undefined` means the host has yet to publish, which is not the same as\n // there being no organization. Waiting keeps a read from resolving against\n // the config fallback and then changing organization a moment later.\n filter((organization) => organization !== undefined),\n map((organization) => (organization as CurrentOrganization)?.id),\n )\n })\n}\n","/**\n * Error message returned by the organization verification\n * @public\n */\nexport interface OrgVerificationResult {\n error: string | null\n}\n\n/**\n * Compares a project's actual organization ID with the expected organization ID.\n * @public\n */\nexport function compareProjectOrganization(\n projectId: string,\n projectOrganizationId: string | null | undefined,\n appOrganizationId: string,\n): OrgVerificationResult {\n if (projectOrganizationId !== appOrganizationId) {\n return {\n error:\n `Project ${projectId} belongs to Organization ${projectOrganizationId ?? 'unknown'}, ` +\n `but the app is configured for Organization ${appOrganizationId}`,\n }\n }\n return {error: null}\n}\n","import {switchMap} from 'rxjs'\n\nimport {getClientState} from '../client/clientStore'\nimport {type Project} from '../project/project'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {defineFetcher} from '../store/fetcherStore'\nimport {buildQuery} from '../utils/buildQuery'\n\nconst API_VERSION = 'v2025-02-19'\n\n/** @public */\nexport interface ProjectsOptions<\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = true,\n> {\n organizationId?: string\n includeMembers?: IncludeMembers\n includeFeatures?: IncludeFeatures\n onlyExplicitMembership?: boolean\n}\n\nfunction normalizeProjectsOptions(options?: ProjectsOptions<boolean, boolean>) {\n return {\n organizationId: options?.organizationId,\n includeMembers: options?.includeMembers ?? false,\n includeFeatures: options?.includeFeatures ?? true,\n onlyExplicitMembership: options?.onlyExplicitMembership ?? false,\n }\n}\n\n/** @internal */\nexport function getProjectsCacheKey(\n _instance: SanityInstance,\n options?: ProjectsOptions<boolean, boolean>,\n): string {\n const {organizationId, includeMembers, includeFeatures, onlyExplicitMembership} =\n normalizeProjectsOptions(options)\n const orgKey = organizationId ? `:org:${organizationId}` : ''\n const membersKey = includeMembers ? ':members' : ''\n const featuresKey = includeFeatures ? ':features' : ''\n const explicitKey = onlyExplicitMembership ? ':explicit' : ''\n return `projects${orgKey}${membersKey}${featuresKey}${explicitKey}`\n}\n\n/**\n * Fetcher for the current user's projects (`GET /projects`), on the shared\n * fetcher cache.\n *\n * @internal\n */\nexport const projects = defineFetcher<\n [options?: ProjectsOptions<boolean, boolean>],\n Project<boolean, boolean>[]\n>({\n name: 'projects',\n getKey: getProjectsCacheKey,\n fetch: (instance) => (options) =>\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable.pipe(\n switchMap((client) =>\n client.observable.request<Project<boolean, boolean>[]>({\n url: '/projects',\n query: buildQuery(normalizeProjectsOptions(options)),\n tag: 'projects.list',\n }),\n ),\n ),\n tags: (data) => [\n {type: 'project', id: 'LIST'},\n ...data.map((project) => ({type: 'project', id: project.id})),\n ],\n})\n","import {switchMap} from 'rxjs'\n\nimport {getClientState} from '../client/clientStore'\nimport {type ProjectHandle} from '../config/sanityConfig'\nimport {projects} from '../projects/projects'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {defineFetcher} from '../store/fetcherStore'\nimport {buildQuery} from '../utils/buildQuery'\n\nconst API_VERSION = 'v2025-02-19'\n\n/** @public */\nexport interface ProjectMemberRole {\n name: string\n title: string\n description: string\n}\n\n/** @public */\nexport interface ProjectMember {\n id: string\n createdAt: string\n updatedAt: string\n isCurrentUser: boolean\n isRobot: boolean\n roles: ProjectMemberRole[]\n}\n\n/** @public */\nexport interface ProjectMetadata {\n color?: string\n externalStudioHost?: string\n initialTemplate?: string\n cliInitializedAt?: string\n integration: 'manage' | 'cli'\n}\n\n/**\n * The base fields returned from `/projects` for every project.\n * @public\n */\nexport interface ProjectBase {\n id: string\n displayName: string\n studioHost: string | null\n organizationId: string\n metadata: ProjectMetadata\n isBlocked: boolean\n isDisabled: boolean\n isDisabledByUser: boolean\n activityFeedEnabled: boolean\n /** Bare CDN URL of the logo; append image-pipeline params (`?w=&h=&fit=crop&auto=format`) for display. */\n logoUrl: string | null\n createdAt: string\n updatedAt: string\n}\n\n/**\n * A `Project` with `members` and/or `features` conditionally included\n * based on the query options used to fetch it.\n * @public\n */\nexport type Project<\n IncludeMembers extends boolean = true,\n IncludeFeatures extends boolean = true,\n> = ProjectBase &\n // `boolean extends T` is non-distributive — true only when T is the wide\n // `boolean`, in which case the field is optional. Literal `true`/`false`\n // fall through to the strict branch.\n (boolean extends IncludeMembers\n ? {members?: ProjectMember[]}\n : IncludeMembers extends true\n ? {members: ProjectMember[]}\n : unknown) &\n (boolean extends IncludeFeatures\n ? {features?: string[]}\n : IncludeFeatures extends true\n ? {features: string[]}\n : unknown)\n\n/** @public */\nexport interface ProjectOptions<\n IncludeMembers extends boolean = true,\n IncludeFeatures extends boolean = true,\n> extends ProjectHandle {\n includeMembers?: IncludeMembers\n includeFeatures?: IncludeFeatures\n}\n\nfunction normalizeProjectOptions(options?: ProjectOptions<boolean, boolean>) {\n return {\n includeMembers: options?.includeMembers ?? true,\n includeFeatures: options?.includeFeatures ?? true,\n }\n}\n\nfunction resolveProjectId(instance: SanityInstance, options?: ProjectOptions<boolean, boolean>) {\n const projectId = options?.projectId ?? instance.config.projectId\n if (!projectId) {\n throw new Error('A projectId is required to use the project API.')\n }\n return projectId\n}\n\n/** @internal */\nexport function getProjectCacheKey(\n instance: SanityInstance,\n options?: ProjectOptions<boolean, boolean>,\n): string {\n const projectId = resolveProjectId(instance, options)\n const {includeMembers, includeFeatures} = normalizeProjectOptions(options)\n const membersKey = includeMembers ? ':members' : ''\n const featuresKey = includeFeatures ? ':features' : ''\n return `project:${projectId}${membersKey}${featuresKey}`\n}\n\n/**\n * Fetcher for a single project (`GET /projects/:id`), on the shared fetcher\n * cache. Pre-seeds from the default {@link projects} list entry when it can\n * satisfy the read — the default list carries features but not members, so\n * only `includeMembers: false` reads seed.\n *\n * @internal\n */\nexport const project = defineFetcher<\n [options?: ProjectOptions<boolean, boolean>],\n Project<boolean, boolean>\n>({\n name: 'project',\n getKey: getProjectCacheKey,\n fetch: (instance) => (options) =>\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable.pipe(\n switchMap((client) =>\n client.observable.request<Project<boolean, boolean>>({\n url: `/projects/${resolveProjectId(instance, options)}`,\n query: buildQuery(normalizeProjectOptions(options)),\n tag: 'projects.get',\n }),\n ),\n ),\n tags: (data) => [{type: 'project', id: data.id}],\n initialData: (instance, options) => {\n if (normalizeProjectOptions(options).includeMembers) return undefined\n const snapshot = projects.getState(instance).getCurrent()\n if (snapshot.status !== 'success') return undefined\n const projectId = resolveProjectId(instance, options)\n const match = snapshot.data.find((item) => item.id === projectId)\n return match && {data: match, dataUpdatedAt: snapshot.dataUpdatedAt}\n },\n})\n","import {type Comment, type CommentStatus, type CommentThread} from './types'\n\n/**\n * What threading needs off a comment: its identity and parentage, plus the\n * fields a thread takes from its first comment.\n *\n * Structural rather than {@link Comment}, so the deprecated add-on dataset\n * store can thread its own comment shape through the same function.\n */\ninterface ThreadableComment {\n id: string\n createdAt: string\n threadId: string\n fieldPath: string\n status: CommentStatus\n parentCommentId?: string\n}\n\n/** A thread over whichever comment shape was threaded. */\ninterface ThreadOf<TComment> {\n threadId: string\n fieldPath: string\n parentComment: TComment\n replies: TComment[]\n commentsCount: number\n status: CommentStatus\n lastActivityAt: string\n}\n\n/**\n * Groups a flat comment list into threads.\n *\n * Users get {@link buildCommentThreads}, which is typed to {@link Comment}. This\n * one is generic so the deprecated add-on dataset store can thread its own\n * comment shape through the same code.\n *\n * @internal\n */\nexport function threadComments<TComment extends ThreadableComment>(\n comments: TComment[],\n): ThreadOf<TComment>[] {\n const repliesByParent = new Map<string, TComment[]>()\n\n for (const comment of comments) {\n if (!comment.parentCommentId) continue\n const existing = repliesByParent.get(comment.parentCommentId)\n if (existing) {\n existing.push(comment)\n } else {\n repliesByParent.set(comment.parentCommentId, [comment])\n }\n }\n\n const threads: ThreadOf<TComment>[] = []\n\n for (const parentComment of comments) {\n if (parentComment.parentCommentId) continue\n\n // The array is built above and owned here, so sorting in place is safe.\n const replies = (repliesByParent.get(parentComment.id) ?? []).sort((a, b) =>\n a.createdAt.localeCompare(b.createdAt),\n )\n\n const lastReply = replies[replies.length - 1]\n\n threads.push({\n threadId: parentComment.threadId,\n fieldPath: parentComment.fieldPath,\n parentComment,\n replies,\n commentsCount: replies.length + 1,\n status: parentComment.status,\n lastActivityAt: lastReply ? lastReply.createdAt : parentComment.createdAt,\n })\n }\n\n return threads\n}\n\n/**\n * Groups a flat comment list into threads, the same way `getCommentThreadsState`\n * and `useCommentThreads` do.\n *\n * Use it on the flat list from `getCommentsQueryState` or `useCommentsQuery`\n * when you want threads, for example for comments read across several\n * documents in one query. Pass replies along with their parents: a thread is\n * assembled from one input, so group by anything else after threading, not\n * before.\n *\n * A thread's parent is the comment with no `parentCommentId`; replies point at\n * the parent's `id`. Replies whose parent is missing from the input are\n * dropped, which is what happens when a parent is deleted but its replies have\n * not disappeared yet.\n *\n * Threads come back in the order their parents appear in `comments`, so passing\n * the store's newest-first list gives newest-thread-first. Replies within a\n * thread are always oldest first, since that is reading order.\n *\n * @param comments - The comments to group, replies included\n * @returns One thread per parent comment in `comments`\n * @beta\n */\nexport function buildCommentThreads(comments: Comment[]): CommentThread[] {\n return threadComments(comments)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,yBAAyB,UAA0D;CACjG,OAAO,+BAA+B,QAAQ,CAAC,CAAC,KAC9C,KAAK,mBAAmB,kB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QAAQ,iBAAiB;EAC9B,IAAM,WAAW,gBAAgB,IAAI,QAAQ,eAAe;EAC5D,AAAI,WACF,SAAS,KAAK,OAAO,IAErB,gBAAgB,IAAI,QAAQ,iBAAiB,CAAC,OAAO,CAAC;CAE1D;CAEA,IAAM,UAAgC,CAAC;CAEvC,KAAK,IAAM,iBAAiB,UAAU;EACpC,IAAI,cAAc,iBAAiB;EAGnC,IAAM,WAAW,gBAAgB,IAAI,cAAc,EAAE,KAAK,CAAC,EAAA,CAAG,MAAM,GAAG,MACrE,EAAE,UAAU,cAAc,EAAE,SAAS,CACvC,GAEM,YAAY,QAAQ,QAAQ,SAAS;EAE3C,QAAQ,KAAK;GACX,UAAU,cAAc;GACxB,WAAW,cAAc;GACzB;GACA;GACA,eAAe,QAAQ,SAAS;GAChC,QAAQ,cAAc;GACtB,gBAAgB,YAAY,UAAU,YAAY,cAAc;EAClE,CAAC;CACH;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,oBAAoB,UAAsC;CACxE,OAAO,eAAe,QAAQ;AAChC"}
|
|
1
|
+
{"version":3,"file":"buildCommentThreads-YikCB5T5.js","names":["API_VERSION"],"sources":["../src/organization/appOrganization.ts","../src/project/organizationVerification.ts","../src/projects/projects.ts","../src/project/project.ts","../src/comments/buildCommentThreads.ts"],"sourcesContent":["import {defer, filter, map, type Observable} from 'rxjs'\n\nimport {getDashboardMessageBus} from '../dashboard/messageBus/store'\nimport {getDashboardOrganizationId, getTopicState} from '../dashboard/messageBus/topicStore'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {type OrganizationBase} from './organization'\n\n/** What the `organizations.current` topic publishes, `null` when none is selected. */\ntype CurrentOrganization = Pick<OrganizationBase, 'id' | 'name' | 'slug'> | null\n\n/**\n * The organization the app itself belongs to, as opposed to the one that owns\n * any particular resource.\n *\n * Inside the Dashboard this arrives with the app, from whichever runtime is\n * hosting it. Outside it, `organizationId` on the `SanityConfig` says so.\n * Emits `undefined` when neither has one, leaving the caller to decide whether\n * that is fatal.\n *\n * @remarks\n * On a message bus this waits for the host's first `organizations.current`\n * publish, with no deadline: a host that never publishes leaves comment reads\n * and organization-scoped user lists unresolved rather than failing. Waiting is\n * deliberate, since resolving against the config first would point a read at one\n * organization and then another. The topic is shared, so a failure another\n * reader's `resolveTopic` records on it errors this stream too.\n *\n * @internal\n */\nexport function observeAppOrganizationId(instance: SanityInstance): Observable<string | undefined> {\n return observeDashboardOrganizationId(instance).pipe(\n map((organizationId) => organizationId ?? instance.config.organizationId),\n )\n}\n\n/**\n * The Dashboard's current organization, or `undefined` when the app is not\n * running in one.\n *\n * Both Dashboard runtimes are covered, the same way `getDashboardOrganizationId`\n * covers them: the topic once this instance has a bus connection, and `_context`\n * otherwise. The connection is read per subscription rather than once at module\n * scope, because the host installs the bus and may not have run by the time this\n * module is first imported.\n */\nfunction observeDashboardOrganizationId(instance: SanityInstance): Observable<string | undefined> {\n return defer(() => {\n if (!getDashboardMessageBus(instance)) {\n return getDashboardOrganizationId(instance).observable\n }\n\n return getTopicState(instance, 'organizations.current').observable.pipe(\n // `undefined` means the host has yet to publish, which is not the same as\n // there being no organization. Waiting keeps a read from resolving against\n // the config fallback and then changing organization a moment later.\n filter((organization) => organization !== undefined),\n map((organization) => (organization as CurrentOrganization)?.id),\n )\n })\n}\n","/**\n * Error message returned by the organization verification\n * @public\n */\nexport interface OrgVerificationResult {\n error: string | null\n}\n\n/**\n * Compares a project's actual organization ID with the expected organization ID.\n * @public\n */\nexport function compareProjectOrganization(\n projectId: string,\n projectOrganizationId: string | null | undefined,\n appOrganizationId: string,\n): OrgVerificationResult {\n if (projectOrganizationId !== appOrganizationId) {\n return {\n error:\n `Project ${projectId} belongs to Organization ${projectOrganizationId ?? 'unknown'}, ` +\n `but the app is configured for Organization ${appOrganizationId}`,\n }\n }\n return {error: null}\n}\n","import {switchMap} from 'rxjs'\n\nimport {getClientState} from '../client/clientStore'\nimport {type Project} from '../project/project'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {defineFetcher} from '../store/fetcherStore'\nimport {buildQuery} from '../utils/buildQuery'\n\nconst API_VERSION = 'v2025-02-19'\n\n/** @public */\nexport interface ProjectsOptions<\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = true,\n> {\n organizationId?: string\n includeMembers?: IncludeMembers\n includeFeatures?: IncludeFeatures\n onlyExplicitMembership?: boolean\n}\n\nfunction normalizeProjectsOptions(options?: ProjectsOptions<boolean, boolean>) {\n return {\n organizationId: options?.organizationId,\n includeMembers: options?.includeMembers ?? false,\n includeFeatures: options?.includeFeatures ?? true,\n onlyExplicitMembership: options?.onlyExplicitMembership ?? false,\n }\n}\n\n/** @internal */\nexport function getProjectsCacheKey(\n _instance: SanityInstance,\n options?: ProjectsOptions<boolean, boolean>,\n): string {\n const {organizationId, includeMembers, includeFeatures, onlyExplicitMembership} =\n normalizeProjectsOptions(options)\n const orgKey = organizationId ? `:org:${organizationId}` : ''\n const membersKey = includeMembers ? ':members' : ''\n const featuresKey = includeFeatures ? ':features' : ''\n const explicitKey = onlyExplicitMembership ? ':explicit' : ''\n return `projects${orgKey}${membersKey}${featuresKey}${explicitKey}`\n}\n\n/**\n * Fetcher for the current user's projects (`GET /projects`), on the shared\n * fetcher cache.\n *\n * @internal\n */\nexport const projects = defineFetcher<\n [options?: ProjectsOptions<boolean, boolean>],\n Project<boolean, boolean>[]\n>({\n name: 'projects',\n getKey: getProjectsCacheKey,\n fetch: (instance) => (options) =>\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable.pipe(\n switchMap((client) =>\n client.observable.request<Project<boolean, boolean>[]>({\n url: '/projects',\n query: buildQuery(normalizeProjectsOptions(options)),\n tag: 'projects.list',\n }),\n ),\n ),\n tags: (data) => [\n {type: 'project', id: 'LIST'},\n ...data.map((project) => ({type: 'project', id: project.id})),\n ],\n})\n","import {switchMap} from 'rxjs'\n\nimport {getClientState} from '../client/clientStore'\nimport {type ProjectHandle} from '../config/sanityConfig'\nimport {projects} from '../projects/projects'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {defineFetcher} from '../store/fetcherStore'\nimport {buildQuery} from '../utils/buildQuery'\n\nconst API_VERSION = 'v2025-02-19'\n\n/** @public */\nexport interface ProjectMemberRole {\n name: string\n title: string\n description: string\n}\n\n/** @public */\nexport interface ProjectMember {\n id: string\n createdAt: string\n updatedAt: string\n isCurrentUser: boolean\n isRobot: boolean\n roles: ProjectMemberRole[]\n}\n\n/** @public */\nexport interface ProjectMetadata {\n color?: string\n externalStudioHost?: string\n initialTemplate?: string\n cliInitializedAt?: string\n integration: 'manage' | 'cli'\n}\n\n/**\n * The base fields returned from `/projects` for every project.\n * @public\n */\nexport interface ProjectBase {\n id: string\n displayName: string\n studioHost: string | null\n organizationId: string\n metadata: ProjectMetadata\n isBlocked: boolean\n isDisabled: boolean\n isDisabledByUser: boolean\n activityFeedEnabled: boolean\n /** Bare CDN URL of the logo; append image-pipeline params (`?w=&h=&fit=crop&auto=format`) for display. */\n logoUrl: string | null\n createdAt: string\n updatedAt: string\n}\n\n/**\n * A `Project` with `members` and/or `features` conditionally included\n * based on the query options used to fetch it.\n * @public\n */\nexport type Project<\n IncludeMembers extends boolean = true,\n IncludeFeatures extends boolean = true,\n> = ProjectBase &\n // `boolean extends T` is non-distributive — true only when T is the wide\n // `boolean`, in which case the field is optional. Literal `true`/`false`\n // fall through to the strict branch.\n (boolean extends IncludeMembers\n ? {members?: ProjectMember[]}\n : IncludeMembers extends true\n ? {members: ProjectMember[]}\n : unknown) &\n (boolean extends IncludeFeatures\n ? {features?: string[]}\n : IncludeFeatures extends true\n ? {features: string[]}\n : unknown)\n\n/** @public */\nexport interface ProjectOptions<\n IncludeMembers extends boolean = true,\n IncludeFeatures extends boolean = true,\n> extends ProjectHandle {\n includeMembers?: IncludeMembers\n includeFeatures?: IncludeFeatures\n}\n\nfunction normalizeProjectOptions(options?: ProjectOptions<boolean, boolean>) {\n return {\n includeMembers: options?.includeMembers ?? true,\n includeFeatures: options?.includeFeatures ?? true,\n }\n}\n\nfunction resolveProjectId(instance: SanityInstance, options?: ProjectOptions<boolean, boolean>) {\n const projectId = options?.projectId ?? instance.config.projectId\n if (!projectId) {\n throw new Error('A projectId is required to use the project API.')\n }\n return projectId\n}\n\n/** @internal */\nexport function getProjectCacheKey(\n instance: SanityInstance,\n options?: ProjectOptions<boolean, boolean>,\n): string {\n const projectId = resolveProjectId(instance, options)\n const {includeMembers, includeFeatures} = normalizeProjectOptions(options)\n const membersKey = includeMembers ? ':members' : ''\n const featuresKey = includeFeatures ? ':features' : ''\n return `project:${projectId}${membersKey}${featuresKey}`\n}\n\n/**\n * Fetcher for a single project (`GET /projects/:id`), on the shared fetcher\n * cache. Pre-seeds from the default {@link projects} list entry when it can\n * satisfy the read — the default list carries features but not members, so\n * only `includeMembers: false` reads seed.\n *\n * @internal\n */\nexport const project = defineFetcher<\n [options?: ProjectOptions<boolean, boolean>],\n Project<boolean, boolean>\n>({\n name: 'project',\n getKey: getProjectCacheKey,\n fetch: (instance) => (options) =>\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable.pipe(\n switchMap((client) =>\n client.observable.request<Project<boolean, boolean>>({\n url: `/projects/${resolveProjectId(instance, options)}`,\n query: buildQuery(normalizeProjectOptions(options)),\n tag: 'projects.get',\n }),\n ),\n ),\n tags: (data) => [{type: 'project', id: data.id}],\n initialData: (instance, options) => {\n if (normalizeProjectOptions(options).includeMembers) return undefined\n const snapshot = projects.getState(instance).getCurrent()\n if (snapshot.status !== 'success') return undefined\n const projectId = resolveProjectId(instance, options)\n const match = snapshot.data.find((item) => item.id === projectId)\n return match && {data: match, dataUpdatedAt: snapshot.dataUpdatedAt}\n },\n})\n","import {type Comment, type CommentStatus, type CommentThread} from './types'\n\n/**\n * What threading needs off a comment: its identity and parentage, plus the\n * fields a thread takes from its first comment.\n *\n * Structural rather than {@link Comment}, so the deprecated add-on dataset\n * store can thread its own comment shape through the same function.\n */\ninterface ThreadableComment {\n id: string\n createdAt: string\n threadId: string\n fieldPath: string\n status: CommentStatus\n parentCommentId?: string\n}\n\n/** A thread over whichever comment shape was threaded. */\ninterface ThreadOf<TComment> {\n threadId: string\n fieldPath: string\n parentComment: TComment\n replies: TComment[]\n commentsCount: number\n status: CommentStatus\n lastActivityAt: string\n}\n\n/**\n * Groups a flat comment list into threads.\n *\n * Users get {@link buildCommentThreads}, which is typed to {@link Comment}. This\n * one is generic so the deprecated add-on dataset store can thread its own\n * comment shape through the same code.\n *\n * @internal\n */\nexport function threadComments<TComment extends ThreadableComment>(\n comments: TComment[],\n): ThreadOf<TComment>[] {\n const repliesByParent = new Map<string, TComment[]>()\n\n for (const comment of comments) {\n if (!comment.parentCommentId) continue\n const existing = repliesByParent.get(comment.parentCommentId)\n if (existing) {\n existing.push(comment)\n } else {\n repliesByParent.set(comment.parentCommentId, [comment])\n }\n }\n\n const threads: ThreadOf<TComment>[] = []\n\n for (const parentComment of comments) {\n if (parentComment.parentCommentId) continue\n\n // The array is built above and owned here, so sorting in place is safe.\n const replies = (repliesByParent.get(parentComment.id) ?? []).sort((a, b) =>\n a.createdAt.localeCompare(b.createdAt),\n )\n\n const lastReply = replies[replies.length - 1]\n\n threads.push({\n threadId: parentComment.threadId,\n fieldPath: parentComment.fieldPath,\n parentComment,\n replies,\n commentsCount: replies.length + 1,\n status: parentComment.status,\n lastActivityAt: lastReply ? lastReply.createdAt : parentComment.createdAt,\n })\n }\n\n return threads\n}\n\n/**\n * Groups a flat comment list into threads, the same way `getCommentThreadsState`\n * and `useCommentThreads` do.\n *\n * Use it on the flat list from `getCommentsQueryState` or `useCommentsQuery`\n * when you want threads, for example for comments read across several\n * documents in one query. Pass replies along with their parents: a thread is\n * assembled from one input, so group by anything else after threading, not\n * before.\n *\n * A thread's parent is the comment with no `parentCommentId`; replies point at\n * the parent's `id`. Replies whose parent is missing from the input are\n * dropped, which is what happens when a parent is deleted but its replies have\n * not disappeared yet.\n *\n * Threads come back in the order their parents appear in `comments`, so passing\n * the store's newest-first list gives newest-thread-first. Replies within a\n * thread are always oldest first, since that is reading order.\n *\n * @param comments - The comments to group, replies included\n * @returns One thread per parent comment in `comments`\n * @beta\n */\nexport function buildCommentThreads(comments: Comment[]): CommentThread[] {\n return threadComments(comments)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,yBAAyB,UAA0D;CACjG,OAAO,+BAA+B,QAAQ,CAAC,CAAC,KAC9C,KAAK,mBAAmB,kBAAkB,SAAS,OAAO,cAAc,CAC1E;AACF;;;;;;;;;;;AAYA,SAAS,+BAA+B,UAA0D;CAChG,OAAO,YACA,uBAAuB,QAAQ,IAI7B,cAAc,UAAU,uBAAuB,CAAC,CAAC,WAAW,KAIjE,QAAQ,iBAAiB,iBAAiB,KAAA,CAAS,GACnD,KAAK,iBAAkB,cAAsC,EAAE,CACjE,IATS,2BAA2B,QAAQ,CAAC,CAAC,UAU/C;AACH;;;;;AC/CA,SAAgB,2BACd,WACA,uBACA,mBACuB;CAQvB,OAPI,0BAA0B,oBAOvB,EAAC,OAAO,KAAI,IANV,EACL,OACE,WAAW,UAAU,2BAA2B,yBAAyB,UAAU,+CACrC,oBAClD;AAGJ;ACJA,SAAS,yBAAyB,SAA6C;CAC7E,OAAO;EACL,gBAAgB,SAAS;EACzB,gBAAgB,SAAS,kBAAkB;EAC3C,iBAAiB,SAAS,mBAAmB;EAC7C,wBAAwB,SAAS,0BAA0B;CAC7D;AACF;;AAGA,SAAgB,oBACd,WACA,SACQ;CACR,IAAM,EAAC,gBAAgB,gBAAgB,iBAAiB,2BACtD,yBAAyB,OAAO;CAKlC,OAAO,WAJQ,iBAAiB,QAAQ,mBAAmB,KACxC,iBAAiB,aAAa,KAC7B,kBAAkB,cAAc,KAChC,yBAAyB,cAAc;AAE7D;;;;;;;AAQA,MAAa,WAAW,cAGtB;CACA,MAAM;CACN,QAAQ;CACR,QAAQ,cAAc,YACpB,eAAe,UAAU;EAAC,YAAYA;EAAa,OAA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AAS,WAAW,WAAW;EACnC,IAAM,YAAY,iBAAiB,UAAU,OAAO,GAC9C,QAAQ,SAAS,KAAK,MAAM,SAAS,KAAK,OAAO,SAAS;EAChE,OAAO,SAAS;GAAC,MAAM;GAAO,eAAe,SAAS;EAAa;CACrE;AACF,CAAC;;;;;;;;;;AC/GD,SAAgB,eACd,UACsB;CACtB,IAAM,kCAAkB,IAAI,IAAwB;CAEpD,KAAK,IAAM,WAAW,UAAU;EAC9B,IAAI,CAAC,QAAQ,iBAAiB;EAC9B,IAAM,WAAW,gBAAgB,IAAI,QAAQ,eAAe;EAC5D,AAAI,WACF,SAAS,KAAK,OAAO,IAErB,gBAAgB,IAAI,QAAQ,iBAAiB,CAAC,OAAO,CAAC;CAE1D;CAEA,IAAM,UAAgC,CAAC;CAEvC,KAAK,IAAM,iBAAiB,UAAU;EACpC,IAAI,cAAc,iBAAiB;EAGnC,IAAM,WAAW,gBAAgB,IAAI,cAAc,EAAE,KAAK,CAAC,EAAA,CAAG,MAAM,GAAG,MACrE,EAAE,UAAU,cAAc,EAAE,SAAS,CACvC,GAEM,YAAY,QAAQ,QAAQ,SAAS;EAE3C,QAAQ,KAAK;GACX,UAAU,cAAc;GACxB,WAAW,cAAc;GACzB;GACA;GACA,eAAe,QAAQ,SAAS;GAChC,QAAQ,cAAc;GACtB,gBAAgB,YAAY,UAAU,YAAY,cAAc;EAClE,CAAC;CACH;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,oBAAoB,UAAsC;CACxE,OAAO,eAAe,QAAQ;AAChC"}
|
package/dist/index.js
CHANGED
|
@@ -3,9 +3,9 @@ import { A as SUBMISSION_RETRY_BASE_DELAY, B as getDefaultStorage, D as API_VERS
|
|
|
3
3
|
import { a as getDashboardMessageBus, h as randomUuid, m as randomId, n as getDashboardOrganizationId, r as getTopicState } from "./topicStore-CKBdgAz7.js";
|
|
4
4
|
import { n as isObject, r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
|
|
5
5
|
import { n as getClient, r as getClientState } from "./clientStore-eysItBQl.js";
|
|
6
|
-
import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "./
|
|
7
|
-
import { a as compareProjectOrganization, i as projects, n as threadComments, o as observeAppOrganizationId, r as project } from "./buildCommentThreads-
|
|
8
|
-
import { A as getDocumentIdsFromHandleLikes, B as ActionError, D as applyFirstQueuedTransaction, F as revertOutgoingTransaction, H as processMutations, I as throwDocumentError, K as getProjectAccessErrorProjectId, L as transitionAppliedTransactionsToOutgoing, M as manageSubscriberIds, N as queueTransaction, O as applyRemoteDocument, P as removeQueuedTransaction, R as calculatePermissions, S as toPreferenceError, T as setFavorite, U as getReleaseDocumentId, V as patchOperations, W as isReleaseAction, _ as setUsersError, b as USERS_STATE_CLEAR_DELAY, c as getActiveReleasesState, d as cancelRequest, f as getUsersKey, g as setUsersData, h as removeSubscription, i as getQueryState, j as isBatchableTransaction, k as cleanupOutgoingTransaction, l as getAllReleasesState, m as parseUsersKey, o as resolveQuery, p as initializeRequest, s as getPerspectiveState, t as CORE_SDK_VERSION, u as addSubscription, v as updateLastLoadMoreRequest, w as favorites, x as PreferenceError, y as PROJECT_API_VERSION, z as createGrantsLookup } from "./version-
|
|
6
|
+
import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "./types-C8dSHL5E.js";
|
|
7
|
+
import { a as compareProjectOrganization, i as projects, n as threadComments, o as observeAppOrganizationId, r as project } from "./buildCommentThreads-YikCB5T5.js";
|
|
8
|
+
import { A as getDocumentIdsFromHandleLikes, B as ActionError, D as applyFirstQueuedTransaction, F as revertOutgoingTransaction, H as processMutations, I as throwDocumentError, K as getProjectAccessErrorProjectId, L as transitionAppliedTransactionsToOutgoing, M as manageSubscriberIds, N as queueTransaction, O as applyRemoteDocument, P as removeQueuedTransaction, R as calculatePermissions, S as toPreferenceError, T as setFavorite, U as getReleaseDocumentId, V as patchOperations, W as isReleaseAction, _ as setUsersError, b as USERS_STATE_CLEAR_DELAY, c as getActiveReleasesState, d as cancelRequest, f as getUsersKey, g as setUsersData, h as removeSubscription, i as getQueryState, j as isBatchableTransaction, k as cleanupOutgoingTransaction, l as getAllReleasesState, m as parseUsersKey, o as resolveQuery, p as initializeRequest, s as getPerspectiveState, t as CORE_SDK_VERSION, u as addSubscription, v as updateLastLoadMoreRequest, w as favorites, x as PreferenceError, y as PROJECT_API_VERSION, z as createGrantsLookup } from "./version-C4jlyyUU.js";
|
|
9
9
|
import { ClientError, CorsOriginError } from "@sanity/client";
|
|
10
10
|
import { BehaviorSubject, EMPTY, NEVER, Observable, ReplaySubject, Subject, Subscription, auditTime, catchError, combineLatest, concat, concatMap, debounceTime, defer, distinctUntilChanged, filter, first, firstValueFrom, from, fromEvent, groupBy, map, merge, mergeMap, of, pairwise, partition, race, share, skip, startWith, switchMap, take, takeUntil, tap, throwError, timer, withLatestFrom } from "rxjs";
|
|
11
11
|
import "@sanity/types";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { i as bindActionGlobally, l as setCleanupInterval, o as UPSTREAM_CLOSE_DELAY_MS, s as defineStore, t as createStateSourceAction, u as setCleanupTimeout } from "./createStateSourceAction-Bn0po7Z3.js";
|
|
2
2
|
import { a as getClientAuthState, x as retryRead, y as classifyFailure } from "./authStore-CinLcYHr.js";
|
|
3
|
+
import "@sanity/client";
|
|
3
4
|
import { EMPTY, Subscription, concatMap, defer, expand, filter, firstValueFrom, fromEvent, map, of, take, tap, toArray } from "rxjs";
|
|
4
5
|
import "@sanity/types";
|
|
5
6
|
import { stringifyPath } from "@sanity/json-match";
|
|
@@ -479,4 +480,4 @@ function toCommentFieldPath(path) {
|
|
|
479
480
|
}
|
|
480
481
|
export { definePagedFetcher as i, defineFetcher as n, defineMutation as r, toCommentFieldPath as t };
|
|
481
482
|
|
|
482
|
-
//# sourceMappingURL=
|
|
483
|
+
//# sourceMappingURL=types-C8dSHL5E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-C8dSHL5E.js","names":[],"sources":["../src/store/fetcherStore.ts","../src/comments/commentFieldPath.ts"],"sourcesContent":["import {\n concatMap,\n defer,\n EMPTY,\n expand,\n filter,\n firstValueFrom,\n fromEvent,\n map,\n type Observable,\n of,\n Subscription,\n take,\n tap,\n toArray,\n} from 'rxjs'\n\nimport {getClientAuthState} from '../auth/authStore'\nimport {classifyFailure, retryRead} from '../client/retry'\nimport {setCleanupInterval, setCleanupTimeout} from '../utils/setCleanupTimeout'\nimport {bindActionGlobally} from './createActionBinder'\nimport {type SanityInstance} from './createSanityInstance'\nimport {\n createStateSourceAction,\n type SelectorContext,\n type StateSource,\n} from './createStateSourceAction'\nimport {UPSTREAM_CLOSE_DELAY_MS} from './createStoreInstance'\nimport {type StoreState} from './createStoreState'\nimport {defineStore, type StoreContext} from './defineStore'\n\nconst DEFAULT_STALE_TIME = 30_000\nconst DEFAULT_GC_TIME = 300_000\n\n/**\n * Identifies cached data for invalidation, matched across the whole store.\n * A fetcher declares the tags each of its entries carries (via\n * {@link FetcherDefinition.tags}); a mutation declares the tags it invalidates\n * (via {@link MutationDefinition.invalidates}).\n *\n * When invalidating,`{type: 'organization'}` matches every entry carrying any `organization` tag;\n * `{type: 'organization', id: 'abc'}` matches only entries carrying that exact pair.\n * List entries carry a `{type, id: 'LIST'}` sentinel plus one tag per item, so a\n * \"create\" mutation can refetch lists without touching unrelated detail entries.\n *\n * @internal\n */\nexport interface CacheTag {\n type: string\n /** Specific id, or the `'LIST'` sentinel for list entries */\n id?: string | number\n}\n\n/**\n * The reactive value of one cache entry, as exposed by\n * {@link Fetcher.getState}. React hooks consume this envelope directly.\n * Discriminated on `status`, so narrowing gives correctly-typed `data`:\n * `'success'` is the only arm carrying data, and a background failure while\n * data still renders surfaces on the `'success'` arm's `error`.\n *\n * `isFetching` is common to all arms: a fetch for this entry is in flight\n * (initial load, revalidation, or poll).\n *\n * @internal\n */\nexport type FetcherSnapshot<TData> =\n | {\n /** No data yet — initial fetch in flight or not started */\n status: 'pending'\n data: undefined\n error: undefined\n isFetching: boolean\n dataUpdatedAt: undefined\n isFallback?: never\n }\n | {\n /** Data available — possibly stale, possibly revalidating */\n status: 'success'\n data: TData\n /** Most recent background-fetch failure, cleared by the next successful fetch */\n error: unknown\n isFetching: boolean\n /** Epoch ms of the fetch that produced `data` */\n dataUpdatedAt: number\n /** `data` is the definition's `fallbackData`, not an answer */\n isFallback?: true\n }\n | {\n /** The last fetch failed and no data exists to serve */\n status: 'error'\n data: undefined\n error: unknown\n isFetching: boolean\n dataUpdatedAt: undefined\n isFallback?: never\n }\n\n/**\n * A typed description of one cached, parameterised read of an API response —\n * here is a single cache per {@link SanityInstance}; every definition registers\n * into it and its `name` namespaces its keys. A list and a detail read are two\n * definitions over the one cache, not two caches.\n *\n * Entry lifecycle: fresh → stale → collected. Fresh entries are served from\n * cache with no fetch; stale entries are served immediately and revalidated in\n * the background (stale-while-revalidate); collected entries are removed once\n * their `gcTime` elapses after the last unsubscribe, so the next subscriber\n * suspends.\n *\n * @internal\n */\nexport interface FetcherDefinition<TParams extends unknown[], TData> {\n /** Namespaces this fetcher's keys in the shared cache; used for devtools and request-tag derivation */\n name: string\n /**\n * Fetches the data once. Return an observable that emits the result and\n * completes. A failure is retried by the rules of {@link retryRead}: a 401\n * once the credential changes, a network error or 5xx after a backoff. Each\n * retry calls the function `fetch` returns again, side effects included.\n */\n fetch: (instance: SanityInstance) => (...params: TParams) => Observable<TData>\n /** Converts params into the cache key that identifies an entry (unique within `name`) */\n getKey: (instance: SanityInstance, ...params: TParams) => string\n /**\n * Cache tags each entry carries, for cache-wide invalidation. A static array,\n * or a function of the fetched data when tags depend on the response (e.g. one\n * tag per list item).\n */\n tags?: CacheTag[] | ((data: TData, ...params: TParams) => CacheTag[])\n /**\n * How long fetched data is fresh, in ms. Fresh entries never refetch;\n * stale entries serve cached data and revalidate in the background.\n * @defaultValue 30_000\n */\n staleTime?: number\n /**\n * How long an entry survives after its last unsubscribe before it is garbage\n * collected, in ms. The clock starts at the last unsubscribe — entries with\n * active subscribers are never collected.\n * @defaultValue 300_000\n */\n gcTime?: number\n /**\n * Refetch on this interval (ms) while the entry has at least one subscriber,\n * independent of staleness, or `false` to disable polling. May be a function\n * of `(instance, ...params)` when individual callers can override the interval.\n * When multiple subscribers watch the same entry with different intervals, the\n * shortest positive interval wins; polling stops once every subscriber opts out.\n * Ticks are skipped while `document.hidden`. Off by default.\n */\n refetchInterval?:\n | number\n | false\n | ((instance: SanityInstance, ...params: TParams) => number | false | undefined)\n /**\n * Whether an entry with subscribers refetches when the tab becomes visible again: once stale\n * (`true`), never (`false`), or however fresh it is (`'always'`). `refetchOnWindowFocus: false`\n * in an app's `SanityConfig` turns it off for that app's entries.\n * @defaultValue true\n */\n refetchOnWindowFocus?: boolean | 'always'\n /**\n * Consulted once, when an entry is being created and no cached data exists for\n * it. Return data pulled from another fetcher in the same cache — read via its\n * ordinary `getState(instance, ...).getCurrent()`, e.g. a detail entry pulling\n * its item out of the cached list — to skip or soften the initial fetch.\n * `dataUpdatedAt` must be when the source data was fetched, not \"now\": staleness\n * is measured from it. Return `undefined` to fetch as normal.\n */\n initialData?: (\n instance: SanityInstance,\n ...params: TParams\n ) => {data: TData; dataUpdatedAt: number} | undefined\n /**\n * Data to show while an entry has none and its fetch fails in a way a retry may fix, like a\n * network error or a 5xx. It shows as stale data while the fetch keeps retrying, with the\n * failure on `error` once the retries run out, and the next success replaces it. A failure that\n * retrying can't fix still errors.\n */\n fallbackData?: (instance: SanityInstance, ...params: TParams) => TData\n}\n\n/**\n * A typed handle over the shared fetcher cache, returned by\n * {@link defineFetcher}. It is a view onto the entries under its definition's\n * `name`, not a cache of its own.\n *\n * @internal\n */\nexport interface Fetcher<TParams extends unknown[], TData> {\n /** Reactive envelope for one entry. Subscribing triggers fetching per staleness rules. */\n getState: (instance: SanityInstance, ...params: TParams) => StateSource<FetcherSnapshot<TData>>\n /**\n * Resolves with the entry's first available data — the promise a suspending\n * component throws. Rejects when the fetch fails, which for a network error\n * or 5xx is once its retries run out, unless the definition has `fallbackData`:\n * then it resolves with that. When the entry's last fetch failed,\n * fetches again straight away, even if a retry is still waiting.\n */\n resolveState: (instance: SanityInstance, ...params: TParams) => Promise<TData>\n /**\n * Marks the entry stale. If it has active subscribers it refetches immediately;\n * otherwise it refetches on next subscribe.\n */\n invalidate: (instance: SanityInstance, ...params: TParams) => void\n /** {@link Fetcher.invalidate} for every entry under this fetcher's `name`. */\n invalidateAll: (instance: SanityInstance) => void\n /**\n * Imperative fetch, bypassing staleness. Dedupes against an in-flight fetch.\n * Resolves with the entry's data as held by the cache once the fetch settles.\n */\n refetch: (instance: SanityInstance, ...params: TParams) => Promise<TData>\n}\n\n/**\n * Writes an entry's data in any fetcher. Passed to {@link MutationDefinition}\n * callbacks — mutations are the only holders of arbitrary write access; read\n * fetchers pull their data (see {@link FetcherDefinition.initialData}). Inside\n * `onMutate`, every write is a pending change that comes off when the mutation\n * settles; inside `onSuccess`, writes are the server's answer.\n *\n * @internal\n */\nexport type CacheWriter = <TParams extends unknown[], TData>(\n fetcher: Fetcher<TParams, TData>,\n params: TParams,\n updater: TData | ((current: TData | undefined) => TData),\n) => void\n\n/**\n * Resolves when the mutation settles on the server. `invalidated` tracks the\n * background reconciliation — the refetches triggered by\n * {@link MutationDefinition.invalidates} — for the rare caller that must wait for\n * full reconvergence rather than server settlement.\n *\n * @internal\n */\nexport interface MutationResult<TResult> {\n /** The server response */\n data: TResult\n /** Settles when the refetches of matched active entries complete */\n invalidated: Promise<void>\n}\n\n/**\n * Defines a mutation with optimistic cache updates. Lifecycle:\n *\n * 1. `onMutate` applies optimistic writes synchronously — the UI updates before\n * the request leaves. Each write is kept as a pending change on its entry, on\n * top of the entry's confirmed data, so other mutations' answers and refetches\n * land underneath it rather than replacing it.\n * 2. The request runs, once earlier mutations with the same `scope` have\n * settled, so their answers come back in order. On failure, this mutation's\n * pending changes come off and any others stay, so failure ends the\n * lifecycle here.\n * 3. On success, `onSuccess` may write the server response; it becomes the\n * entry's confirmed data in place of this mutation's changes. An entry\n * `onSuccess` doesn't write keeps the changes as confirmed.\n * 4. On success, `invalidates` tags mark matching entries across the cache\n * stale (active entries refetch), so the cache reconverges on server truth\n * even if the optimistic shape was wrong.\n *\n * @internal\n */\nexport interface MutationDefinition<TInput, TResult> {\n /** Unique mutation name, used for devtools and request-tag derivation */\n name: string\n /** Creates the observable that performs the server mutation */\n mutationFn: (instance: SanityInstance) => (input: TInput) => Observable<TResult>\n /**\n * Mutations with the same scope are sent one at a time, in the order they're made, so the server\n * keeps the last one. Without a scope, a mutation is sent straight away.\n */\n scope?: (input: TInput) => string\n /** Optimistic cache writes, applied synchronously before the request */\n onMutate?: (write: CacheWriter, input: TInput) => void\n /** Reconcile the cache with the server response, avoiding a refetch round-trip */\n onSuccess?: (write: CacheWriter, result: TResult, input: TInput) => void\n /**\n * Cache tags to invalidate on success. Failure invalidates nothing: the\n * mutation's optimistic changes come off, and any server-side ambiguity (e.g.\n * timeout after commit) heals via `staleTime`.\n * A static array, or a function of the result/input.\n */\n invalidates?: CacheTag[] | ((result: TResult, input: TInput) => CacheTag[])\n}\n\n// --- Internal cache machinery -------------------------------------------------\n\n/** Internal bookkeeping carried by every entry, on top of the public {@link FetcherSnapshot} fields. */\ninterface CacheEntryMeta {\n fetcherName: string\n /** The entry's cache key — unique across the whole cache */\n key: string\n params: unknown[]\n instance: SanityInstance\n /** Bumps on every write; a fetch whose result lands on a changed version is discarded */\n version: number\n /** Forced stale by invalidation, independent of `staleTime` */\n forcedStale: boolean\n tags: CacheTag[]\n subscriptions: number\n /** Optimistic writes of mutations still in flight, applied in order on top of `confirmed` */\n pending: PendingChange[]\n /** What the entry shows without `pending`; only set while there are pending changes */\n confirmed: Confirmed | undefined\n /** The definition's `fallbackData`, shown while the entry has no data and its fetch is retried */\n fallback?: unknown\n}\n\n/** One optimistic write, tagged with the mutation call that made it. */\ninterface PendingChange {\n mutation: number\n updater: unknown\n}\n\n/** The parts of an entry a pending change is applied on top of. */\ntype Confirmed = Pick<CacheEntry, 'status' | 'data' | 'error' | 'dataUpdatedAt' | 'tags'>\n\n/**\n * One entry in the shared cache: a {@link FetcherSnapshot} plus internal\n * bookkeeping. Discriminated on `status` like the snapshot, so `data` and\n * `dataUpdatedAt` are correctly typed per status. Generic over the fetcher's\n * `TData`; the store holds `CacheEntry` (i.e. `CacheEntry<unknown>`) because it\n * is shared across fetchers, and {@link asTyped} recovers a specific `TData` at\n * the read boundary. Immutable: replaced, never mutated in place.\n */\ntype CacheEntry<TData = unknown> = FetcherSnapshot<TData> & CacheEntryMeta\n\ninterface CacheState {\n entries: {[compoundKey: string]: CacheEntry}\n}\n\ninterface InflightFetch {\n sub: Subscription\n promise: Promise<unknown>\n resolve: (data: unknown) => void\n reject: (error: unknown) => void\n startVersion: number\n /** Set once an attempt fails, while `retryRead` retries it */\n failure?: {error: unknown}\n /** Reads a paged entry's next page, rather than every page again */\n nextPage: boolean\n /** Reads every page again, and the next page of one it replaced, so a load more isn't lost */\n extraPage: boolean\n}\n\n// Erased definition type used by the machinery, which is generic-agnostic.\ntype AnyDefinition = FetcherDefinition<unknown[], unknown>\n\n// Module-level: the cache store is global (one instance across all Sanity\n// instances, keyed only by fetcher key), so this bookkeeping lives alongside it.\nconst definitions = new Map<string, AnyDefinition>()\n// So a mutation's writes, which name a fetcher, reach its definition\nconst fetcherDefinitions = new WeakMap<object, AnyDefinition>()\nconst inflight = new Map<string, InflightFetch>()\n// `resolveState` calls waiting on one entry share one subscription. A reader per call would\n// unsubscribe once answered and wake the next one in the same call stack, overflowing it\nconst waits = new Map<string, Promise<unknown>>()\n// Per mutation scope, when the last mutation in it settles. A later one's request waits for it, so\n// answers come back in the order the changes were made\nconst lastWrites = new Map<string, Promise<void>>()\ninterface IntervalTimer {\n timer: ReturnType<typeof setInterval>\n ms: number\n}\n\nconst gcTimers = new Map<string, ReturnType<typeof setTimeout>>()\nconst intervalTimers = new Map<string, IntervalTimer>()\n// Active positive polling intervals per entry key, one token per polling subscriber.\n// The shortest interval among active subscribers drives the entry's timer.\nconst subscriberIntervals = new Map<string, Map<symbol, number>>()\nconst stopTimers = new Map<string, ReturnType<typeof setTimeout>>()\nconst snapshotCache = new WeakMap<CacheEntry, FetcherSnapshot<unknown>>()\n\nconst PENDING_SNAPSHOT: FetcherSnapshot<never> = {\n status: 'pending',\n data: undefined,\n error: undefined,\n isFetching: false,\n dataUpdatedAt: undefined,\n}\n\n/** Builds the cache key that identifies one entry: the fetcher's name namespacing its raw key. */\nconst entryKey = (fetcherName: string, rawKey: string): string => `${fetcherName}:${rawKey}`\n\nconst computeTags = (def: AnyDefinition, data: unknown, params: unknown[]): CacheTag[] =>\n typeof def.tags === 'function' ? def.tags(data, ...params) : (def.tags ?? [])\n\n/**\n * Distinguishes an updater function from a replacement value. Sound because\n * cached data is API response data — never itself callable — so a callable\n * `updater` can only be the function arm. This lets us narrow without an `as`.\n */\nconst isUpdaterFn = <T>(\n updater: T | ((current: T | undefined) => T),\n): updater is (current: T | undefined) => T => typeof updater === 'function'\n\n/** Applies an updater — a replacement value, or a function of the current value. */\nconst applyUpdater = <T>(updater: T | ((current: T | undefined) => T), current: T | undefined): T =>\n isUpdaterFn(updater) ? updater(current) : updater\n\n/** Whether an entry should fetch on subscribe: not already fetching, and either empty or stale. */\nconst needsFetch = (entry: CacheEntry, def: AnyDefinition): boolean => {\n if (entry.isFetching) return false\n if (entry.status !== 'success') return true\n return (\n entry.forcedStale ||\n Date.now() - (entry.dataUpdatedAt ?? 0) >= (def.staleTime ?? DEFAULT_STALE_TIME)\n )\n}\n\n/**\n * Views a stored entry as the calling fetcher's typed entry. The cache holds\n * every fetcher's entries as `CacheEntry<unknown>`, but keys are namespaced by\n * fetcher name, so an entry read under a fetcher's key holds that fetcher's\n * `TData` — the one sound `unknown → TData` seam (cf. TanStack's `getQueryData`).\n */\nconst asTyped = <TData>(entry: CacheEntry): CacheEntry<TData> => entry as CacheEntry<TData>\n\n/** Snapshot for a given entry, memoised by entry identity so unrelated cache changes don't re-emit. */\nconst toSnapshot = <TData>(entry: CacheEntry<TData> | undefined): FetcherSnapshot<TData> => {\n if (!entry) return PENDING_SNAPSHOT\n const cached = snapshotCache.get(entry)\n if (cached) return cached as FetcherSnapshot<TData>\n\n let snapshot: FetcherSnapshot<TData>\n if (entry.status === 'success') {\n snapshot = {\n status: 'success',\n data: entry.data,\n error: entry.error,\n isFetching: entry.isFetching,\n dataUpdatedAt: entry.dataUpdatedAt,\n }\n } else if (entry.fallback !== undefined) {\n snapshot = {\n status: 'success',\n data: entry.fallback as TData,\n error: entry.error,\n isFetching: entry.isFetching,\n dataUpdatedAt: 0,\n isFallback: true,\n }\n } else if (entry.status === 'error') {\n snapshot = {\n status: 'error',\n data: undefined,\n error: entry.error,\n isFetching: entry.isFetching,\n dataUpdatedAt: undefined,\n }\n } else {\n snapshot = {\n status: 'pending',\n data: undefined,\n error: undefined,\n isFetching: entry.isFetching,\n dataUpdatedAt: undefined,\n }\n }\n\n snapshotCache.set(entry, snapshot)\n return snapshot\n}\n\nconst cacheStore = defineStore<CacheState>({\n name: 'FetcherCache',\n getInitialState: () => ({entries: {}}),\n initialize: ({state}) => {\n const comeBack = (\n typeof document === 'undefined' ? EMPTY : fromEvent(document, 'visibilitychange')\n )\n .pipe(\n filter(() => !document.hidden),\n tap(() => refetchOnWindowFocus(state)),\n )\n .subscribe()\n // The global store is disposed only when the last Sanity instance is: tear\n // down every outstanding timer and fetch so nothing leaks between lifetimes.\n return () => {\n comeBack.unsubscribe()\n for (const timer of gcTimers.values()) clearTimeout(timer)\n for (const {timer} of intervalTimers.values()) clearInterval(timer)\n for (const timer of stopTimers.values()) clearTimeout(timer)\n for (const fetch of inflight.values()) fetch.sub.unsubscribe()\n gcTimers.clear()\n intervalTimers.clear()\n subscriberIntervals.clear()\n stopTimers.clear()\n inflight.clear()\n waits.clear()\n lastWrites.clear()\n }\n },\n})\n\n/** Immutably replace (or delete, when the updater returns `undefined`) one entry. */\nconst updateEntry = (\n state: StoreState<CacheState>,\n key: string,\n actionName: string,\n updater: (prev: CacheEntry | undefined) => CacheEntry | undefined,\n): void => {\n state.set(actionName, (prev: CacheState) => {\n const next = updater(prev.entries[key])\n if (next === prev.entries[key]) return prev\n const entries = {...prev.entries}\n if (next === undefined) delete entries[key]\n else entries[key] = next\n return {entries}\n })\n}\n\nconst baseEntry = (\n def: AnyDefinition,\n key: string,\n instance: SanityInstance,\n params: unknown[],\n): CacheEntry => {\n const seeded = def.initialData?.(instance, ...params)\n if (seeded) {\n return {\n fetcherName: def.name,\n key,\n params,\n instance,\n status: 'success',\n data: seeded.data,\n error: undefined,\n dataUpdatedAt: seeded.dataUpdatedAt,\n isFetching: false,\n version: 0,\n forcedStale: false,\n tags: computeTags(def, seeded.data, params),\n subscriptions: 0,\n pending: [],\n confirmed: undefined,\n }\n }\n return {\n fetcherName: def.name,\n key,\n params,\n instance,\n status: 'pending',\n data: undefined,\n error: undefined,\n dataUpdatedAt: undefined,\n isFetching: false,\n version: 0,\n forcedStale: false,\n tags: [],\n subscriptions: 0,\n pending: [],\n confirmed: undefined,\n }\n}\n\nconst confirmedOf = ({status, data, error, dataUpdatedAt, tags}: CacheEntry): Confirmed =>\n ({status, data, error, dataUpdatedAt, tags}) as Confirmed\n\n/**\n * The entry as shown: its confirmed parts with every pending change applied in order. Each\n * mutation's changes come off when it settles, so a late answer, a refusal or a refetch never\n * drops another mutation's change.\n */\nconst showChanges = (\n def: AnyDefinition,\n entry: CacheEntry,\n confirmed: Confirmed,\n pending: PendingChange[],\n): CacheEntry => {\n const version = entry.version + 1\n if (!pending.length) {\n return {...entry, ...confirmed, version, pending, confirmed: undefined} as CacheEntry\n }\n const data = pending.reduce<unknown>(\n (current, change) => applyUpdater(change.updater, current),\n confirmed.data,\n )\n return {\n ...entry,\n status: 'success',\n data,\n error: confirmed.error,\n dataUpdatedAt: confirmed.dataUpdatedAt ?? Date.now(),\n tags: computeTags(def, data, entry.params),\n version,\n pending,\n confirmed,\n }\n}\n\n/**\n * Runs (or dedupes/restarts) the fetch for one entry, wiring the result back\n * into the cache. Returns a promise resolving with the entry's data once the\n * fetch settles — rejecting only when the entry has no data to serve.\n */\nconst startFetch = (\n state: StoreState<CacheState>,\n def: AnyDefinition,\n instance: SanityInstance,\n params: unknown[],\n force: boolean,\n nextPage?: () => Observable<unknown>,\n): Promise<unknown> => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n\n const existing = inflight.get(key)\n if (existing && !force) return existing.promise\n if (existing) {\n existing.sub.unsubscribe()\n inflight.delete(key)\n }\n\n updateEntry(state, key, 'fetchStart', (prev) => ({\n ...(prev ?? baseEntry(def, key, instance, params)),\n isFetching: true,\n }))\n\n let resolve!: (data: unknown) => void\n let reject!: (error: unknown) => void\n const promise = new Promise<unknown>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n // A forced fetch pre-empted one already in flight: forward this fetch's\n // settlement to the pre-empted promise so its awaiters don't hang forever.\n if (existing) void promise.then(existing.resolve, existing.reject)\n\n // Register before subscribing so a synchronous observable (whose `next`/\n // `complete` fire during `.subscribe()`) sees — and can clean up — its own record.\n const sub = new Subscription()\n const record: InflightFetch = {\n sub,\n promise,\n resolve,\n reject,\n startVersion: 0,\n nextPage: nextPage !== undefined,\n extraPage: !nextPage && Boolean(existing?.nextPage || existing?.extraPage),\n }\n inflight.set(key, record)\n\n sub.add(\n // Each attempt notes the version it starts from: a retry that starts after a write isn't stale\n defer(() => {\n record.startVersion = state.get().entries[key]?.version ?? 0\n return nextPage ? nextPage() : def.fetch(instance)(...params)\n })\n .pipe(\n take(1),\n tap({\n error: (error: unknown) => {\n record.failure = {error}\n updateFallback(state, def, key, params, error)\n },\n }),\n retryRead(getClientAuthState(instance), (error) => {\n // A shown failure comes off once the read recovers, or moves on to one not shown yet\n if (error === undefined) {\n updateEntry(state, key, 'fetchRetry', (prev) => {\n if (!prev || prev.error === undefined) return prev\n if (prev.status === 'success') return {...prev, error: undefined, isFetching: true}\n return {...prev, status: 'pending', error: undefined, isFetching: true}\n })\n return\n }\n updateEntry(state, key, 'fetchError', (prev) => {\n if (!prev) return prev\n // Keep rendering data if we have it (background failure); otherwise surface as error.\n if (prev.status === 'success') return {...prev, error, isFetching: false}\n return {...prev, status: 'error', error, isFetching: false}\n })\n reject(error)\n }),\n )\n .subscribe({\n next: (data) => {\n const current = state.get().entries[key]\n // An entry with nothing confirmed, like one showing only a change or a fallback, has\n // nothing newer than this result, so it takes it\n if (current && current.version !== record.startVersion && hasConfirmedData(current)) {\n // A write (optimistic mutation) landed mid-fetch: discard the now-stale\n // server result and keep the written data. Tear the fetch down here —\n // a non-completing source won't fire `complete` to clear `isFetching`.\n inflight.delete(key)\n // An error an earlier attempt showed is out of date now this one has been answered\n if (current.isFetching || current.error !== undefined) {\n updateEntry(\n state,\n key,\n 'fetchDiscard',\n (prev) => prev && {...prev, isFetching: false, error: undefined},\n )\n }\n resolve(current.data)\n sub.unsubscribe()\n return\n }\n if (current?.pending.length) {\n // The server's latest, or all there is; changes still in flight go on top\n updateEntry(\n state,\n key,\n 'fetchUnderChanges',\n (prev) =>\n prev &&\n showChanges(\n def,\n {...prev, isFetching: false, forcedStale: false},\n {\n status: 'success',\n data,\n error: undefined,\n dataUpdatedAt: Date.now(),\n tags: computeTags(def, data, params),\n },\n prev.pending,\n ),\n )\n resolve(state.get().entries[key]?.data)\n return\n }\n updateEntry(state, key, 'fetchSuccess', (prev) => ({\n ...(prev ?? baseEntry(def, key, instance, params)),\n status: 'success',\n data,\n error: undefined,\n dataUpdatedAt: Date.now(),\n isFetching: false,\n forcedStale: false,\n tags: computeTags(def, data, params),\n }))\n resolve(data)\n },\n complete: () => {\n inflight.delete(key)\n const current = state.get().entries[key]\n if (current?.isFetching) {\n updateEntry(state, key, 'fetchSettle', (prev) => prev && {...prev, isFetching: false})\n }\n },\n }),\n )\n\n return promise\n}\n\n// Data the entry shows without changes still in flight\nconst hasConfirmedData = (entry: CacheEntry): boolean =>\n (entry.confirmed ?? entry).data !== undefined\n\n// A fallback only stands in for a failure a retry may fix, on an entry with nothing confirmed\nconst updateFallback = (\n state: StoreState<CacheState>,\n def: AnyDefinition,\n key: string,\n params: unknown[],\n error: unknown,\n): void => {\n const {fallbackData} = def\n if (!fallbackData) return\n const transient = classifyFailure(error) === 'transient'\n updateEntry(state, key, 'fetchFallback', (prev) => {\n if (!prev || transient === (prev.fallback !== undefined)) return prev\n if (!transient) return {...prev, fallback: undefined}\n if (hasConfirmedData(prev)) return prev\n return {...prev, fallback: fallbackData(prev.instance, ...params)}\n })\n}\n\n/**\n * Trigger a fetch without awaiting it. The failure is already reflected in the\n * entry's snapshot, so swallow the promise rejection to avoid an unhandled one.\n */\nconst detach = (promise: Promise<unknown>): void => {\n void promise.catch(() => {})\n}\n\nconst markStale = (state: StoreState<CacheState>, key: string): void =>\n updateEntry(state, key, 'markStale', (prev) => prev && {...prev, forcedStale: true})\n\nconst resolveRefetchInterval = (\n def: AnyDefinition,\n instance: SanityInstance,\n params: unknown[],\n): number | undefined => {\n const interval =\n typeof def.refetchInterval === 'function'\n ? def.refetchInterval(instance, ...params)\n : def.refetchInterval\n return typeof interval === 'number' && Number.isFinite(interval) && interval > 0\n ? interval\n : undefined\n}\n\n/**\n * Reconciles an entry's polling timer with its active subscribers' requested intervals.\n * Runs at the shortest positive interval requested, or clears the timer when no subscriber polls.\n * Skips ticks while the tab is hidden.\n */\nconst syncInterval = (state: StoreState<CacheState>, def: AnyDefinition, key: string): void => {\n const active = subscriberIntervals.get(key)\n const desiredMs = active && active.size > 0 ? Math.min(...active.values()) : undefined\n const current = intervalTimers.get(key)\n if (current?.ms === desiredMs) return\n\n if (current) {\n clearInterval(current.timer)\n intervalTimers.delete(key)\n }\n if (desiredMs === undefined) return\n\n const timer = setCleanupInterval(() => {\n if (typeof document !== 'undefined' && document.hidden) return\n const entry = state.get().entries[key]\n // A poll would cancel the next page, as it reads only the pages before it. A next page that\n // keeps failing holds the poll off until it's read or nobody watches the list\n if (inflight.get(key)?.nextPage) return\n if (entry && entry.subscriptions > 0) {\n detach(startFetch(state, def, entry.instance, entry.params, true))\n }\n }, desiredMs)\n intervalTimers.set(key, {timer, ms: desiredMs})\n}\n\n/** Registers a subscriber's polling interval and returns a cleanup callback to remove it. */\nconst addSubscriberInterval = (\n state: StoreState<CacheState>,\n def: AnyDefinition,\n instance: SanityInstance,\n params: unknown[],\n key: string,\n): (() => void) | undefined => {\n const intervalMs = resolveRefetchInterval(def, instance, params)\n if (intervalMs === undefined) return undefined\n const token = Symbol()\n const active = subscriberIntervals.get(key) ?? new Map<symbol, number>()\n active.set(token, intervalMs)\n subscriberIntervals.set(key, active)\n syncInterval(state, def, key)\n return () => {\n active.delete(token)\n if (active.size === 0 && subscriberIntervals.get(key) === active) {\n subscriberIntervals.delete(key)\n }\n syncInterval(state, def, key)\n }\n}\n\n/**\n * Schedules an unsubscribed entry for garbage collection: after `gcTime` (from\n * now) its in-flight fetch is torn down and the entry removed. No-op if the\n * entry still has subscribers or a GC timer is already pending. Called from\n * every path that can leave an entry at zero subscribers — the unsubscribe\n * teardown, and the imperative `refetch`, `resolveState` retry and mutation writes\n * that fetch or create entries without ever subscribing. A later subscribe cancels\n * the pending timer.\n */\nconst scheduleGc = (state: StoreState<CacheState>, def: AnyDefinition, key: string): void => {\n if (gcTimers.has(key)) return\n const entry = state.get().entries[key]\n if (!entry || entry.subscriptions > 0) return\n const timer = setCleanupTimeout(() => {\n gcTimers.delete(key)\n const fetch = inflight.get(key)\n if (fetch) {\n fetch.sub.unsubscribe()\n inflight.delete(key)\n }\n updateEntry(state, key, 'gc', () => undefined)\n }, def.gcTime ?? DEFAULT_GC_TIME)\n gcTimers.set(key, timer)\n}\n\n/**\n * A second after an entry stops being watched, stops retrying its failed fetch, as the query\n * store does, and marks the entry stale so the next subscriber fetches again.\n */\nconst stopUnwatchedRetry = (state: StoreState<CacheState>, key: string): void => {\n clearTimeout(stopTimers.get(key))\n const timer = setCleanupTimeout(() => {\n stopTimers.delete(key)\n const fetch = inflight.get(key)\n if (!fetch?.failure || (state.get().entries[key]?.subscriptions ?? 0) > 0) return\n fetch.sub.unsubscribe()\n inflight.delete(key)\n fetch.reject(fetch.failure.error)\n updateEntry(\n state,\n key,\n 'stopRetry',\n (prev) => prev && {...prev, isFetching: false, forcedStale: true},\n )\n }, UPSTREAM_CLOSE_DELAY_MS)\n stopTimers.set(key, timer)\n}\n\nconst cancelGc = (key: string): void => {\n const timer = gcTimers.get(key)\n if (!timer) return\n clearTimeout(timer)\n gcTimers.delete(key)\n}\n\n/**\n * Refetches the entries on screen when the tab becomes visible again, as each fetcher's\n * `refetchOnWindowFocus` says. Doesn't restart a fetch in flight, so a \"Load more\" isn't cancelled.\n */\nconst refetchOnWindowFocus = (state: StoreState<CacheState>): void => {\n for (const entry of Object.values(state.get().entries)) {\n const def = definitions.get(entry.fetcherName)\n const when = def?.refetchOnWindowFocus ?? true\n if (!def || !when || entry.subscriptions <= 0) continue\n if (entry.instance.config.refetchOnWindowFocus === false) continue\n if (when === 'always' || needsFetch(entry, def)) {\n detach(startFetch(state, def, entry.instance, entry.params, false))\n }\n }\n}\n\n/** Shared across all fetchers: scans the whole cache and revalidates entries carrying any matched tag. */\nconst invalidateByTags = bindActionGlobally(\n cacheStore,\n ({state}: StoreContext<CacheState>, targets: CacheTag[]): Promise<void> => {\n const refetches: Promise<unknown>[] = []\n for (const [key, entry] of Object.entries(state.get().entries)) {\n const matches = entry.tags.some((tag) =>\n targets.some(\n (target) => tag.type === target.type && (target.id === undefined || tag.id === target.id),\n ),\n )\n if (!matches) continue\n markStale(state, key)\n if (entry.subscriptions <= 0) continue\n const def = definitions.get(entry.fetcherName)\n // Reconciliation is best-effort: a failed refetch surfaces on its snapshot,\n // and must not reject the caller's `invalidated` promise.\n if (def)\n refetches.push(\n startFetch(state, def, entry.instance, entry.params, true).catch(() => undefined),\n )\n }\n return Promise.all(refetches).then(() => undefined)\n },\n)\n\n/**\n * Registers a fetcher definition against the shared cache and returns its typed\n * handle.\n *\n * @internal\n */\nexport function defineFetcher<TParams extends unknown[], TData>(\n definition: FetcherDefinition<TParams, TData>,\n): Fetcher<TParams, TData> {\n const def = definition as unknown as AnyDefinition\n definitions.set(definition.name, def)\n\n const getState = bindActionGlobally(\n cacheStore,\n createStateSourceAction<CacheState, TParams, FetcherSnapshot<TData>>({\n selector: ({state, instance}: SelectorContext<CacheState>, ...params: TParams) => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n const entry = state.entries[key]\n return toSnapshot(entry && asTyped<TData>(entry))\n },\n onSubscribe: ({state, instance}: StoreContext<CacheState>, ...params: TParams) => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n cancelGc(key)\n clearTimeout(stopTimers.get(key))\n stopTimers.delete(key)\n\n updateEntry(state, key, 'subscribe', (prev) => ({\n ...(prev ?? baseEntry(def, key, instance, params)),\n instance,\n subscriptions: (prev?.subscriptions ?? 0) + 1,\n }))\n const removeInterval = addSubscriberInterval(state, def, instance, params, key)\n\n // Defer the fetch decision off the subscribe call stack to avoid a\n // re-entrant cache write during subscription setup.\n queueMicrotask(() => {\n const entry = state.get().entries[key]\n if (entry && entry.subscriptions > 0 && needsFetch(entry, def)) {\n detach(startFetch(state, def, instance, params, false))\n }\n })\n\n return () => {\n removeInterval?.()\n updateEntry(\n state,\n key,\n 'unsubscribe',\n (prev) => prev && {...prev, subscriptions: Math.max(0, prev.subscriptions - 1)},\n )\n const entry = state.get().entries[key]\n if (!entry || entry.subscriptions > 0) return\n\n scheduleGc(state, def, key)\n stopUnwatchedRetry(state, key)\n }\n },\n }),\n )\n\n const resolveState = bindActionGlobally(\n cacheStore,\n // Async so a key that can't be built rejects, like a failed fetch, instead of throwing\n async ({state, instance}: StoreContext<CacheState>, ...params: TParams): Promise<TData> => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n // An error left by an earlier fetch is not an answer: fetch again now, restarting a retry\n // that is waiting on a backoff or a new token, keeping garbage collection off the entry\n // until that fetch settles\n const entry = state.get().entries[key]\n if (entry?.status === 'error' && entry.fallback === undefined) {\n cancelGc(key)\n const retrying = inflight.get(key)?.failure !== undefined\n return (startFetch(state, def, instance, params, retrying) as Promise<TData>).finally(\n () => {\n scheduleGc(state, def, key)\n stopUnwatchedRetry(state, key)\n },\n )\n }\n const waiting = waits.get(key)\n if (waiting) return waiting as Promise<TData>\n const wait = firstValueFrom(\n getState(instance, ...params).observable.pipe(\n filter(\n (snapshot): snapshot is Exclude<FetcherSnapshot<TData>, {status: 'pending'}> =>\n snapshot.status !== 'pending',\n ),\n map((snapshot) => {\n if (snapshot.status === 'error') throw snapshot.error\n return snapshot.data\n }),\n ),\n ).finally(() => waits.delete(key))\n waits.set(key, wait)\n return wait\n },\n )\n\n const invalidate = bindActionGlobally(\n cacheStore,\n ({state, instance}: StoreContext<CacheState>, ...params: TParams) => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n markStale(state, key)\n const entry = state.get().entries[key]\n if (entry && entry.subscriptions > 0) detach(startFetch(state, def, instance, params, true))\n },\n )\n\n const invalidateAll = bindActionGlobally(cacheStore, ({state}: StoreContext<CacheState>) => {\n const prefix = `${def.name}:`\n for (const [key, entry] of Object.entries(state.get().entries)) {\n if (!key.startsWith(prefix)) continue\n markStale(state, key)\n if (entry.subscriptions > 0)\n detach(startFetch(state, def, entry.instance, entry.params, true))\n }\n })\n\n const refetch = bindActionGlobally(\n cacheStore,\n ({state, instance}: StoreContext<CacheState>, ...params: TParams): Promise<TData> => {\n const key = entryKey(def.name, def.getKey(instance, ...params))\n const promise = startFetch(state, def, instance, params, true) as Promise<TData>\n scheduleGc(state, def, key)\n return promise.finally(() => stopUnwatchedRetry(state, key))\n },\n )\n\n const fetcher = {getState, resolveState, invalidate, invalidateAll, refetch}\n fetcherDefinitions.set(fetcher, def)\n return fetcher\n}\n\n/**\n * One page of a list the API answers a page at a time: its items, and the cursor to read the page\n * after it with, or `null` on the last page.\n *\n * @internal\n */\nexport interface CursorPage {\n data: unknown[]\n nextCursor: string | null\n}\n\n/**\n * A {@link FetcherDefinition} for a list the API answers a page at a time. An entry holds the\n * pages read so far, in order.\n *\n * @internal\n */\nexport interface PagedFetcherDefinition<\n TParams extends unknown[],\n TPage extends CursorPage,\n> extends Omit<FetcherDefinition<TParams, TPage[]>, 'fetch' | 'initialData' | 'fallbackData'> {\n /**\n * Reads one page: the first without a cursor, each one after with the `nextCursor` of the page\n * before. Return an observable that emits the page.\n */\n fetch: (\n instance: SanityInstance,\n ) => (cursor: string | undefined, ...params: TParams) => Observable<TPage>\n}\n\n/**\n * A {@link Fetcher} over the pages of a list read so far, returned by {@link definePagedFetcher}.\n * A refetch, after a change or on the poll, reads every one of them again from the first, so an\n * item never shows twice or goes missing. A refetch that starts while `loadMore` reads the next page\n * reads that page too.\n *\n * @internal\n */\nexport interface PagedFetcher<TParams extends unknown[], TPage extends CursorPage> extends Fetcher<\n TParams,\n TPage[]\n> {\n /**\n * Reads the page after the last one read and adds it. Called again while that page loads, it\n * shares the read. A failure rejects and shows on the entry's `error`, keeping the pages read so\n * far. Resolves with the pages read so far when there's no page after them.\n */\n loadMore: (instance: SanityInstance, ...params: TParams) => Promise<TPage[]>\n}\n\n/**\n * Registers a fetcher for a list the API answers a page at a time, like TanStack Query's infinite\n * queries, against the shared cache. An entry's data is the pages read so far, so a mutation that\n * writes to one updates an array of pages, and readers outside React join them.\n *\n * @internal\n */\nexport function definePagedFetcher<TParams extends unknown[], TPage extends CursorPage>({\n fetch: fetchPage,\n ...definition\n}: PagedFetcherDefinition<TParams, TPage>): PagedFetcher<TParams, TPage> {\n const pagesDefinition: FetcherDefinition<TParams, TPage[]> = {\n ...definition,\n fetch:\n (instance) =>\n (...params) => {\n const read = (cursor?: string) => fetchPage(instance)(cursor, ...params).pipe(take(1))\n const pages = fetcher.getState(instance, ...params).getCurrent().data?.length ?? 1\n const key = entryKey(definition.name, definition.getKey(instance, ...params))\n const count = inflight.get(key)?.extraPage ? pages + 1 : pages\n return read().pipe(\n expand((page, index) =>\n page.nextCursor !== null && index + 1 < count ? read(page.nextCursor) : EMPTY,\n ),\n toArray(),\n )\n },\n }\n const fetcher = defineFetcher(pagesDefinition)\n const def = pagesDefinition as unknown as AnyDefinition\n\n const loadMore: PagedFetcher<TParams, TPage>['loadMore'] = bindActionGlobally(\n cacheStore,\n ({state, instance}: StoreContext<CacheState>, ...params: TParams): Promise<TPage[]> => {\n const loading = inflight.get(entryKeyOf(def, instance, params))\n // A next page retrying after a failure is read again now, as `resolveState` does\n if (loading?.nextPage && !loading.failure) return loading.promise as Promise<TPage[]>\n // A refetch, like the one after a change, goes first, even while it retries, so the next\n // page follows its pages\n if (loading && !loading.nextPage) {\n return loading.promise.then(() => loadMore(instance, ...params))\n }\n const pages = fetcher.getState(instance, ...params).getCurrent().data\n const cursor = pages?.at(-1)?.nextCursor\n if (!pages || typeof cursor !== 'string') return fetcher.resolveState(instance, ...params)\n return startFetch(state, def, instance, params, true, () =>\n fetchPage(instance)(cursor, ...params).pipe(map((page) => [...pages, page])),\n ) as Promise<TPage[]>\n },\n )\n\n const paged = {...fetcher, loadMore}\n fetcherDefinitions.set(paged, def)\n return paged\n}\n\nconst entryKeyOf = (def: AnyDefinition, instance: SanityInstance, params: unknown[]): string =>\n entryKey(def.name, def.getKey(instance, ...params))\n\n/** Records a mutation's optimistic write as a pending change on the entry, shown at once. */\nconst addChange = bindActionGlobally(\n cacheStore,\n (\n {state, instance}: StoreContext<CacheState>,\n def: AnyDefinition,\n params: unknown[],\n change: PendingChange,\n ) => {\n const key = entryKeyOf(def, instance, params)\n updateEntry(state, key, 'addChange', (prev) => {\n const from = prev ?? baseEntry(def, key, instance, params)\n return showChanges(def, from, from.confirmed ?? confirmedOf(from), [...from.pending, change])\n })\n scheduleGc(state, def, key)\n },\n)\n\n/**\n * Takes a settled mutation's changes off the entry. On success they become confirmed: replaced by\n * its `onSuccess` writes when it made any, or else kept as the server accepted them. On failure\n * they're dropped. Other mutations' changes stay on top either way.\n */\nconst settleChanges = bindActionGlobally(\n cacheStore,\n (\n {state, instance}: StoreContext<CacheState>,\n def: AnyDefinition,\n params: unknown[],\n mutation: number,\n {succeeded, confirms}: {succeeded: boolean; confirms: unknown[]},\n ) => {\n const key = entryKeyOf(def, instance, params)\n updateEntry(state, key, 'settleChanges', (prev) => {\n if (!prev && !confirms.length) return prev\n const from = prev ?? baseEntry(def, key, instance, params)\n const own = from.pending.filter((change) => change.mutation === mutation)\n const accepted = succeeded && !confirms.length ? own.map(({updater}) => updater) : []\n const confirmed = [...accepted, ...confirms].reduce<Confirmed>(\n (current, updater) => {\n const data = applyUpdater(updater, current.data)\n return {\n status: 'success',\n data,\n error: undefined,\n dataUpdatedAt: current.dataUpdatedAt ?? Date.now(),\n tags: computeTags(def, data, params),\n }\n },\n from.confirmed ?? confirmedOf(from),\n )\n const pending = from.pending.filter((change) => change.mutation !== mutation)\n return showChanges(def, from, confirmed, pending)\n })\n scheduleGc(state, def, key)\n },\n)\n\nlet mutationCount = 0\n\n/**\n * Creates a bound mutation from its definition. The returned action resolves at\n * server settlement — not after invalidation refetches, which run as background\n * reconciliation (see {@link MutationResult.invalidated}).\n *\n * @internal\n */\nexport function defineMutation<TInput, TResult>(\n definition: MutationDefinition<TInput, TResult>,\n): (instance: SanityInstance, input: TInput) => Promise<MutationResult<TResult>> {\n return (instance, input) => {\n const mutation = ++mutationCount\n // Every entry this call writes to, with the `onSuccess` writes to apply when it settles\n const touched = new Map<string, {def: AnyDefinition; params: unknown[]; confirms: unknown[]}>()\n const touch = (fetcher: object, params: unknown[]) => {\n const def = fetcherDefinitions.get(fetcher)\n if (!def) throw new Error('A mutation wrote to a fetcher that `defineFetcher` did not create')\n const key = entryKeyOf(def, instance, params)\n const entry = touched.get(key) ?? {def, params, confirms: []}\n touched.set(key, entry)\n return entry\n }\n const settle = (succeeded: boolean) => {\n for (const {def, params, confirms} of touched.values()) {\n settleChanges(instance, def, params, mutation, {succeeded, confirms})\n }\n }\n\n definition.onMutate?.((fetcher, params, updater) => {\n addChange(instance, touch(fetcher, params).def, params, {mutation, updater})\n }, input)\n\n const scope = definition.scope?.(input)\n const earlier = scope === undefined ? undefined : lastWrites.get(scope)\n // `of` sends a request with nothing ahead of it straight away. `concatMap` turns a request that\n // throws before it's sent into a rejection, so its changes come off\n const request = firstValueFrom(\n defer(() => earlier ?? of(undefined)).pipe(\n concatMap(() => definition.mutationFn(instance)(input)),\n ),\n )\n if (scope !== undefined) {\n const settled = request.then(\n () => {},\n () => {},\n )\n lastWrites.set(scope, settled)\n void settled.then(() => {\n if (lastWrites.get(scope) === settled) lastWrites.delete(scope)\n })\n }\n\n return request.then(\n (result) => {\n definition.onSuccess?.(\n (fetcher, params, updater) => {\n touch(fetcher, params).confirms.push(updater)\n },\n result,\n input,\n )\n settle(true)\n const targets =\n typeof definition.invalidates === 'function'\n ? definition.invalidates(result, input)\n : (definition.invalidates ?? [])\n const invalidated = targets.length ? invalidateByTags(instance, targets) : Promise.resolve()\n return {data: result, invalidated}\n },\n (error) => {\n settle(false)\n throw error\n },\n )\n }\n}\n","import {stringifyPath} from '@sanity/json-match'\nimport {type Path} from '@sanity/types'\n\n/** A dotted segment GROQ would read as a literal rather than a field name. */\nconst RESERVED_SEGMENT = /\\.(true|false|null)(?=$|[.[])/g\n\n/**\n * One quoted string, or one run of text containing no quote at all. Splitting on\n * this is what keeps the rewrite below out of `[_key==\"...\"]` values.\n */\nconst QUOTED_OR_PLAIN = /\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|[^\"']+/g\n\nfunction quoteReservedFieldSegments(path: string): string {\n return path.replace(QUOTED_OR_PLAIN, (chunk) =>\n chunk.startsWith('\"') || chunk.startsWith(\"'\")\n ? chunk\n : chunk.replace(RESERVED_SEGMENT, '[\"$1\"]'),\n )\n}\n\n/**\n * Normalises a field path to the string form comments are stored in.\n *\n * Comments keep `target.path.field` as a string rather than a path array,\n * because that is what the Studio writes and reading it back has to match\n * exactly. A string given here is parsed and re-stringified, so both a path\n * array and a hand-written string come out in the same canonical form.\n *\n * `undefined` and `[]` both produce `''`. Callers writing a comment reject that\n * rather than passing it on, since a comment has to point at a field.\n *\n * @example\n * ```ts\n * toCommentFieldPath(['body', {_key: 'intro'}, 'content'])\n * // 'body[_key==\"intro\"].content'\n * toCommentFieldPath(undefined)\n * // ''\n * ```\n *\n * @internal\n */\nexport function toCommentFieldPath(path?: string | Path): string {\n return quoteReservedFieldSegments(stringifyPath(path))\n}\n"],"mappings":";;;;;;AA+BA,MAiUM,8BAAc,IAAI,IAA2B,GAE7C,qCAAqB,IAAI,QAA+B,GACxD,2BAAW,IAAI,IAA2B,GAG1C,wBAAQ,IAAI,IAA8B,GAG1C,6BAAa,IAAI,IAA2B,GAM5C,2BAAW,IAAI,IAA2C,GAC1D,iCAAiB,IAAI,IAA2B,GAGhD,sCAAsB,IAAI,IAAiC,GAC3D,6BAAa,IAAI,IAA2C,GAC5D,gCAAgB,IAAI,QAA8C,GAElE,mBAA2C;CAC/C,QAAQ;CACR,MAAM,KAAA;CACN,OAAO,KAAA;CACP,YAAY;CACZ,eAAe,KAAA;AACjB,GAGM,YAAY,aAAqB,WAA2B,GAAG,YAAY,GAAG,UAE9E,eAAe,KAAoB,MAAe,WACtD,OAAO,IAAI,QAAS,aAAa,IAAI,KAAK,MAAM,GAAG,MAAM,IAAK,IAAI,QAAQ,CAAC,GAOvE,eACJ,YAC6C,OAAO,WAAY,YAG5D,gBAAmB,SAA8C,YACrE,YAAY,OAAO,IAAI,QAAQ,OAAO,IAAI,SAGtC,cAAc,OAAmB,QACjC,MAAM,aAAmB,KACzB,MAAM,WAAW,aAEnB,MAAM,eACN,KAAK,IAAI,KAAK,MAAM,iBAAiB,OAAO,IAAI,aAAa,MAU3D,WAAkB,UAAyC,OAG3D,cAAqB,UAAiE;CAC1F,IAAI,CAAC,OAAO,OAAO;CACnB,IAAM,SAAS,cAAc,IAAI,KAAK;CACtC,IAAI,QAAQ,OAAO;CAEnB,IAAI;CAqCJ,OApCA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AAQ;GAC1D;EACnC,IACC,UAAU;GAET,MADA,OAAO,EAAK,GACN;EACR,CACF;CACF;AACF;;AC3yCA,MAAM,mBAAmB,kCAMnB,kBAAkB;AAExB,SAAS,2BAA2B,MAAsB;CACxD,OAAO,KAAK,QAAQ,kBAAkB,UACpC,MAAM,WAAW,IAAG,KAAK,MAAM,WAAW,GAAG,IACzC,QACA,MAAM,QAAQ,kBAAkB,UAAQ,CAC9C;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAmB,MAA8B;CAC/D,OAAO,2BAA2B,cAAc,IAAI,CAAC;AACvD"}
|
|
@@ -3,7 +3,7 @@ import { C as isNetworkFailure, I as getClientErrorApiBody, L as getClientErrorA
|
|
|
3
3
|
import { h as randomUuid, m as randomId } from "./topicStore-CKBdgAz7.js";
|
|
4
4
|
import { r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
|
|
5
5
|
import { r as getClientState } from "./clientStore-eysItBQl.js";
|
|
6
|
-
import { n as defineFetcher, r as defineMutation } from "./
|
|
6
|
+
import { n as defineFetcher, r as defineMutation } from "./types-C8dSHL5E.js";
|
|
7
7
|
import { t as getNodeState } from "./getNodeState-Bp9sxNE1.js";
|
|
8
8
|
import { ClientError, ConnectionFailedError, CorsOriginError, DisconnectError, ServerError, isTimeoutError } from "@sanity/client";
|
|
9
9
|
import { BehaviorSubject, EMPTY, NEVER, Observable, catchError, combineLatest, defer, distinctUntilChanged, filter, first, firstValueFrom, from, groupBy, map, mergeMap, of, pairwise, race, share, startWith, switchMap, tap, timer } from "rxjs";
|
|
@@ -2326,7 +2326,7 @@ const _resolveQuery = bindActionByResource(queryStore, ({ state, instance }, { s
|
|
|
2326
2326
|
};
|
|
2327
2327
|
return promise.then(releaseSubscriber, releaseSubscriber), promise;
|
|
2328
2328
|
});
|
|
2329
|
-
var version = "3.17.0
|
|
2329
|
+
var version = "3.17.0";
|
|
2330
2330
|
/**
|
|
2331
2331
|
* This version is provided by pkg-utils at build time
|
|
2332
2332
|
* @internal
|
|
@@ -2334,4 +2334,4 @@ var version = "3.17.0-next.20261126182834";
|
|
|
2334
2334
|
const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
|
|
2335
2335
|
export { getDocumentIdsFromHandleLikes as A, ActionError as B, favoriteScope as C, applyFirstQueuedTransaction as D, toFavoriteDocument as E, revertOutgoingTransaction as F, getProjectAccessErrorDetails as G, processMutations as H, throwDocumentError as I, getProjectAccessErrorProjectId as K, transitionAppliedTransactionsToOutgoing as L, manageSubscriberIds as M, queueTransaction as N, applyRemoteDocument as O, removeQueuedTransaction as P, calculatePermissions as R, toPreferenceError as S, setFavorite as T, getReleaseDocumentId as U, patchOperations as V, isReleaseAction as W, setUsersError as _, parseQueryKey as a, USERS_STATE_CLEAR_DELAY as b, getActiveReleasesState as c, cancelRequest as d, getUsersKey as f, setUsersData as g, removeSubscription as h, getQueryState as i, isBatchableTransaction as j, cleanupOutgoingTransaction as k, getAllReleasesState as l, parseUsersKey as m, version as n, resolveQuery as o, initializeRequest as p, getSignInMethodLabel as q, getQueryKey as r, getPerspectiveState as s, CORE_SDK_VERSION as t, addSubscription as u, updateLastLoadMoreRequest as v, favorites as w, PreferenceError as x, PROJECT_API_VERSION as y, createGrantsLookup as z };
|
|
2336
2336
|
|
|
2337
|
-
//# sourceMappingURL=version-
|
|
2337
|
+
//# sourceMappingURL=version-C4jlyyUU.js.map
|