@sanity/sdk 3.9.1 → 3.9.2-next.20261014121948

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.
Files changed (27) hide show
  1. package/dist/_exports/_internal.d.ts +2 -2
  2. package/dist/_exports/_internal.js +9 -17
  3. package/dist/_exports/_internal.js.map +1 -1
  4. package/dist/_exports/agent.js +1 -1
  5. package/dist/_exports/comlink.d.ts +1 -0
  6. package/dist/_exports/comlink.d.ts.map +1 -1
  7. package/dist/_exports/comlink.js +1 -1
  8. package/dist/_exports/dashboard.d.ts +2 -2
  9. package/dist/_exports/dashboard.js +2 -2
  10. package/dist/{applications-DowvM7CN.d.ts → applications-CkDu_W5X.d.ts} +3 -3
  11. package/dist/{applications-DowvM7CN.d.ts.map → applications-CkDu_W5X.d.ts.map} +1 -1
  12. package/dist/{authStore-KH1GNOOB.js → authStore-DwKgZOzo.js} +8 -26
  13. package/dist/{authStore-KH1GNOOB.js.map → authStore-DwKgZOzo.js.map} +1 -1
  14. package/dist/{bus-ClLO0kQU.d.ts → bus-bvKfVggT.d.ts} +2 -2
  15. package/dist/{bus-ClLO0kQU.d.ts.map → bus-bvKfVggT.d.ts.map} +1 -1
  16. package/dist/{clientStore-DW3iIcbg.js → clientStore-DnMH7LPG.js} +2 -2
  17. package/dist/{clientStore-DW3iIcbg.js.map → clientStore-DnMH7LPG.js.map} +1 -1
  18. package/dist/{getNodeState-CkxvEZD5.js → getNodeState-Bp9sxNE1.js} +2 -5
  19. package/dist/{getNodeState-CkxvEZD5.js.map → getNodeState-Bp9sxNE1.js.map} +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +50 -74
  22. package/dist/index.js.map +1 -1
  23. package/dist/{topicStore-CU-oF3fc.js → topicStore-CNzfuPGY.js} +2 -2
  24. package/dist/{topicStore-CU-oF3fc.js.map → topicStore-CNzfuPGY.js.map} +1 -1
  25. package/dist/{version-7EzMhxQE.js → version-Bx_0tNcN.js} +10 -14
  26. package/dist/{version-7EzMhxQE.js.map → version-Bx_0tNcN.js.map} +1 -1
  27. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
- import { Dr as StateTopic, Er as ReplyOf, Mr as ValueOf, _r as EventTopic, jr as Topics, kr as TopicName, t as Application, wr as PayloadOf, xr as MessageBusTopics } from "./applications-DowvM7CN.js";
1
+ import { Dr as StateTopic, Er as ReplyOf, Mr as ValueOf, _r as EventTopic, jr as Topics, kr as TopicName, t as Application, wr as PayloadOf, xr as MessageBusTopics } from "./applications-CkDu_W5X.js";
2
2
  import { Observable } from "rxjs";
3
3
  /**
4
4
  * A message bus protocol error code.
@@ -238,4 +238,4 @@ interface InstallMessageBusOptions {
238
238
  */
239
239
  declare function installMessageBus(options?: InstallMessageBusOptions): MessageBusHost<Topics>;
240
240
  export { installMessageBus as _, MessageBusClient as a, MessageBusEmitResult as c, MessageBusHost as d, MessageBusMessage as f, connectMessageBus as g, MessageBusStateSource as h, MessageBusAbortOptions as i, MessageBusError as l, MessageBusQueryOptions as m, InstallMessageBusOptions as n, MessageBusConnection as o, MessageBusMeta as p, MessageBus as r, MessageBusEmitOptions as s, ConnectMessageBusOptions as t, MessageBusErrorCode as u, isMessageBusEnvironment as v, resetMessageBus as y };
241
- //# sourceMappingURL=bus-ClLO0kQU.d.ts.map
241
+ //# sourceMappingURL=bus-bvKfVggT.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bus-ClLO0kQU.d.ts","names":[],"sources":["../src/dashboard/messageBus/bus.ts"],"mappings":";;;;;;;KAqCY;;;;;;cAeC,wBAAwB;;WAE1B,MAAM;;EAGH,YAAA,MAAM,qBAAqB,kBAAkB;IAAW;;;;;;;;UAYrD;;EAEf,OAAO;;;;;;EAMP;;EAEA;;;;;;;UAQe,kBAAkB,GAAG,WAAW,UAAU,cAAc;;EAEvE,MAAM;;EAEN,SAAS;;EAET,MAAM;;EAEN,MAAM,OAAO;;;;;;EAMb,OAAO;;WAEE,QAAQ;;;;;;;UA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,QAAQ,GAAG;;EAEpF,UAAU,UAAU,WAAW,UAAU,MAAM,IAAI,WAAW,UAAU,GAAG;;;;;;;UAQ5D,qBAAqB,UAAU,0BAA0B,WAAW;;WAE1E,OAAO;;;;;;EAMhB;;;;;;;UAQe;;WAEN,OAAO;;WAEP;;WAEA,QAAQ;;EAEjB,KAAK,UAAU,YAAY,MAAM,GAAG,OAAO,QAAQ;;;;;;;;;;;;;EAanD,OAAO,UAAU,YAAY,MAAM,GAAG;;;;;;;;;;;;;UAcvB,eAAe,UAAU,0BAA0B,qBAAqB;;;;;;;WAO9E,aAAa,WAAW;;;;;;iBA89BnB;;;;;;UASC;;EAEf;;EAEA;;;;;;;iBAQc,kBACd,UAAS,2BACR;;;;;iBAuBa;;;;;;UAWC;;EAEf;;;;;;;;iBASc,kBAAkB,UAAS,2BAAgC,eAAe"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-vyAXikos.js";
2
2
  import { h as isMediaLibraryResource, i as bindActionGlobally, m as isDatasetResource, p as isCanvasResource, s as defineStore, t as createStateSourceAction } from "./createStateSourceAction-Bn0po7Z3.js";
3
- import { B as getStagingApiHost, c as getTokenState, r as getAuthMethodState } from "./authStore-KH1GNOOB.js";
3
+ import { B as getStagingApiHost, c as getTokenState, r as getAuthMethodState } from "./authStore-DwKgZOzo.js";
4
4
  import { i as pickProperties } from "./object-CxXlSVg7.js";
5
5
  import { createClient } from "@sanity/client";
6
6
  var clientStore_exports = /* @__PURE__ */ __exportAll({
@@ -87,4 +87,4 @@ const allowedKeys = Object.keys({
87
87
  }), getClientState = bindActionGlobally(clientStore, createStateSourceAction(({ instance }, options) => getClient(instance, options)));
88
88
  export { getClient as n, getClientState as r, clientStore_exports as t };
89
89
 
90
- //# sourceMappingURL=clientStore-DW3iIcbg.js.map
90
+ //# sourceMappingURL=clientStore-DnMH7LPG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clientStore-DW3iIcbg.js","names":[],"sources":["../src/client/clientStore.ts"],"sourcesContent":["import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'\n\nimport {getAuthMethodState, getTokenState} from '../auth/authStore'\nimport {\n type DocumentResource,\n isCanvasResource,\n isDatasetResource,\n isMediaLibraryResource,\n} from '../config/sanityConfig'\nimport {bindActionGlobally} from '../store/createActionBinder'\nimport {createStateSourceAction} from '../store/createStateSourceAction'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {getStagingApiHost} from '../utils/getStagingApiHost'\nimport {pickProperties} from '../utils/object'\n\nconst DEFAULT_API_VERSION = '2024-11-12'\nconst DEFAULT_REQUEST_TAG_PREFIX = 'sanity.sdk'\n\ntype AllowedClientConfigKey =\n | 'useCdn'\n | 'token'\n | 'perspective'\n | 'apiHost'\n | 'proxy'\n | 'withCredentials'\n | 'timeout'\n | 'maxRetries'\n | 'dataset'\n | 'projectId'\n | 'requestTagPrefix'\n | 'useProjectHostname'\n\nconst allowedKeys = Object.keys({\n apiHost: null,\n useCdn: null,\n token: null,\n perspective: null,\n proxy: null,\n withCredentials: null,\n timeout: null,\n maxRetries: null,\n dataset: null,\n projectId: null,\n scope: null,\n apiVersion: null,\n requestTagPrefix: null,\n useProjectHostname: null,\n resource: null,\n} satisfies Record<keyof ClientOptions, null>) as (keyof ClientOptions)[]\n\nconst DEFAULT_CLIENT_CONFIG: ClientConfig = {\n apiVersion: DEFAULT_API_VERSION,\n useCdn: false,\n ignoreBrowserTokenWarning: true,\n allowReconfigure: false,\n requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,\n}\n\n/**\n * States tracked by the client store\n * @public\n */\nexport interface ClientStoreState {\n token: string | null\n clients: {[TKey in string]?: SanityClient}\n authMethod?: 'localstorage' | 'cookie'\n}\n\n/**\n * Options used when retrieving a client instance from the client store.\n *\n * This interface extends the base {@link ClientConfig} and adds:\n *\n * - **apiVersion:** A required string indicating the API version for the client.\n * - **scope:** An optional flag to choose between the project-specific client\n * ('project') and the global client ('global'). When set to `'global'`, the\n * global client is used.\n *\n * These options are utilized by `getClient` and `getClientState` to configure and\n * return appropriate client instances that automatically handle authentication\n * updates and configuration changes.\n *\n * @public\n */\nexport interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {\n /**\n * An optional flag to choose between the default client (typically project-level)\n * and the global client ('global'). When set to `'global'`, the global client\n * is used.\n */\n scope?: 'default' | 'global'\n /**\n * A required string indicating the API version for the client.\n */\n apiVersion: string\n\n /**\n * @internal\n * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.\n */\n resource?: DocumentResource\n}\n\nconst clientStore = defineStore<ClientStoreState>({\n name: 'clientStore',\n\n getInitialState: (instance) => ({\n clients: {},\n token: getTokenState(instance).getCurrent(),\n }),\n\n initialize(context) {\n const subscription = listenToToken(context)\n const authMethodSubscription = listenToAuthMethod(context)\n return () => {\n subscription.unsubscribe()\n authMethodSubscription.unsubscribe()\n }\n },\n})\n\n/**\n * Updates the client store state when a token is received.\n * @internal\n */\nconst listenToToken = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getTokenState(instance).observable.subscribe((token) => {\n state.set('setTokenAndResetClients', {token, clients: {}})\n })\n}\n\nconst listenToAuthMethod = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getAuthMethodState(instance).observable.subscribe((authMethod) => {\n state.set('setAuthMethod', {authMethod})\n })\n}\n\ntype ClientInstanceCacheKeyInput = ClientConfig &\n Partial<Pick<ClientOptions, 'scope'>> & {\n apiVersion: string\n }\n\nconst getClientConfigKey = (options: ClientInstanceCacheKeyInput) =>\n JSON.stringify(pickProperties(options, allowedKeys))\n\n/**\n * Retrieves a Sanity client instance configured with the provided options.\n *\n * This function returns a client instance configured for the project or as a\n * global client based on the options provided. It ensures efficient reuse of\n * client instances by returning the same instance for the same options.\n * For automatic handling of authentication token updates, consider using\n * `getClientState`.\n *\n * @public\n */\nexport const getClient = bindActionGlobally(\n clientStore,\n ({state, instance}, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'getClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: getClient(instance, { apiVersion: \"2024-11-12\" })',\n )\n }\n\n // Check for disallowed keys\n const providedKeys = Object.keys(options) as (keyof ClientOptions)[]\n const disallowedKeys = providedKeys.filter((key) => !allowedKeys.includes(key))\n\n if (disallowedKeys.length > 0) {\n const listFormatter = new Intl.ListFormat('en', {style: 'long', type: 'conjunction'})\n throw new Error(\n `The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. ` +\n `Allowed keys are: ${listFormatter.format(allowedKeys)}.`,\n )\n }\n\n const tokenFromState = state.get().token\n const {clients, authMethod} = state.get()\n let projectId = options.projectId ?? instance.config.projectId\n let dataset = options.dataset ?? instance.config.dataset\n\n let resource: ClientConfig['resource'] | undefined\n\n if (options.resource) {\n if (isMediaLibraryResource(options.resource)) {\n resource = {type: 'media-library', id: options.resource.mediaLibraryId}\n } else if (isCanvasResource(options.resource)) {\n resource = {type: 'canvas', id: options.resource.canvasId}\n } else if (isDatasetResource(options.resource)) {\n // use project-based routes for datasets to avoid existing CORS and Studio auth cookie issues\n projectId = options.resource.projectId\n dataset = options.resource.dataset\n }\n }\n\n const apiHost = options.apiHost ?? instance.config.auth?.apiHost ?? getStagingApiHost()\n\n const effectiveOptions: ClientConfig & {apiVersion: string} = {\n ...DEFAULT_CLIENT_CONFIG,\n ...((options.scope === 'global' || !projectId || resource) && {useProjectHostname: false}),\n token: authMethod === 'cookie' ? undefined : (tokenFromState ?? undefined),\n ...options,\n ...(projectId && {projectId}),\n ...(dataset && {dataset}),\n ...(resource ? {resource} : {resource: undefined}),\n ...(apiHost && {apiHost}),\n }\n\n // When a resource is provided, don't use projectId/dataset - the client should be \"projectless\"\n // The client code itself will ignore the non-resource config, so we do this to prevent confusing the user.\n // (ref: https://github.com/sanity-io/client/blob/5c23f81f5ab93a53f5b22b39845c867988508d84/src/data/dataMethods.ts#L691)\n if (resource) {\n delete effectiveOptions.projectId\n delete effectiveOptions.dataset\n }\n\n if (effectiveOptions.token === null || typeof effectiveOptions.token === 'undefined') {\n delete effectiveOptions.token\n if (authMethod === 'cookie') {\n effectiveOptions.withCredentials = true\n }\n } else {\n delete effectiveOptions.withCredentials\n }\n\n const key = getClientConfigKey(effectiveOptions)\n\n if (clients[key]) return clients[key]\n\n const client = createClient(effectiveOptions)\n state.set('addClient', (prev) => ({clients: {...prev.clients, [key]: client}}))\n\n return client\n },\n)\n\n/**\n * Returns a state source for the Sanity client instance.\n *\n * This function provides a subscribable state source that emits updated client\n * instances whenever relevant configurations change (such as authentication tokens).\n * Use this when you need to react to client configuration changes in your application.\n *\n * @public\n */\nexport const getClientState = bindActionGlobally(\n clientStore,\n createStateSourceAction(({instance}, options: ClientOptions) => getClient(instance, options)),\n)\n"],"mappings":";;;;;;;;;AAeA,MAiBM,cAAc,OAAO,KAAK;CAC9B,SAAS;CACT,QAAQ;CACR,OAAO;CACP,aAAa;CACb,OAAO;CACP,iBAAiB;CACjB,SAAS;CACT,YAAY;CACZ,SAAS;CACT,WAAW;CACX,OAAO;CACP,YAAY;CACZ,kBAAkB;CAClB,oBAAoB;CACpB,UAAU;AACZ,CAA6C,GAEvC,wBAAsC;CAC1C,YAAY;CACZ,QAAQ;CACR,2BAA2B;CAC3B,kBAAkB;CAClB,kBAAkB;AACpB,GA+CM,cAAc,YAA8B;CAChD,MAAM;CAEN,kBAAkB,cAAc;EAC9B,SAAS,CAAC;EACV,OAAO,cAAc,QAAQ,CAAC,CAAC,WAAW;CAC5C;CAEA,WAAW,SAAS;EAClB,IAAM,eAAe,cAAc,OAAO,GACpC,yBAAyB,mBAAmB,OAAO;EACzD,aAAa;GAEX,AADA,aAAa,YAAY,GACzB,uBAAuB,YAAY;EACrC;CACF;AACF,CAAC,GAMK,iBAAiB,EAAC,UAAU,YACzB,cAAc,QAAQ,CAAC,CAAC,WAAW,WAAW,UAAU;CAC7D,MAAM,IAAI,2BAA2B;EAAC;EAAO,SAAS,CAAC;CAAC,CAAC;AAC3D,CAAC,GAGG,s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a,kBAAkB,KAAA;EAChE,GAAG;EACH,GAAI,aAAa,EAAC,UAAS;EAC3B,GAAI,WAAW,EAAC,QAAO;EACvB,GAAI,WAAW,EAAC,SAAQ,IAAI,EAAC,UAAU,KAAA,EAAS;EAChD,GAAI,WAAW,EAAC,QAAO;CACzB;CAUA,AALI,aACF,OAAO,iBAAiB,WACxB,OAAO,iBAAiB,UAGtB,iBAAiB,UAAU,QAAe,iBAAiB,UAAU,UACvE,OAAO,iBAAiB,OACpB,eAAe,aACjB,iBAAiB,kBAAkB,OAGrC,OAAO,iBAAiB;CAG1B,IAAM,MAAM,mBAAmB,gBAAgB;CAE/C,IAAI,QAAQ,MAAM,OAAO,QAAQ;CAEjC,IAAM,SAAS,aAAa,gBAAgB;CAG5C,OAFA,MAAM,IAAI,cAAc,UAAU,EAAC,SAAS;EAAC,GAAG,KAAK;GAAU,MAAM;CAAM,EAAC,EAAE,GAEvE;AACT,CACF,GAWa,iBAAiB,mBAC5B,aACA,yBAAyB,EAAC,YAAW,YAA2B,UAAU,UAAU,OAAO,CAAC,CAC9F"}
1
+ {"version":3,"file":"clientStore-DnMH7LPG.js","names":[],"sources":["../src/client/clientStore.ts"],"sourcesContent":["import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'\n\nimport {getAuthMethodState, getTokenState} from '../auth/authStore'\nimport {\n type DocumentResource,\n isCanvasResource,\n isDatasetResource,\n isMediaLibraryResource,\n} from '../config/sanityConfig'\nimport {bindActionGlobally} from '../store/createActionBinder'\nimport {createStateSourceAction} from '../store/createStateSourceAction'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {getStagingApiHost} from '../utils/getStagingApiHost'\nimport {pickProperties} from '../utils/object'\n\nconst DEFAULT_API_VERSION = '2024-11-12'\nconst DEFAULT_REQUEST_TAG_PREFIX = 'sanity.sdk'\n\ntype AllowedClientConfigKey =\n | 'useCdn'\n | 'token'\n | 'perspective'\n | 'apiHost'\n | 'proxy'\n | 'withCredentials'\n | 'timeout'\n | 'maxRetries'\n | 'dataset'\n | 'projectId'\n | 'requestTagPrefix'\n | 'useProjectHostname'\n\nconst allowedKeys = Object.keys({\n apiHost: null,\n useCdn: null,\n token: null,\n perspective: null,\n proxy: null,\n withCredentials: null,\n timeout: null,\n maxRetries: null,\n dataset: null,\n projectId: null,\n scope: null,\n apiVersion: null,\n requestTagPrefix: null,\n useProjectHostname: null,\n resource: null,\n} satisfies Record<keyof ClientOptions, null>) as (keyof ClientOptions)[]\n\nconst DEFAULT_CLIENT_CONFIG: ClientConfig = {\n apiVersion: DEFAULT_API_VERSION,\n useCdn: false,\n ignoreBrowserTokenWarning: true,\n allowReconfigure: false,\n requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,\n}\n\n/**\n * States tracked by the client store\n * @public\n */\nexport interface ClientStoreState {\n token: string | null\n clients: {[TKey in string]?: SanityClient}\n authMethod?: 'localstorage' | 'cookie'\n}\n\n/**\n * Options used when retrieving a client instance from the client store.\n *\n * This interface extends the base {@link ClientConfig} and adds:\n *\n * - **apiVersion:** A required string indicating the API version for the client.\n * - **scope:** An optional flag to choose between the project-specific client\n * ('project') and the global client ('global'). When set to `'global'`, the\n * global client is used.\n *\n * These options are utilized by `getClient` and `getClientState` to configure and\n * return appropriate client instances that automatically handle authentication\n * updates and configuration changes.\n *\n * @public\n */\nexport interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {\n /**\n * An optional flag to choose between the default client (typically project-level)\n * and the global client ('global'). When set to `'global'`, the global client\n * is used.\n */\n scope?: 'default' | 'global'\n /**\n * A required string indicating the API version for the client.\n */\n apiVersion: string\n\n /**\n * @internal\n * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.\n */\n resource?: DocumentResource\n}\n\nconst clientStore = defineStore<ClientStoreState>({\n name: 'clientStore',\n\n getInitialState: (instance) => ({\n clients: {},\n token: getTokenState(instance).getCurrent(),\n }),\n\n initialize(context) {\n const subscription = listenToToken(context)\n const authMethodSubscription = listenToAuthMethod(context)\n return () => {\n subscription.unsubscribe()\n authMethodSubscription.unsubscribe()\n }\n },\n})\n\n/**\n * Updates the client store state when a token is received.\n * @internal\n */\nconst listenToToken = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getTokenState(instance).observable.subscribe((token) => {\n state.set('setTokenAndResetClients', {token, clients: {}})\n })\n}\n\nconst listenToAuthMethod = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getAuthMethodState(instance).observable.subscribe((authMethod) => {\n state.set('setAuthMethod', {authMethod})\n })\n}\n\ntype ClientInstanceCacheKeyInput = ClientConfig &\n Partial<Pick<ClientOptions, 'scope'>> & {\n apiVersion: string\n }\n\nconst getClientConfigKey = (options: ClientInstanceCacheKeyInput) =>\n JSON.stringify(pickProperties(options, allowedKeys))\n\n/**\n * Retrieves a Sanity client instance configured with the provided options.\n *\n * This function returns a client instance configured for the project or as a\n * global client based on the options provided. It ensures efficient reuse of\n * client instances by returning the same instance for the same options.\n * For automatic handling of authentication token updates, consider using\n * `getClientState`.\n *\n * @public\n */\nexport const getClient = bindActionGlobally(\n clientStore,\n ({state, instance}, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'getClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: getClient(instance, { apiVersion: \"2024-11-12\" })',\n )\n }\n\n // Check for disallowed keys\n const providedKeys = Object.keys(options) as (keyof ClientOptions)[]\n const disallowedKeys = providedKeys.filter((key) => !allowedKeys.includes(key))\n\n if (disallowedKeys.length > 0) {\n const listFormatter = new Intl.ListFormat('en', {style: 'long', type: 'conjunction'})\n throw new Error(\n `The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. ` +\n `Allowed keys are: ${listFormatter.format(allowedKeys)}.`,\n )\n }\n\n const tokenFromState = state.get().token\n const {clients, authMethod} = state.get()\n let projectId = options.projectId ?? instance.config.projectId\n let dataset = options.dataset ?? instance.config.dataset\n\n let resource: ClientConfig['resource'] | undefined\n\n if (options.resource) {\n if (isMediaLibraryResource(options.resource)) {\n resource = {type: 'media-library', id: options.resource.mediaLibraryId}\n } else if (isCanvasResource(options.resource)) {\n resource = {type: 'canvas', id: options.resource.canvasId}\n } else if (isDatasetResource(options.resource)) {\n // use project-based routes for datasets to avoid existing CORS and Studio auth cookie issues\n projectId = options.resource.projectId\n dataset = options.resource.dataset\n }\n }\n\n const apiHost = options.apiHost ?? instance.config.auth?.apiHost ?? getStagingApiHost()\n\n const effectiveOptions: ClientConfig & {apiVersion: string} = {\n ...DEFAULT_CLIENT_CONFIG,\n ...((options.scope === 'global' || !projectId || resource) && {useProjectHostname: false}),\n token: authMethod === 'cookie' ? undefined : (tokenFromState ?? undefined),\n ...options,\n ...(projectId && {projectId}),\n ...(dataset && {dataset}),\n ...(resource ? {resource} : {resource: undefined}),\n ...(apiHost && {apiHost}),\n }\n\n // When a resource is provided, don't use projectId/dataset - the client should be \"projectless\"\n // The client code itself will ignore the non-resource config, so we do this to prevent confusing the user.\n // (ref: https://github.com/sanity-io/client/blob/5c23f81f5ab93a53f5b22b39845c867988508d84/src/data/dataMethods.ts#L691)\n if (resource) {\n delete effectiveOptions.projectId\n delete effectiveOptions.dataset\n }\n\n if (effectiveOptions.token === null || typeof effectiveOptions.token === 'undefined') {\n delete effectiveOptions.token\n if (authMethod === 'cookie') {\n effectiveOptions.withCredentials = true\n }\n } else {\n delete effectiveOptions.withCredentials\n }\n\n const key = getClientConfigKey(effectiveOptions)\n\n if (clients[key]) return clients[key]\n\n const client = createClient(effectiveOptions)\n state.set('addClient', (prev) => ({clients: {...prev.clients, [key]: client}}))\n\n return client\n },\n)\n\n/**\n * Returns a state source for the Sanity client instance.\n *\n * This function provides a subscribable state source that emits updated client\n * instances whenever relevant configurations change (such as authentication tokens).\n * Use this when you need to react to client configuration changes in your application.\n *\n * @public\n */\nexport const getClientState = bindActionGlobally(\n clientStore,\n createStateSourceAction(({instance}, options: ClientOptions) => getClient(instance, options)),\n)\n"],"mappings":";;;;;;;;;AAeA,MAiBM,cAAc,OAAO,KA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SAAS;EAAC,GAAG,KAAK;GAAU,MAAM;CAAM,EAAC,EAAE,GAEvE;AACT,CACF,GAWa,iBAAiB,mBAC5B,aACA,yBAAyB,EAAC,YAAW,YAA2B,UAAU,UAAU,OAAO,CAAC,CAC9F"}
@@ -27,10 +27,7 @@ const getOrCreateNode$1 = ({ state }, options) => {
27
27
  return nodes.set(options.name, entry), state.set("createNode", { nodes }), node;
28
28
  }, releaseNode$1 = ({ state }, name) => {
29
29
  let nodes = state.get().nodes, existing = nodes.get(name);
30
- if (existing) {
31
- existing.statusUnsub && existing.statusUnsub(), existing.node.stop(), nodes.delete(name), state.set("removeNode", { nodes });
32
- return;
33
- }
30
+ existing && (existing.statusUnsub && existing.statusUnsub(), existing.node.stop(), nodes.delete(name), state.set("removeNode", { nodes }));
34
31
  }, comlinkNodeStore = defineStore({
35
32
  name: "nodeStore",
36
33
  getInitialState: () => ({
@@ -87,4 +84,4 @@ const _getNodeState = bindActionGlobally(comlinkNodeStore, createStateSourceActi
87
84
  }));
88
85
  export { getOrCreateNode as n, releaseNode as r, getNodeState as t };
89
86
 
90
- //# sourceMappingURL=getNodeState-CkxvEZD5.js.map
87
+ //# sourceMappingURL=getNodeState-Bp9sxNE1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getNodeState-CkxvEZD5.js","names":["getOrCreateNode","releaseNode","unboundReleaseNode","unboundGetOrCreateNode"],"sources":["../src/comlink/node/actions/getOrCreateNode.ts","../src/comlink/node/actions/releaseNode.ts","../src/comlink/node/comlinkNodeStore.ts","../src/comlink/node/getNodeState.ts"],"sourcesContent":["import {createNode, type Node, type NodeInput} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {isDeepEqual} from '../../../utils/object'\nimport {type FrameMessage, type WindowMessage} from '../../types'\nimport {type ComlinkNodeState} from '../comlinkNodeStore'\n\nexport const getOrCreateNode = (\n {state}: StoreContext<ComlinkNodeState>,\n options: NodeInput,\n): Node<WindowMessage, FrameMessage> => {\n const nodes = state.get().nodes\n const existing = nodes.get(options.name)\n\n // limit nodes to one per name\n if (existing) {\n if (!isDeepEqual(existing.options, options)) {\n throw new Error(`Node \"${options.name}\" already exists with different options`)\n }\n\n existing.node.start()\n return existing.node\n }\n\n const node: Node<WindowMessage, FrameMessage> = createNode(options)\n node.start()\n\n // Subscribe to status changes\n const statusUnsub = node.onStatus((status) => {\n const currentNodes = state.get().nodes\n const currentEntry = currentNodes.get(options.name)\n if (!currentEntry) return\n const updatedEntry = {\n ...currentEntry,\n status,\n }\n state.set('updateNodeStatus', {\n nodes: new Map(currentNodes).set(options.name, updatedEntry),\n })\n })\n\n // Set up initial entry with status, error, and statusUnsub\n const entry = {\n node,\n options,\n status: 'idle' as const,\n statusUnsub,\n }\n\n nodes.set(options.name, entry)\n\n state.set('createNode', {nodes})\n\n return node\n}\n","import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkNodeState} from '../comlinkNodeStore'\n\nexport const releaseNode = ({state}: StoreContext<ComlinkNodeState>, name: string): void => {\n const nodes = state.get().nodes\n const existing = nodes.get(name)\n\n if (existing) {\n if (existing.statusUnsub) {\n existing.statusUnsub()\n }\n existing.node.stop()\n nodes.delete(name)\n state.set('removeNode', {nodes})\n return\n }\n}\n","import {type Node, type NodeInput, type Status} from '@sanity/comlink'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {type SanityInstance} from '../../store/createSanityInstance'\nimport {defineStore} from '../../store/defineStore'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {getOrCreateNode as unboundGetOrCreateNode} from './actions/getOrCreateNode'\nimport {releaseNode as unboundReleaseNode} from './actions/releaseNode'\n\n/**\n * Individual node with its relevant options\n * @public\n */\nexport interface NodeEntry {\n node: Node<WindowMessage, FrameMessage>\n // we store options to ensure that channels remain as unique / consistent as possible\n options: NodeInput\n // status of the node connection\n status: Status\n statusUnsub?: () => void\n}\n\n/**\n * Internal state tracking comlink connections\n * @public\n */\nexport interface ComlinkNodeState {\n nodes: Map<string, NodeEntry>\n // Map of node name to set of active subscriber symbols\n subscriptions: Map<string, Set<symbol>>\n}\n\nexport const comlinkNodeStore = defineStore<ComlinkNodeState>({\n name: 'nodeStore',\n getInitialState: () => ({\n nodes: new Map(),\n subscriptions: new Map(),\n }),\n\n initialize({state}) {\n return () => {\n state.get().nodes.forEach(({node}) => {\n node.stop()\n })\n }\n },\n})\n\n/**\n * Signals to the store that the consumer has stopped using the node\n * @public\n */\nexport const releaseNode = bindActionGlobally(comlinkNodeStore, unboundReleaseNode)\n\nconst _getOrCreateNode = bindActionGlobally(comlinkNodeStore, unboundGetOrCreateNode)\n\n/**\n * Retrieve or create a node to be used for communication between\n * an application and the controller -- specifically, a node should\n * be created within a frame / window to communicate with the controller.\n *\n * Nodes are shared by name, so the message types must match the protocol spoken on that name.\n * @public\n */\nexport function getOrCreateNode<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n>(instance: SanityInstance, options: NodeInput): Node<TWindowMessage, TFrameMessage> {\n // The store keeps nodes of any protocol, so the message types are the caller's to assert.\n return _getOrCreateNode(instance, options) as Node<TWindowMessage, TFrameMessage>\n}\n","import {type Node, type NodeInput, type Status} from '@sanity/comlink'\nimport {createSelector} from 'reselect'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {type SanityInstance} from '../../store/createSanityInstance'\nimport {\n createStateSourceAction,\n type SelectorContext,\n type StateSource,\n} from '../../store/createStateSourceAction'\nimport {setCleanupTimeout} from '../../utils/setCleanupTimeout'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {\n type ComlinkNodeState,\n comlinkNodeStore,\n getOrCreateNode,\n releaseNode,\n} from './comlinkNodeStore'\n\nconst NODE_RELEASE_TIME = 5000\n\n// Public shape for node state\n/**\n * @public\n */\nexport interface NodeState<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n> {\n node: Node<TWindowMessage, TFrameMessage>\n status: Status | undefined\n}\nconst selectNode = (context: SelectorContext<ComlinkNodeState>, nodeInput: NodeInput) =>\n context.state.nodes.get(nodeInput.name)\n\n/**\n * Provides a subscribable state source for a node by name\n * @param instance - The Sanity instance to get the node state for\n * @param nodeInput - The configuration for the node to get the state for\n\n * @returns A subscribable state source for the node\n * @public\n */\nexport function getNodeState<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n>(\n instance: SanityInstance,\n nodeInput: NodeInput,\n): StateSource<NodeState<TWindowMessage, TFrameMessage> | undefined> {\n // Same caller-asserted message types as `getOrCreateNode`.\n return _getNodeState(instance, nodeInput) as StateSource<\n NodeState<TWindowMessage, TFrameMessage> | undefined\n >\n}\n\nconst _getNodeState = bindActionGlobally(\n comlinkNodeStore,\n createStateSourceAction<ComlinkNodeState, [NodeInput], NodeState | undefined>({\n selector: createSelector([selectNode], (nodeEntry) => {\n return nodeEntry?.status === 'connected'\n ? {\n node: nodeEntry.node,\n status: nodeEntry.status,\n }\n : undefined\n }),\n onSubscribe: ({state, instance}, nodeInput) => {\n const nodeName = nodeInput.name\n const subscriberId = Symbol('comlink-node-subscriber')\n getOrCreateNode(instance, nodeInput)\n\n // Add subscriber to the set for this node\n let subs = state.get().subscriptions.get(nodeName)\n if (!subs) {\n subs = new Set()\n state.get().subscriptions.set(nodeName, subs)\n }\n subs.add(subscriberId)\n\n return () => {\n setCleanupTimeout(() => {\n const activeSubs = state.get().subscriptions.get(nodeName)\n if (activeSubs) {\n activeSubs.delete(subscriberId)\n if (activeSubs.size === 0) {\n state.get().subscriptions.delete(nodeName)\n releaseNode(instance, nodeName)\n }\n }\n }, NODE_RELEASE_TIME)\n }\n },\n }),\n)\n"],"mappings":";;;;AAOA,MAAaA,qBACX,EAAC,SACD,YACsC;CACtC,IAAM,QAAQ,MAAM,IAAI,CAAC,CAAC,OACpB,WAAW,MAAM,IAAI,QAAQ,IAAI;CAGvC,IAAI,UAAU;EACZ,IAAI,CAAC,YAAY,SAAS,S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AAyD;CAEnF,OAAO,iBAAiB,UAAU,OAAO;AAC3C;ACnDA,MAaM,cAAc,SAA4C,cAC9D,QAAQ,MAAM,MAAM,IAAI,UAAU,IAAI;;;;;;;;;AAUxC,SAAgB,aAId,UACA,WACmE;CAEnE,OAAO,cAAc,UAAU,SAAS;AAG1C;AAEA,MAAM,gBAAgB,mBACpB,kBACA,wBAA8E;CAC5E,UAAU,eAAe,CAAC,UAAU,IAAI,cAC/B,WAAW,WAAW,cACzB;EACE,MAAM,UAAU;EAChB,QAAQ,UAAU;CACpB,IACA,KAAA,CACL;CACD,cAAc,EAAC,OAAO,YAAW,cAAc;EAC7C,IAAM,WAAW,UAAU,MACrB,eAAe,OAAO,yBAAyB;EACrD,gBAAgB,UAAU,SAAS;EAGnC,IAAI,OAAO,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,QAAQ;EAOjD,OANK,SACH,uBAAO,IAAI,IAAI,GACf,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,UAAU,IAAI,IAE9C,KAAK,IAAI,YAAY,SAER;GACX,wBAAwB;IACtB,IAAM,aAAa,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,QAAQ;IACzD,AAAI,eACF,WAAW,OAAO,YAAY,GAC1B,WAAW,SAAS,MACtB,MAAM,IAAI,CAAC,CAAC,cAAc,OAAO,QAAQ,GACzC,YAAY,UAAU,QAAQ;GAGpC,GAAG,GAAiB;EACtB;CACF;AACF,CAAC,CACH"}
1
+ {"version":3,"file":"getNodeState-Bp9sxNE1.js","names":["getOrCreateNode","releaseNode","unboundReleaseNode","unboundGetOrCreateNode"],"sources":["../src/comlink/node/actions/getOrCreateNode.ts","../src/comlink/node/actions/releaseNode.ts","../src/comlink/node/comlinkNodeStore.ts","../src/comlink/node/getNodeState.ts"],"sourcesContent":["import {createNode, type Node, type NodeInput} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {isDeepEqual} from '../../../utils/object'\nimport {type FrameMessage, type WindowMessage} from '../../types'\nimport {type ComlinkNodeState} from '../comlinkNodeStore'\n\nexport const getOrCreateNode = (\n {state}: StoreContext<ComlinkNodeState>,\n options: NodeInput,\n): Node<WindowMessage, FrameMessage> => {\n const nodes = state.get().nodes\n const existing = nodes.get(options.name)\n\n // limit nodes to one per name\n if (existing) {\n if (!isDeepEqual(existing.options, options)) {\n throw new Error(`Node \"${options.name}\" already exists with different options`)\n }\n\n existing.node.start()\n return existing.node\n }\n\n const node: Node<WindowMessage, FrameMessage> = createNode(options)\n node.start()\n\n // Subscribe to status changes\n const statusUnsub = node.onStatus((status) => {\n const currentNodes = state.get().nodes\n const currentEntry = currentNodes.get(options.name)\n if (!currentEntry) return\n const updatedEntry = {\n ...currentEntry,\n status,\n }\n state.set('updateNodeStatus', {\n nodes: new Map(currentNodes).set(options.name, updatedEntry),\n })\n })\n\n // Set up initial entry with status, error, and statusUnsub\n const entry = {\n node,\n options,\n status: 'idle' as const,\n statusUnsub,\n }\n\n nodes.set(options.name, entry)\n\n state.set('createNode', {nodes})\n\n return node\n}\n","import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkNodeState} from '../comlinkNodeStore'\n\nexport const releaseNode = ({state}: StoreContext<ComlinkNodeState>, name: string): void => {\n const nodes = state.get().nodes\n const existing = nodes.get(name)\n\n if (existing) {\n if (existing.statusUnsub) {\n existing.statusUnsub()\n }\n existing.node.stop()\n nodes.delete(name)\n state.set('removeNode', {nodes})\n return\n }\n}\n","import {type Node, type NodeInput, type Status} from '@sanity/comlink'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {type SanityInstance} from '../../store/createSanityInstance'\nimport {defineStore} from '../../store/defineStore'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {getOrCreateNode as unboundGetOrCreateNode} from './actions/getOrCreateNode'\nimport {releaseNode as unboundReleaseNode} from './actions/releaseNode'\n\n/**\n * Individual node with its relevant options\n * @public\n */\nexport interface NodeEntry {\n node: Node<WindowMessage, FrameMessage>\n // we store options to ensure that channels remain as unique / consistent as possible\n options: NodeInput\n // status of the node connection\n status: Status\n statusUnsub?: () => void\n}\n\n/**\n * Internal state tracking comlink connections\n * @public\n */\nexport interface ComlinkNodeState {\n nodes: Map<string, NodeEntry>\n // Map of node name to set of active subscriber symbols\n subscriptions: Map<string, Set<symbol>>\n}\n\nexport const comlinkNodeStore = defineStore<ComlinkNodeState>({\n name: 'nodeStore',\n getInitialState: () => ({\n nodes: new Map(),\n subscriptions: new Map(),\n }),\n\n initialize({state}) {\n return () => {\n state.get().nodes.forEach(({node}) => {\n node.stop()\n })\n }\n },\n})\n\n/**\n * Signals to the store that the consumer has stopped using the node\n * @public\n */\nexport const releaseNode = bindActionGlobally(comlinkNodeStore, unboundReleaseNode)\n\nconst _getOrCreateNode = bindActionGlobally(comlinkNodeStore, unboundGetOrCreateNode)\n\n/**\n * Retrieve or create a node to be used for communication between\n * an application and the controller -- specifically, a node should\n * be created within a frame / window to communicate with the controller.\n *\n * Nodes are shared by name, so the message types must match the protocol spoken on that name.\n * @public\n */\nexport function getOrCreateNode<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n>(instance: SanityInstance, options: NodeInput): Node<TWindowMessage, TFrameMessage> {\n // The store keeps nodes of any protocol, so the message types are the caller's to assert.\n return _getOrCreateNode(instance, options) as Node<TWindowMessage, TFrameMessage>\n}\n","import {type Node, type NodeInput, type Status} from '@sanity/comlink'\nimport {createSelector} from 'reselect'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {type SanityInstance} from '../../store/createSanityInstance'\nimport {\n createStateSourceAction,\n type SelectorContext,\n type StateSource,\n} from '../../store/createStateSourceAction'\nimport {setCleanupTimeout} from '../../utils/setCleanupTimeout'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {\n type ComlinkNodeState,\n comlinkNodeStore,\n getOrCreateNode,\n releaseNode,\n} from './comlinkNodeStore'\n\nconst NODE_RELEASE_TIME = 5000\n\n// Public shape for node state\n/**\n * @public\n */\nexport interface NodeState<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n> {\n node: Node<TWindowMessage, TFrameMessage>\n status: Status | undefined\n}\nconst selectNode = (context: SelectorContext<ComlinkNodeState>, nodeInput: NodeInput) =>\n context.state.nodes.get(nodeInput.name)\n\n/**\n * Provides a subscribable state source for a node by name\n * @param instance - The Sanity instance to get the node state for\n * @param nodeInput - The configuration for the node to get the state for\n\n * @returns A subscribable state source for the node\n * @public\n */\nexport function getNodeState<\n TWindowMessage extends WindowMessage = WindowMessage,\n TFrameMessage extends FrameMessage = FrameMessage,\n>(\n instance: SanityInstance,\n nodeInput: NodeInput,\n): StateSource<NodeState<TWindowMessage, TFrameMessage> | undefined> {\n // Same caller-asserted message types as `getOrCreateNode`.\n return _getNodeState(instance, nodeInput) as StateSource<\n NodeState<TWindowMessage, TFrameMessage> | undefined\n >\n}\n\nconst _getNodeState = bindActionGlobally(\n comlinkNodeStore,\n createStateSourceAction<ComlinkNodeState, [NodeInput], NodeState | undefined>({\n selector: createSelector([selectNode], (nodeEntry) => {\n return nodeEntry?.status === 'connected'\n ? {\n node: nodeEntry.node,\n status: nodeEntry.status,\n }\n : undefined\n }),\n onSubscribe: ({state, instance}, nodeInput) => {\n const nodeName = nodeInput.name\n const subscriberId = Symbol('comlink-node-subscriber')\n getOrCreateNode(instance, nodeInput)\n\n // Add subscriber to the set for this node\n let subs = state.get().subscriptions.get(nodeName)\n if (!subs) {\n subs = new Set()\n state.get().subscriptions.set(nodeName, subs)\n }\n subs.add(subscriberId)\n\n return () => {\n setCleanupTimeout(() => {\n const activeSubs = state.get().subscriptions.get(nodeName)\n if (activeSubs) {\n activeSubs.delete(subscriberId)\n if (activeSubs.size === 0) {\n state.get().subscriptions.delete(nodeName)\n releaseNode(instance, nodeName)\n }\n }\n }, NODE_RELEASE_TIME)\n }\n },\n }),\n)\n"],"mappings":";;;;AAOA,MAAaA,qBACX,EAAC,SACD,Y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cAAc,mBAAmB,kBAAkBC,aAAkB,GAE5E,mBAAmB,mBAAmB,kBAAkBC,iBAAsB;;;;;;;;;AAUpF,SAAgB,gBAGd,UAA0B,SAAyD;CAEnF,OAAO,iBAAiB,UAAU,OAAO;AAC3C;ACnDA,MAaM,cAAc,SAA4C,cAC9D,QAAQ,MAAM,MAAM,IAAI,UAAU,IAAI;;;;;;;;;AAUxC,SAAgB,aAId,UACA,WACmE;CAEnE,OAAO,cAAc,UAAU,SAAS;AAG1C;AAEA,MAAM,gBAAgB,mBACpB,kBACA,wBAA8E;CAC5E,UAAU,eAAe,CAAC,UAAU,IAAI,cAC/B,WAAW,WAAW,cACzB;EACE,MAAM,UAAU;EAChB,QAAQ,UAAU;CACpB,IACA,KAAA,CACL;CACD,cAAc,EAAC,OAAO,YAAW,cAAc;EAC7C,IAAM,WAAW,UAAU,MACrB,eAAe,OAAO,yBAAyB;EACrD,gBAAgB,UAAU,SAAS;EAGnC,IAAI,OAAO,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,QAAQ;EAOjD,OANK,SACH,uBAAO,IAAI,IAAI,GACf,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,UAAU,IAAI,IAE9C,KAAK,IAAI,YAAY,SAER;GACX,wBAAwB;IACtB,IAAM,aAAa,MAAM,IAAI,CAAC,CAAC,cAAc,IAAI,QAAQ;IACzD,AAAI,eACF,WAAW,OAAO,YAAY,GAC1B,WAAW,SAAS,MACtB,MAAM,IAAI,CAAC,CAAC,cAAc,OAAO,QAAQ,GACzC,YAAY,UAAU,QAAQ;GAGpC,GAAG,GAAiB;EACtB;CACF;AACF,CAAC,CACH"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { _ as isCanvasResource, a as DatasetResource, b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, g as TokenSource, h as StudioConfig, i as DatasetHandle, l as MediaLibraryResource, m as SanityConfig, n as createSanityInstance, o as DocumentHandle, p as ReleasePerspective, r as CanvasResource, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, v as isDatasetResource, x as AuthProvider, y as isMediaLibraryResource } from "./createSanityInstance--Lrldto8.js";
2
2
  import { n as StateSource, t as Selector } from "./createStateSourceAction-CICvr0ZE.js";
3
- import { $ as Project, $i as LoggedOutAuthState, $n as ResolveProjectionResult, $r as Logger, $t as DocumentPublishedEvent, A as stringifyPath, Ai as CommentTextSelectionItem, An as EditReleaseAction, At as SanityUser, B as getPerspectiveState, Bi as getOAuthTokensState, Bn as createRelease, Br as InstallationAccess, Bt as SetFavoriteInput, C as SanityDocument, Ci as updateComment, Cn as CreateReleaseAction, Ct as TransportEvent, D as joinPaths, Di as CommentReaction, Dn as DocumentAction, Dt as Membership, E as getPathDepth, Ei as CommentMessage, En as DiscardDocumentAction, Et as GetUsersOptions, F as getUsersState, Fi as getClientState, Fn as UnarchiveReleaseAction, Fr as OrganizationBase, Ft as Organizations, Gi as logout, Gn as editRelease, Gr as InstallationsResponse, Gt as ApplyDocumentActionsOptions, H as getActiveReleasesState, Hi as refreshOAuthTokens, Hn as deleteRelease, Hr as InstallationBase, Ht as setFavorite, I as loadMoreUsers, In as UnpublishDocumentAction, Ir as OrganizationMember, It as OrganizationsOptions, J as resolveQuery, Ji as OrgVerificationResult, Jn as scheduleRelease, Jr as configureLogging, Jt as DocumentCreatedEvent, K as getQueryState, Ki as handleAuthCallback, Kn as publishDocument, Kr as installation, Kt as applyDocumentActions, L as resolveUser, Ln as UnscheduleReleaseAction, Lr as OrganizationOptions, Lt as organizations, M as isImportError, Mi as ClientOptions, Mn as PublishReleaseAction, Mt as UserProfile, N as getCorsErrorProjectId, Ni as ClientStoreState, Nn as ReleaseAction, Nt as UsersGroupState, O as jsonMatch, Oi as CommentStatus, On as EditDocumentAction, Ot as ResolveUserOptions, P as getUserState, Pi as getClient, Pn as ScheduleReleaseAction, Pr as Organization, Pt as UsersStoreState, Q as getProjectionState, Qi as LoggedInAuthState, Qn as ResolveDocument, Qr as LogNamespace, Qt as DocumentEvent, R as resolveUsers, Ri as getProjectAccessErrorProjectId, Rn as archiveRelease, Rr as organization, Rt as FavoriteDocumentContext, S as Role, Si as setCommentStatus, Sn as CreateDocumentAction, St as StateEvent, T as getIndexForKey, Ti as CommentLocalState, Tn as DeleteReleaseAction, Tt as GetUserOptions, U as getAllReleasesState, Ui as revokeOAuthTokens, Un as discardDocument, Ur as InstallationInclude, Ut as getReleaseDocumentId, V as ReleaseState, Vi as handleOAuthCallback, Vn as deleteDocument, Vr as InstallationActiveConfig, Vt as favorites, W as QueryOptions, Wi as startOAuthAuthorization, Wn as editDocument, Wr as InstallationsOptions, Wt as ActionsResult, X as projects, Xi as AuthStoreState, Xn as unpublishDocument, Xr as LogContext, Xt as DocumentDiscardedEvent, Y as ProjectsOptions, Yi as AuthState, Yn as unarchiveRelease, Yr as InstanceContext, Yt as DocumentDeletedEvent, Z as resolveProjection, Zi as ErrorAuthState, Zn as unscheduleRelease, Zr as LogLevel, Zt as DocumentEditedEvent, _ as applications, _i as SetCommentStatusOptions, _n as patchOperations, _t as PresencePerspectiveOptions, a as ApplicationInclude, aa as getTokenState, ai as createProjectHandle, an as TransactionSubmissionFailedEvent, at as project, b as CurrentUser, bi as removeComment, bn as Action, bt as ReportPresenceOptions, c as ApplicationStudioConfig, ca as AuthStateType, ci as getCommentThreadsState, cn as getDocumentSyncStatus, ct as PreviewValue, d as ApplicationsOptions, dn as resolvePermissions, dt as getPresence, ea as LoggingInAuthState, ei as LoggerConfig, en as DocumentRemotePatchesEvent, er as ResolveQueryResult, et as ProjectBase, f as ApplicationsResponse, fi as resolveCommentThreads, fn as subscribeDocumentEvents, ft as reportPresence, g as application, gi as ReplyToCommentOptions, gn as ProcessMutationsOptions, gt as PresenceLocation, h as UpdateApplicationInput, hi as RemoveCommentOptions, hn as DocumentSet, ht as DocumentPresenceOptions, i as ApplicationDeployment, ia as getLoginUrlState, ii as createDocumentTypeHandle, in as TransactionRevertedEvent, ir as getDashboardOrganizationId, it as ProjectOptions, j as CORE_SDK_VERSION, ji as CommentThread, jn as PublishDocumentAction, jt as SanityUserResponse, k as slicePath, ki as CommentTextSelection, kn as EditDocumentOptions, kt as ResolveUsersOptions, l as ApplicationVisibility, la as AccessResourceType, ln as getPermissionsState, lt as ProjectionValuePending, m as DeletedResult, mi as CreateCommentOptions, mn as PermissionDeniedReason, mt as DocumentPresence, n as ApplicationAccess, na as getCurrentUserState, ni as createDatasetHandle, nn as DocumentUnpublishedEvent, nt as ProjectMemberRole, o as ApplicationInterface, oa as setAuthToken, oi as CommentsOptions, on as DocumentOptions, ot as PreviewMedia, p as DeleteApplicationInput, pi as resolveComments, pn as DocumentPermissionsResult, pt as DisconnectEvent, qi as observeOrganizationVerificationState, qn as publishRelease, qr as installations, qt as ActionErrorEvent, r as ApplicationBase, ra as getIsInDashboardState, ri as createDocumentHandle, rn as TransactionAcceptedEvent, rt as ProjectMetadata, s as ApplicationInterfacePlacementMetadata, sa as OAuthTokens, si as ResolveCommentsOptions, sn as getDocumentState, st as PreviewQueryResult, t as Application, ta as getAuthState, tn as DocumentTransactionSubmissionResult, tr as datasets, tt as ProjectMember, u as ApplicationWorkspace, ua as checkPermissions, ui as getCommentsState, un as resolveDocument, ut as getDocumentPresence, v as deleteApplication, vi as UpdateCommentOptions, vn as processMutations, vt as PresenceSelection, w as SanityProject, wi as Comment, wn as DeleteDocumentAction, wt as UserPresence, x as ReleaseDocument, xi as replyToComment, xn as ArchiveReleaseAction, xt as RollCallEvent, y as updateApplication, yi as createComment, yn as JsonMatch, yt as PresenceSelectionPoint, z as defineProjection, zn as createDocument, zr as Installation, zt as FavoriteStatusResponse } from "./applications-DowvM7CN.js";
3
+ import { $ as Project, $i as LoggedOutAuthState, $n as ResolveProjectionResult, $r as Logger, $t as DocumentPublishedEvent, A as stringifyPath, Ai as CommentTextSelectionItem, An as EditReleaseAction, At as SanityUser, B as getPerspectiveState, Bi as getOAuthTokensState, Bn as createRelease, Br as InstallationAccess, Bt as SetFavoriteInput, C as SanityDocument, Ci as updateComment, Cn as CreateReleaseAction, Ct as TransportEvent, D as joinPaths, Di as CommentReaction, Dn as DocumentAction, Dt as Membership, E as getPathDepth, Ei as CommentMessage, En as DiscardDocumentAction, Et as GetUsersOptions, F as getUsersState, Fi as getClientState, Fn as UnarchiveReleaseAction, Fr as OrganizationBase, Ft as Organizations, Gi as logout, Gn as editRelease, Gr as InstallationsResponse, Gt as ApplyDocumentActionsOptions, H as getActiveReleasesState, Hi as refreshOAuthTokens, Hn as deleteRelease, Hr as InstallationBase, Ht as setFavorite, I as loadMoreUsers, In as UnpublishDocumentAction, Ir as OrganizationMember, It as OrganizationsOptions, J as resolveQuery, Ji as OrgVerificationResult, Jn as scheduleRelease, Jr as configureLogging, Jt as DocumentCreatedEvent, K as getQueryState, Ki as handleAuthCallback, Kn as publishDocument, Kr as installation, Kt as applyDocumentActions, L as resolveUser, Ln as UnscheduleReleaseAction, Lr as OrganizationOptions, Lt as organizations, M as isImportError, Mi as ClientOptions, Mn as PublishReleaseAction, Mt as UserProfile, N as getCorsErrorProjectId, Ni as ClientStoreState, Nn as ReleaseAction, Nt as UsersGroupState, O as jsonMatch, Oi as CommentStatus, On as EditDocumentAction, Ot as ResolveUserOptions, P as getUserState, Pi as getClient, Pn as ScheduleReleaseAction, Pr as Organization, Pt as UsersStoreState, Q as getProjectionState, Qi as LoggedInAuthState, Qn as ResolveDocument, Qr as LogNamespace, Qt as DocumentEvent, R as resolveUsers, Ri as getProjectAccessErrorProjectId, Rn as archiveRelease, Rr as organization, Rt as FavoriteDocumentContext, S as Role, Si as setCommentStatus, Sn as CreateDocumentAction, St as StateEvent, T as getIndexForKey, Ti as CommentLocalState, Tn as DeleteReleaseAction, Tt as GetUserOptions, U as getAllReleasesState, Ui as revokeOAuthTokens, Un as discardDocument, Ur as InstallationInclude, Ut as getReleaseDocumentId, V as ReleaseState, Vi as handleOAuthCallback, Vn as deleteDocument, Vr as InstallationActiveConfig, Vt as favorites, W as QueryOptions, Wi as startOAuthAuthorization, Wn as editDocument, Wr as InstallationsOptions, Wt as ActionsResult, X as projects, Xi as AuthStoreState, Xn as unpublishDocument, Xr as LogContext, Xt as DocumentDiscardedEvent, Y as ProjectsOptions, Yi as AuthState, Yn as unarchiveRelease, Yr as InstanceContext, Yt as DocumentDeletedEvent, Z as resolveProjection, Zi as ErrorAuthState, Zn as unscheduleRelease, Zr as LogLevel, Zt as DocumentEditedEvent, _ as applications, _i as SetCommentStatusOptions, _n as patchOperations, _t as PresencePerspectiveOptions, a as ApplicationInclude, aa as getTokenState, ai as createProjectHandle, an as TransactionSubmissionFailedEvent, at as project, b as CurrentUser, bi as removeComment, bn as Action, bt as ReportPresenceOptions, c as ApplicationStudioConfig, ca as AuthStateType, ci as getCommentThreadsState, cn as getDocumentSyncStatus, ct as PreviewValue, d as ApplicationsOptions, dn as resolvePermissions, dt as getPresence, ea as LoggingInAuthState, ei as LoggerConfig, en as DocumentRemotePatchesEvent, er as ResolveQueryResult, et as ProjectBase, f as ApplicationsResponse, fi as resolveCommentThreads, fn as subscribeDocumentEvents, ft as reportPresence, g as application, gi as ReplyToCommentOptions, gn as ProcessMutationsOptions, gt as PresenceLocation, h as UpdateApplicationInput, hi as RemoveCommentOptions, hn as DocumentSet, ht as DocumentPresenceOptions, i as ApplicationDeployment, ia as getLoginUrlState, ii as createDocumentTypeHandle, in as TransactionRevertedEvent, ir as getDashboardOrganizationId, it as ProjectOptions, j as CORE_SDK_VERSION, ji as CommentThread, jn as PublishDocumentAction, jt as SanityUserResponse, k as slicePath, ki as CommentTextSelection, kn as EditDocumentOptions, kt as ResolveUsersOptions, l as ApplicationVisibility, la as AccessResourceType, ln as getPermissionsState, lt as ProjectionValuePending, m as DeletedResult, mi as CreateCommentOptions, mn as PermissionDeniedReason, mt as DocumentPresence, n as ApplicationAccess, na as getCurrentUserState, ni as createDatasetHandle, nn as DocumentUnpublishedEvent, nt as ProjectMemberRole, o as ApplicationInterface, oa as setAuthToken, oi as CommentsOptions, on as DocumentOptions, ot as PreviewMedia, p as DeleteApplicationInput, pi as resolveComments, pn as DocumentPermissionsResult, pt as DisconnectEvent, qi as observeOrganizationVerificationState, qn as publishRelease, qr as installations, qt as ActionErrorEvent, r as ApplicationBase, ra as getIsInDashboardState, ri as createDocumentHandle, rn as TransactionAcceptedEvent, rt as ProjectMetadata, s as ApplicationInterfacePlacementMetadata, sa as OAuthTokens, si as ResolveCommentsOptions, sn as getDocumentState, st as PreviewQueryResult, t as Application, ta as getAuthState, tn as DocumentTransactionSubmissionResult, tr as datasets, tt as ProjectMember, u as ApplicationWorkspace, ua as checkPermissions, ui as getCommentsState, un as resolveDocument, ut as getDocumentPresence, v as deleteApplication, vi as UpdateCommentOptions, vn as processMutations, vt as PresenceSelection, w as SanityProject, wi as Comment, wn as DeleteDocumentAction, wt as UserPresence, x as ReleaseDocument, xi as replyToComment, xn as ArchiveReleaseAction, xt as RollCallEvent, y as updateApplication, yi as createComment, yn as JsonMatch, yt as PresenceSelectionPoint, z as defineProjection, zn as createDocument, zr as Installation, zt as FavoriteStatusResponse } from "./applications-CkDu_W5X.js";
4
4
  export { type AccessResourceType, type Action, type ActionErrorEvent, type ActionsResult, type Application, type ApplicationAccess, type ApplicationBase, type ApplicationDeployment, type ApplicationInclude, type ApplicationInterface, type ApplicationInterfacePlacementMetadata, type ApplicationStudioConfig, type ApplicationVisibility, type ApplicationWorkspace, type ApplicationsOptions, type ApplicationsResponse, type ApplyDocumentActionsOptions, type ArchiveReleaseAction, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type CanvasResource, type ClientOptions, type ClientStoreState as ClientState, type Comment, type CommentLocalState, type CommentMessage, type CommentReaction, type CommentStatus, type CommentTextSelection, type CommentTextSelectionItem, type CommentThread, type CommentsOptions, type CreateCommentOptions, type CreateDocumentAction, type CreateReleaseAction, type CurrentUser, type DatasetHandle, type DatasetResource, type DeleteApplicationInput, type DeleteDocumentAction, type DeleteReleaseAction, type DeletedResult, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPresence, type DocumentPresenceOptions, type DocumentPublishedEvent, type DocumentRemotePatchesEvent, type DocumentResource, type DocumentSet, type DocumentTransactionSubmissionResult, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type EditDocumentOptions, type EditReleaseAction, type ErrorAuthState, type FavoriteDocumentContext, type FavoriteStatusResponse, type GetUserOptions, type GetUsersOptions, type Installation, type InstallationAccess, type InstallationActiveConfig, type InstallationBase, type InstallationInclude, type InstallationsOptions, type InstallationsResponse, type InstanceContext, type JsonMatch, type LogContext, type LogLevel, type LogNamespace, type LoggedInAuthState, type LoggedOutAuthState, type Logger, type LoggerConfig, type LoggingInAuthState, type MediaLibraryResource, type Membership, type OAuthTokens, type OrgVerificationResult, type Organization, type OrganizationBase, type OrganizationMember, type OrganizationOptions, type Organizations, type OrganizationsOptions, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PresencePerspectiveOptions, type PresenceSelection, type PresenceSelectionPoint, type PreviewMedia, type PreviewQueryResult, type PreviewValue, type ProcessMutationsOptions, type Project, type ProjectBase, type ProjectHandle, type ProjectMember, type ProjectMemberRole, type ProjectMetadata, type ProjectOptions, type ProjectionValuePending, type ProjectsOptions, type PublishDocumentAction, type PublishReleaseAction, type QueryOptions, type ReleaseAction, type ReleaseDocument, type ReleaseHandle, type ReleasePerspective, type ReleaseState, type RemoveCommentOptions, type ReplyToCommentOptions, type ReportPresenceOptions, type ResolveCommentsOptions, type ResolveDocument, type ResolveProjectionResult, type ResolveQueryResult, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type ScheduleReleaseAction, type Selector, type SetCommentStatusOptions, type SetFavoriteInput, type StateEvent, type StateSource, type StudioConfig, type TokenSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransactionSubmissionFailedEvent, type TransportEvent, type UnarchiveReleaseAction, type UnpublishDocumentAction, type UnscheduleReleaseAction, type UpdateApplicationInput, type UpdateCommentOptions, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, application, applications, applyDocumentActions, archiveRelease, checkPermissions, configureLogging, createComment, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createProjectHandle, createRelease, createSanityInstance, datasets, defineProjection, deleteApplication, deleteDocument, deleteRelease, discardDocument, editDocument, editRelease, favorites, getActiveReleasesState, getAllReleasesState, getAuthState, getClient, getClientState, getCommentThreadsState, getCommentsState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDocumentPresence, getDocumentState, getDocumentSyncStatus, getIndexForKey, getIsInDashboardState, getLoginUrlState, getOAuthTokensState, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getProjectAccessErrorProjectId, getProjectionState, getQueryState, getReleaseDocumentId, getTokenState, getUserState, getUsersState, handleAuthCallback, handleOAuthCallback, installation, installations, isCanvasResource, isDatasetResource, isImportError, isMediaLibraryResource, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, organization, organizations, patchOperations, processMutations, project, projects, publishDocument, publishRelease, refreshOAuthTokens, removeComment, replyToComment, reportPresence, resolveCommentThreads, resolveComments, resolveDocument, resolvePermissions, resolveProjection, resolveQuery, resolveUser, resolveUsers, revokeOAuthTokens, scheduleRelease, setAuthToken, setCommentStatus, setFavorite, slicePath, startOAuthAuthorization, stringifyPath, subscribeDocumentEvents, unarchiveRelease, unpublishDocument, unscheduleRelease, updateApplication, updateComment };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { c as cleanupTimer, f as isReleasePerspective, h as isMediaLibraryResource, i as bindActionGlobally, m as isDatasetResource, n as bindActionByResource, o as UPSTREAM_CLOSE_DELAY_MS, p as isCanvasResource, r as bindActionByResourceAndPerspective, s as defineStore, t as createStateSourceAction, u as setCleanupTimeout } from "./createStateSourceAction-Bn0po7Z3.js";
2
- import { $ as randomUuid, A as toCommentsKeyParts, B as setPendingTransaction, C as commentsStore, E as getCommentsState, F as receiveComment, G as provisionAddonDataset, H as toCommentFieldPath, I as removeCommentById, J as getProjectAccessErrorProjectId, K as COMMENTS_API_VERSION, L as restoreComments, M as applyCommentUpdate, N as clearPendingTransaction, O as resolveCommentThreads, P as getCommentsKey, Q as randomId, R as rollbackCommentUpdate, U as assertDatasetResource, V as normalizeComment, W as getAddonDatasetState, X as defineFetcher, Z as defineMutation, _ as updateLastLoadMoreRequest, a as resolveQuery, b as favorites, c as getAllReleasesState, d as getUsersKey, f as initializeRequest, g as setUsersError, h as setUsersData, j as addComment, k as resolveComments, l as addSubscription, m as removeSubscription, o as getPerspectiveState, p as parseUsersKey, r as getQueryState, s as getActiveReleasesState, t as CORE_SDK_VERSION, u as cancelRequest, v as PROJECT_API_VERSION, w as getCommentThreadsState, x as setFavorite, y as USERS_STATE_CLEAR_DELAY, z as setCommentCreateError } from "./version-7EzMhxQE.js";
3
- import { A as REQUEST_TAG_PREFIX, C as getDefaultLocation, H as createLogger, L as _defineProperty, O as DEFAULT_API_VERSION, T as AuthStateType, V as configureLogging$1, _ as createLoggedInAuthState, a as getCurrentUserState, c as getTokenState, d as appendResourceIndicator, f as createOAuthClient, g as toOAuthTokens, h as serializeTokens, i as getAuthState, k as DEFAULT_BASE, l as setAuthToken, m as postTokenRequest, o as getIsInDashboardState, p as getOAuthOptions, s as getLoginUrlState, t as authStore, u as runOAuthTokenRefresh, v as getAuthCode, w as getTokenFromLocation, y as getCleanedUrl, z as getAuthLogger } from "./authStore-KH1GNOOB.js";
2
+ import { $ as randomUuid, A as toCommentsKeyParts, B as setPendingTransaction, C as commentsStore, E as getCommentsState, F as receiveComment, G as provisionAddonDataset, H as toCommentFieldPath, I as removeCommentById, J as getProjectAccessErrorProjectId, K as COMMENTS_API_VERSION, L as restoreComments, M as applyCommentUpdate, N as clearPendingTransaction, O as resolveCommentThreads, P as getCommentsKey, Q as randomId, R as rollbackCommentUpdate, U as assertDatasetResource, V as normalizeComment, W as getAddonDatasetState, X as defineFetcher, Z as defineMutation, _ as updateLastLoadMoreRequest, a as resolveQuery, b as favorites, c as getAllReleasesState, d as getUsersKey, f as initializeRequest, g as setUsersError, h as setUsersData, j as addComment, k as resolveComments, l as addSubscription, m as removeSubscription, o as getPerspectiveState, p as parseUsersKey, r as getQueryState, s as getActiveReleasesState, t as CORE_SDK_VERSION, u as cancelRequest, v as PROJECT_API_VERSION, w as getCommentThreadsState, x as setFavorite, y as USERS_STATE_CLEAR_DELAY, z as setCommentCreateError } from "./version-Bx_0tNcN.js";
3
+ import { A as REQUEST_TAG_PREFIX, C as getDefaultLocation, H as createLogger, L as _defineProperty, O as DEFAULT_API_VERSION, T as AuthStateType, V as configureLogging$1, _ as createLoggedInAuthState, a as getCurrentUserState, c as getTokenState, d as appendResourceIndicator, f as createOAuthClient, g as toOAuthTokens, h as serializeTokens, i as getAuthState, k as DEFAULT_BASE, l as setAuthToken, m as postTokenRequest, o as getIsInDashboardState, p as getOAuthOptions, s as getLoginUrlState, t as authStore, u as runOAuthTokenRefresh, v as getAuthCode, w as getTokenFromLocation, y as getCleanedUrl, z as getAuthLogger } from "./authStore-DwKgZOzo.js";
4
4
  import { r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
5
- import { n as getClient, r as getClientState } from "./clientStore-DW3iIcbg.js";
6
- import { n as getDashboardOrganizationId } from "./topicStore-CU-oF3fc.js";
5
+ import { n as getClient, r as getClientState } from "./clientStore-DnMH7LPG.js";
6
+ import { n as getDashboardOrganizationId } from "./topicStore-CNzfuPGY.js";
7
7
  import { ClientError, CorsOriginError, ServerError } from "@sanity/client";
8
8
  import { 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, retry, share, skip, startWith, switchMap, take, takeUntil, tap, throttle, throwError, timer, withLatestFrom } from "rxjs";
9
9
  import { isKeySegment, isKeyedObject } from "@sanity/types";
@@ -48,14 +48,10 @@ function createSanityInstance(config = {}) {
48
48
  config,
49
49
  isDisposed: () => disposed.current,
50
50
  dispose: () => {
51
- if (disposed.current) {
52
- logger.trace("Dispose called on already disposed instance", { internal: !0 });
53
- return;
54
- }
55
- logger.trace("Disposing instance", {
51
+ disposed.current ? logger.trace("Dispose called on already disposed instance", { internal: !0 }) : (logger.trace("Disposing instance", {
56
52
  internal: !0,
57
53
  listenerCount: disposeListeners.size
58
- }), disposed.current = !0, disposeListeners.forEach((listener) => listener()), disposeListeners.clear(), logger.info("Instance disposed");
54
+ }), disposed.current = !0, disposeListeners.forEach((listener) => listener()), disposeListeners.clear(), logger.info("Instance disposed"));
59
55
  },
60
56
  onDispose: (cb) => {
61
57
  let listenerId = randomId(16);
@@ -1317,11 +1313,8 @@ const ensureArrayKeysDeep = memoize((input) => {
1317
1313
  */
1318
1314
  function resolvesArraySegments(input, path) {
1319
1315
  let current = input;
1320
- for (let segment of path) {
1321
- if (typeof segment == "string") {
1322
- current = typeof current == "object" && current && !Array.isArray(current) ? current[segment] : void 0;
1323
- continue;
1324
- }
1316
+ for (let segment of path) if (typeof segment == "string") current = typeof current == "object" && current && !Array.isArray(current) ? current[segment] : void 0;
1317
+ else {
1325
1318
  if (!Array.isArray(current)) return !1;
1326
1319
  if (isKeySegment(segment)) {
1327
1320
  let index = getIndexForKey$1(current, segment._key);
@@ -1572,58 +1565,46 @@ function getDocumentIds(selection) {
1572
1565
  function processMutations({ documents, mutations, transactionId, timestamp }) {
1573
1566
  if (!mutations.length) return documents;
1574
1567
  let dataset = { ...documents }, now = timestamp || (/* @__PURE__ */ new Date()).toISOString();
1575
- for (let mutation of mutations) {
1576
- if ("create" in mutation) {
1577
- let id = getId(mutation.create._id);
1578
- if (dataset[id]) throw Error(`Cannot create document with \`_id\` \`${id}\` because another document with the same ID already exists.`);
1579
- dataset[id] = {
1580
- _createdAt: now,
1581
- _updatedAt: now,
1582
- ...mutation.create,
1583
- _rev: transactionId,
1584
- _id: id
1585
- };
1586
- continue;
1587
- }
1588
- if ("createOrReplace" in mutation) {
1589
- let id = getId(mutation.createOrReplace._id), prev = dataset[id];
1590
- dataset[id] = {
1591
- ...mutation.createOrReplace,
1592
- _createdAt: prev?._createdAt || typeof mutation.createOrReplace._createdAt == "string" && mutation.createOrReplace._createdAt || now,
1593
- _updatedAt: prev ? now : typeof mutation.createOrReplace._updatedAt == "string" && mutation.createOrReplace._updatedAt || now,
1594
- _rev: transactionId,
1595
- _id: id
1596
- };
1597
- continue;
1598
- }
1599
- if ("createIfNotExists" in mutation) {
1600
- let id = getId(mutation.createIfNotExists._id);
1601
- if (dataset[id]) continue;
1602
- dataset[id] = {
1603
- _createdAt: now,
1604
- _updatedAt: now,
1605
- ...mutation.createIfNotExists,
1606
- _rev: transactionId,
1607
- _id: id
1608
- };
1609
- continue;
1610
- }
1611
- if ("delete" in mutation) {
1612
- for (let id of getDocumentIds(mutation.delete)) dataset[id] = null;
1613
- continue;
1614
- }
1615
- if ("patch" in mutation) {
1616
- let { patch } = mutation, patched = getDocumentIds(patch).map((id) => {
1617
- if (!dataset[id]) throw Error(`Cannot patch document with ID \`${id}\` because it was not found.`);
1618
- return Object.entries(patchOperations).reduce((acc, [type, operation]) => patch[type] ? operation(acc, patch[type]) : acc, dataset[id]);
1619
- });
1620
- for (let result of patched) dataset[result._id] = {
1621
- ...result,
1622
- _rev: transactionId,
1623
- _updatedAt: now
1624
- };
1625
- continue;
1626
- }
1568
+ for (let mutation of mutations) if ("create" in mutation) {
1569
+ let id = getId(mutation.create._id);
1570
+ if (dataset[id]) throw Error(`Cannot create document with \`_id\` \`${id}\` because another document with the same ID already exists.`);
1571
+ dataset[id] = {
1572
+ _createdAt: now,
1573
+ _updatedAt: now,
1574
+ ...mutation.create,
1575
+ _rev: transactionId,
1576
+ _id: id
1577
+ };
1578
+ } else if ("createOrReplace" in mutation) {
1579
+ let id = getId(mutation.createOrReplace._id), prev = dataset[id];
1580
+ dataset[id] = {
1581
+ ...mutation.createOrReplace,
1582
+ _createdAt: prev?._createdAt || typeof mutation.createOrReplace._createdAt == "string" && mutation.createOrReplace._createdAt || now,
1583
+ _updatedAt: prev ? now : typeof mutation.createOrReplace._updatedAt == "string" && mutation.createOrReplace._updatedAt || now,
1584
+ _rev: transactionId,
1585
+ _id: id
1586
+ };
1587
+ } else if ("createIfNotExists" in mutation) {
1588
+ let id = getId(mutation.createIfNotExists._id);
1589
+ if (dataset[id]) continue;
1590
+ dataset[id] = {
1591
+ _createdAt: now,
1592
+ _updatedAt: now,
1593
+ ...mutation.createIfNotExists,
1594
+ _rev: transactionId,
1595
+ _id: id
1596
+ };
1597
+ } else if ("delete" in mutation) for (let id of getDocumentIds(mutation.delete)) dataset[id] = null;
1598
+ else if ("patch" in mutation) {
1599
+ let { patch } = mutation, patched = getDocumentIds(patch).map((id) => {
1600
+ if (!dataset[id]) throw Error(`Cannot patch document with ID \`${id}\` because it was not found.`);
1601
+ return Object.entries(patchOperations).reduce((acc, [type, operation]) => patch[type] ? operation(acc, patch[type]) : acc, dataset[id]);
1602
+ });
1603
+ for (let result of patched) dataset[result._id] = {
1604
+ ...result,
1605
+ _rev: transactionId,
1606
+ _updatedAt: now
1607
+ };
1627
1608
  }
1628
1609
  return dataset;
1629
1610
  }
@@ -3210,7 +3191,8 @@ function groupTransactionEvents(options) {
3210
3191
  return;
3211
3192
  }
3212
3193
  let isMultiDocument = (event.transactionTotalEvents ?? 0) > 1;
3213
- if (!open) {
3194
+ if (open) event.transactionId === open.transactionId ? (open.events.push(event), open.events.length >= open.total && (closeOpen(), releaseHeld())) : (held.push(event), held.length > maxHeldEvents && releaseEverything());
3195
+ else {
3214
3196
  if (!isMultiDocument) {
3215
3197
  subscriber.next(event);
3216
3198
  return;
@@ -3223,13 +3205,7 @@ function groupTransactionEvents(options) {
3223
3205
  closeOpen(), releaseHeld();
3224
3206
  }, flushDeadline)
3225
3207
  };
3226
- return;
3227
- }
3228
- if (event.transactionId === open.transactionId) {
3229
- open.events.push(event), open.events.length >= open.total && (closeOpen(), releaseHeld());
3230
- return;
3231
3208
  }
3232
- held.push(event), held.length > maxHeldEvents && releaseEverything();
3233
3209
  }, subscription = source.subscribe({
3234
3210
  next: processEvent,
3235
3211
  error: (error) => {