@sanity/sdk 0.0.0-alpha.15 → 0.0.0-alpha.17

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 (36) hide show
  1. package/dist/index.d.ts +24 -13
  2. package/dist/index.js +92 -162
  3. package/dist/index.js.map +1 -1
  4. package/package.json +2 -2
  5. package/src/_exports/index.ts +0 -1
  6. package/src/auth/authConstants.ts +1 -1
  7. package/src/auth/authStore.test.ts +13 -0
  8. package/src/auth/authStore.ts +20 -0
  9. package/src/auth/handleCallback.test.ts +2 -2
  10. package/src/auth/handleCallback.ts +16 -2
  11. package/src/auth/logout.test.ts +1 -1
  12. package/src/auth/refreshStampedToken.test.ts +43 -4
  13. package/src/auth/refreshStampedToken.ts +1 -0
  14. package/src/auth/subscribeToStateAndFetchCurrentUser.test.ts +2 -2
  15. package/src/client/clientStore.ts +3 -0
  16. package/src/common/createLiveEventSubscriber.ts +3 -3
  17. package/src/document/documentStore.ts +0 -1
  18. package/src/document/sharedListener.test.ts +1 -1
  19. package/src/document/sharedListener.ts +1 -1
  20. package/src/instance/types.ts +0 -2
  21. package/src/preview/getPreviewProjection.ts +45 -0
  22. package/src/preview/previewQuery.test.ts +91 -276
  23. package/src/preview/previewQuery.ts +68 -137
  24. package/src/preview/previewStore.ts +15 -2
  25. package/src/preview/subscribeToStateAndFetchBatches.test.ts +3 -22
  26. package/src/preview/subscribeToStateAndFetchBatches.ts +5 -9
  27. package/src/preview/util.ts +1 -1
  28. package/src/query/queryStore.ts +1 -1
  29. package/src/users/usersStore.test.ts +14 -0
  30. package/src/users/usersStore.ts +1 -0
  31. package/src/preview/getProjectionForSchemaType.test.ts +0 -527
  32. package/src/preview/getProjectionForSchemaType.ts +0 -112
  33. package/src/schema/getSchemaState.test.ts +0 -34
  34. package/src/schema/getSchemaState.ts +0 -4
  35. package/src/schema/schemaManager.test.ts +0 -19
  36. package/src/schema/schemaManager.ts +0 -33
package/dist/index.d.ts CHANGED
@@ -20,7 +20,6 @@ import {SanityClient} from '@sanity/client'
20
20
  import {SanityDocument} from '@sanity/types'
21
21
  import {SanityDocumentLike} from '@sanity/types'
22
22
  import {SanityProject as SanityProject_2} from '@sanity/client'
23
- import {SchemaTypeDefinition} from '@sanity/types'
24
23
  import {Subject} from 'rxjs'
25
24
 
26
25
  declare interface AccessAttributeNode extends BaseNode {
@@ -303,6 +302,7 @@ export declare interface AuthStoreState {
303
302
  callbackUrl: string | undefined
304
303
  providedToken: string | undefined
305
304
  }
305
+ dashboardContext?: DashboardContext
306
306
  }
307
307
 
308
308
  /** The base interface for SyntaxNode. */
@@ -481,6 +481,17 @@ export declare const createUsersStore: (instance: SanityInstance | ActionContext
481
481
 
482
482
  export {CurrentUser}
483
483
 
484
+ /**
485
+ * Represents the various states the authentication can be in.
486
+ *
487
+ * @public
488
+ */
489
+ declare interface DashboardContext {
490
+ mode?: string
491
+ env?: string
492
+ orgId?: string | object
493
+ }
494
+
484
495
  declare class DateTime {
485
496
  date: Date
486
497
  constructor(date: Date)
@@ -1524,6 +1535,17 @@ declare interface PosNode extends BaseNode {
1524
1535
  base: ExprNode
1525
1536
  }
1526
1537
 
1538
+ /**
1539
+ * Represents a media asset in a preview.
1540
+ *
1541
+ * @public
1542
+ */
1543
+ declare interface PreviewMedia {
1544
+ type: 'image-asset'
1545
+ _ref: string
1546
+ url: string
1547
+ }
1548
+
1527
1549
  /**
1528
1550
  * @public
1529
1551
  */
@@ -1561,10 +1583,7 @@ export declare interface PreviewValue {
1561
1583
  * An optional piece of media representing the document within its preview.
1562
1584
  * Currently, only image assets are available.
1563
1585
  */
1564
- media?: {
1565
- type: 'image-asset'
1566
- url: string
1567
- } | null
1586
+ media?: PreviewMedia | null
1568
1587
  /**
1569
1588
  * The status of the document.
1570
1589
  */
@@ -1818,7 +1837,6 @@ export declare interface SanityConfig {
1818
1837
  projectId: string
1819
1838
  dataset: string
1820
1839
  auth?: AuthConfig
1821
- schema?: SchemaConfig
1822
1840
  }
1823
1841
 
1824
1842
  export {SanityDocument}
@@ -1859,13 +1877,6 @@ declare interface SanityUserResponse {
1859
1877
  nextCursor: string | null
1860
1878
  }
1861
1879
 
1862
- /**
1863
- * @public
1864
- */
1865
- export declare interface SchemaConfig {
1866
- types: SchemaTypeDefinition[]
1867
- }
1868
-
1869
1880
  declare class Scope {
1870
1881
  params: Record<string, unknown>
1871
1882
  source: Value
package/dist/index.js CHANGED
@@ -3,8 +3,7 @@ import { devtools } from "zustand/middleware";
3
3
  import { createStore as createStore$1 } from "zustand/vanilla";
4
4
  import { createClient } from "@sanity/client";
5
5
  import { createSelector } from "reselect";
6
- import { noop, omit, isEqual } from "lodash-es";
7
- import { Schema } from "@sanity/schema";
6
+ import { noop, omit, isObject, isEqual } from "lodash-es";
8
7
  import { createController, createNode } from "@sanity/comlink";
9
8
  import { SanityEncoder } from "@sanity/mutate";
10
9
  import { getPublishedId as getPublishedId$1 } from "@sanity/client/csm";
@@ -288,7 +287,7 @@ function createFetcherStore({
288
287
  return { getState: getState2, resolveState };
289
288
  }
290
289
  var AuthStateType = /* @__PURE__ */ ((AuthStateType2) => (AuthStateType2.LOGGED_IN = "logged-in", AuthStateType2.LOGGING_IN = "logging-in", AuthStateType2.ERROR = "error", AuthStateType2.LOGGED_OUT = "logged-out", AuthStateType2))(AuthStateType || {});
291
- const DEFAULT_BASE = "http://localhost", AUTH_CODE_PARAM = "sid", DEFAULT_API_VERSION$1 = "2021-06-07", REQUEST_TAG_PREFIX = "sdk.auth", refreshStampedToken = createInternalAction(
290
+ const DEFAULT_BASE = "http://localhost", AUTH_CODE_PARAM = "sid", DEFAULT_API_VERSION$1 = "2021-06-07", REQUEST_TAG_PREFIX = "sanity.sdk.auth", refreshStampedToken = createInternalAction(
292
291
  ({ state }) => {
293
292
  const { clientFactory, apiHost, storageArea, storageKey } = state.get().options, refreshToken$ = state.observable.pipe(
294
293
  map(({ authState }) => authState),
@@ -296,6 +295,8 @@ const DEFAULT_BASE = "http://localhost", AUTH_CODE_PARAM = "sid", DEFAULT_API_VE
296
295
  (authState) => authState.type === AuthStateType.LOGGED_IN
297
296
  ),
298
297
  distinctUntilChanged(),
298
+ filter$1((authState) => authState.token.includes("-st")),
299
+ // Ensure we only try to refresh stamped tokens
299
300
  switchMap$1(
300
301
  (authState) => interval(10 * 60 * 1e3).pipe(
301
302
  takeWhile(() => state.get().authState.type === AuthStateType.LOGGED_IN),
@@ -581,13 +582,13 @@ function generateArrayKey(length = 12) {
581
582
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, length);
582
583
  }
583
584
  function memoize(fn) {
584
- const cache2 = /* @__PURE__ */ new WeakMap();
585
+ const cache = /* @__PURE__ */ new WeakMap();
585
586
  return (input) => {
586
587
  if (!input || typeof input != "object") return fn(input);
587
- const cached = cache2.get(input);
588
+ const cached = cache.get(input);
588
589
  if (cached) return cached;
589
590
  const result = fn(input);
590
- return cache2.set(input, result), result;
591
+ return cache.set(input, result), result;
591
592
  };
592
593
  }
593
594
  const ensureArrayKeysDeep = memoize((input) => {
@@ -790,7 +791,7 @@ function unsetDeep(input, path) {
790
791
  )
791
792
  ) : Array.isArray(input) ? input.filter((_nestedInput, index) => index !== segment) : Object.fromEntries(Object.entries(input).filter(([key]) => key !== segment.toString())) : input;
792
793
  }
793
- const DEFAULT_API_VERSION = "2024-11-12", clientStore = {
794
+ const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.sdk", clientStore = {
794
795
  name: "clientStore",
795
796
  getInitialState: (instance) => {
796
797
  const { identity, config } = instance, defaultClient = createClient({
@@ -799,6 +800,7 @@ const DEFAULT_API_VERSION = "2024-11-12", clientStore = {
799
800
  token: config?.auth?.token,
800
801
  useCdn: !1,
801
802
  apiVersion: DEFAULT_API_VERSION,
803
+ requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,
802
804
  ...config?.auth?.apiHost ? { apiHost: config.auth.apiHost } : {}
803
805
  }), defaultGlobalClient = createClient({
804
806
  token: config?.auth?.token,
@@ -806,6 +808,7 @@ const DEFAULT_API_VERSION = "2024-11-12", clientStore = {
806
808
  apiVersion: "vX",
807
809
  // Many global APIs are only available under this version, we may need to support other versions in the future
808
810
  useProjectHostname: !1,
811
+ requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,
809
812
  ...config?.auth?.apiHost ? { apiHost: config.auth.apiHost } : {}
810
813
  });
811
814
  return {
@@ -886,8 +889,18 @@ const DEFAULT_API_VERSION = "2024-11-12", clientStore = {
886
889
  if (authState.type === AuthStateType.LOGGING_IN && authState.isExchangingToken) return !1;
887
890
  const authCode = getAuthCode(callbackUrl, locationHref);
888
891
  if (!authCode) return !1;
892
+ const parsedUrl = new URL(locationHref);
893
+ let dashboardContext = {};
894
+ try {
895
+ const contextParam = parsedUrl.searchParams.get("_context") ?? "{}";
896
+ dashboardContext = JSON.parse(contextParam);
897
+ } catch (err) {
898
+ console.error("Failed to parse dashboard context:", err);
899
+ }
900
+ const { mode, env, orgId } = dashboardContext;
889
901
  state.set("exchangeSessionForToken", {
890
- authState: { type: AuthStateType.LOGGING_IN, isExchangingToken: !0 }
902
+ authState: { type: AuthStateType.LOGGING_IN, isExchangingToken: !0 },
903
+ dashboardContext: { mode, env, orgId }
891
904
  });
892
905
  try {
893
906
  const client = clientFactory({
@@ -931,16 +944,7 @@ const DEFAULT_API_VERSION = "2024-11-12", clientStore = {
931
944
  }), storageArea?.removeItem(storageKey);
932
945
  }
933
946
  };
934
- }), schemaManager = {
935
- name: "schemaManager",
936
- getInitialState(instance) {
937
- const { config } = instance;
938
- return { schema: Schema.compile({
939
- name: "default",
940
- types: config.schema?.types ?? []
941
- }) };
942
- }
943
- };
947
+ });
944
948
  function createLiveEventSubscriber(tag) {
945
949
  return createInternalAction(({ instance, state }) => {
946
950
  const client$ = getClientState(instance, { apiVersion: "vX" }).observable, syncTags$ = state.observable.pipe(
@@ -968,88 +972,45 @@ function createLiveEventSubscriber(tag) {
968
972
  };
969
973
  });
970
974
  }
971
- const getSchemaState = createStateSourceAction(schemaManager, (state) => state.schema);
972
975
  function hashString(str) {
973
976
  let hash = 0;
974
977
  for (let i2 = 0; i2 < str.length; i2++)
975
978
  hash = (hash * 31 + str.charCodeAt(i2)) % 2147483647;
976
979
  return Math.abs(hash).toString(16).padStart(8, "0");
977
980
  }
978
- function getProjectionForSchemaType(schema, schemaTypeName) {
979
- const schemaType = schema.get(schemaTypeName);
980
- if (!schemaType)
981
- throw new Error(`Could not find type \`${schemaTypeName}\` in the provided schema.`);
982
- return `{${Object.entries(schemaType.preview?.select ?? {}).map(([key, path]) => `${JSON.stringify(key)}:${getGroqFromPath(schema, schemaType, path)}`).join(",")}}`;
983
- }
984
- function isReferenceType(type, visited = /* @__PURE__ */ new Set()) {
985
- return !type || visited.has(type) ? !1 : (visited.add(type), type.name === "reference" ? !0 : isReferenceType(type.type, visited));
986
- }
987
- function printPath(segments) {
988
- return segments.reduce((acc, segment) => segment.type === "deref" ? `${acc}->` : segment.type === "element" ? `${acc}[${segment.index}]` : acc.endsWith("->") ? `${acc}${segment.name}` : [acc, segment.name].filter(Boolean).join("."), "");
989
- }
990
- const cache = /* @__PURE__ */ new WeakMap();
991
- function getGroqFromPath(schema, node, path) {
992
- const cached = cache.get(node)?.get(path);
993
- if (cached) return cached;
994
- const possiblePaths = Array.from(
995
- new Set(resolveAllPaths(schema, node, path.split(".")).map(printPath))
996
- );
997
- if (!possiblePaths.length)
998
- return console.warn(`Could not resolve path \`${path}\` from schema type \`${node.name}\`.`), "null";
999
- const result = possiblePaths.length === 1 ? possiblePaths[0] : `coalesce(${possiblePaths.join(",")})`;
1000
- return cache.has(node) || cache.set(node, /* @__PURE__ */ new Map()), cache.get(node).set(path, result), result;
1001
- }
1002
- function resolveAllPaths(schema, schemaType, path) {
1003
- const [name, ...rest] = path;
1004
- if (name?.startsWith("_"))
1005
- return [
1006
- [
1007
- { type: "attribute", name },
1008
- ...rest.map(
1009
- (next) => /\d+/.test(next) ? { type: "element", index: parseInt(next, 10) } : { type: "attribute", name: next }
1010
- )
1011
- ]
1012
- ];
1013
- if (name) {
1014
- if (isReferenceType(schemaType))
1015
- return schemaType.to.flatMap(
1016
- (referenceType) => resolveAllPaths(schema, referenceType, path).map((nextPath) => [
1017
- { type: "deref" },
1018
- ...nextPath
1019
- ])
1020
- );
1021
- if (schemaType.jsonType === "object") {
1022
- const fieldType = schemaType.fields.find((field) => field.name === name)?.type;
1023
- return fieldType ? resolveAllPaths(schema, fieldType, rest).map((nextPath) => [
1024
- { type: "attribute", name },
1025
- ...nextPath
1026
- ]) : [];
1027
- } else if (schemaType.jsonType === "array") {
1028
- const index = parseInt(name, 10);
1029
- return schemaType.of.flatMap(
1030
- (itemType) => resolveAllPaths(schema, itemType, rest).map((nextPath) => [
1031
- { type: "element", index },
1032
- ...nextPath
1033
- ])
1034
- );
1035
- } else
1036
- return [];
1037
- } else return [[]];
981
+ const TITLE_CANDIDATES = ["title", "name", "label", "heading", "header", "caption"], SUBTITLE_CANDIDATES = ["description", "subtitle", ...TITLE_CANDIDATES];
982
+ function getPreviewProjection() {
983
+ return `{
984
+ // Get all potential title fields
985
+ "titleCandidates": {
986
+ ${TITLE_CANDIDATES.map((field) => `"${field}": ${field}`).join(`,
987
+ `)}
988
+ },
989
+ // Get all potential subtitle fields
990
+ "subtitleCandidates": {
991
+ ${SUBTITLE_CANDIDATES.map((field) => `"${field}": ${field}`).join(`,
992
+ `)}
993
+ },
994
+ "media": coalesce(
995
+ select(
996
+ defined(asset) => {"type": "image-asset", "_ref": asset._ref},
997
+ defined(image.asset) => {"type": "image-asset", "_ref": image.asset._ref},
998
+ defined(mainImage.asset) => {"type": "image-asset", "_ref": mainImage.asset._ref},
999
+ null
1000
+ )
1001
+ ),
1002
+ _type,
1003
+ _id,
1004
+ _updatedAt
1005
+ }`;
1038
1006
  }
1039
- const PREVIEW_TAG = "sdk.preview", STABLE_EMPTY_PREVIEW = { results: null, isPending: !1 }, STABLE_ERROR_PREVIEW = {
1007
+ const PREVIEW_TAG = "preview", STABLE_EMPTY_PREVIEW = { results: null, isPending: !1 }, STABLE_ERROR_PREVIEW = {
1040
1008
  results: {
1041
1009
  title: "Preview Error",
1042
1010
  ...!!getEnv("DEV") && { subtitle: "Check the console for more details" }
1043
1011
  },
1044
1012
  isPending: !1
1045
1013
  };
1046
- function defaultPrepare(value) {
1047
- let title, subtitle;
1048
- return "title" in value && typeof value.title == "string" && (title = value.title), "subtitle" in value && typeof value.subtitle == "string" && (subtitle = value.subtitle), { title: title ?? "Untitled", subtitle };
1049
- }
1050
- function hasImageAsset(value) {
1051
- return typeof value == "object" && value !== null && "asset" in value && typeof value.asset == "object" && typeof value.asset?._ref == "string";
1052
- }
1053
1014
  function assetIdToUrl(assetId, projectId, dataset) {
1054
1015
  const pattern = /^image-(?<assetName>[A-Za-z0-9]+)-(?<dimensions>\d+x\d+)-(?<format>[a-z]+)$/, match = assetId.match(pattern);
1055
1016
  if (!match?.groups)
@@ -1059,53 +1020,43 @@ function assetIdToUrl(assetId, projectId, dataset) {
1059
1020
  const { assetName, dimensions, format } = match.groups;
1060
1021
  return `https://cdn.sanity.io/images/${projectId}/${dataset}/${assetName}-${dimensions}.${format}`;
1061
1022
  }
1023
+ function hasImageRef(value) {
1024
+ return isObject(value) && "_ref" in value && typeof value._ref == "string";
1025
+ }
1062
1026
  function normalizeMedia(media, projectId, dataset) {
1063
- return !media || !hasImageAsset(media) ? null : { type: "image-asset", url: assetIdToUrl(media.asset._ref, projectId, dataset) };
1027
+ return !media || !hasImageRef(media) ? null : {
1028
+ type: "image-asset",
1029
+ _ref: media._ref,
1030
+ url: assetIdToUrl(media._ref, projectId, dataset)
1031
+ };
1064
1032
  }
1065
- function preparePreviewForSchemaType({
1066
- projectId,
1067
- dataset,
1068
- schema,
1069
- schemaTypeName,
1070
- selectResult
1071
- }) {
1072
- const schemaType = schema.get(schemaTypeName);
1073
- if (!schemaType)
1074
- throw new Error(
1075
- `Could not find schema type \`${schemaTypeName}\` in schema \`${schema.name}\`.`
1076
- );
1077
- const prepare = schemaType.preview?.prepare ?? defaultPrepare;
1078
- try {
1079
- const result = prepare(selectResult);
1080
- return { ...result, media: normalizeMedia(result.media, projectId, dataset) };
1081
- } catch (e3) {
1082
- const message = typeof e3 == "object" && e3 && "message" in e3 && typeof e3.message == "string" ? e3.message : "Unknown error.";
1083
- throw new Error(`Failed to prepare preview: ${message}`, { cause: e3 });
1084
- }
1033
+ function findFirstDefined(fieldsToSearch, candidates, exclude) {
1034
+ if (candidates)
1035
+ for (const field of fieldsToSearch) {
1036
+ const value = candidates[field];
1037
+ if (typeof value == "string" && value.trim() !== "" && value !== exclude)
1038
+ return value;
1039
+ }
1085
1040
  }
1086
1041
  function processPreviewQuery({
1087
1042
  projectId,
1088
1043
  dataset,
1089
- schema,
1090
1044
  ids,
1091
- documentTypes,
1092
1045
  results
1093
1046
  }) {
1094
1047
  const resultMap = results.reduce((acc, next) => (acc[next._id] = next, acc), {});
1095
1048
  return Object.fromEntries(
1096
1049
  Array.from(ids).map((id) => {
1097
- const publishedId = getPublishedId(id), draftId = getDraftId(id), draftResult = resultMap[draftId], publishedResult = resultMap[publishedId], documentType = documentTypes[publishedId];
1098
- if (!documentType) return [id, STABLE_EMPTY_PREVIEW];
1099
- const selectResult = draftResult?.select ?? publishedResult?.select;
1100
- if (!selectResult) return [id, STABLE_EMPTY_PREVIEW];
1050
+ const publishedId = getPublishedId(id), draftId = getDraftId(id), draftResult = resultMap[draftId], publishedResult = resultMap[publishedId];
1051
+ if (!draftResult && !publishedResult) return [id, STABLE_EMPTY_PREVIEW];
1101
1052
  try {
1102
- const preview = preparePreviewForSchemaType({
1103
- projectId,
1104
- dataset,
1105
- schema,
1106
- schemaTypeName: documentType,
1107
- selectResult
1108
- }), status = {
1053
+ const result = draftResult || publishedResult;
1054
+ if (!result) return [id, STABLE_EMPTY_PREVIEW];
1055
+ const title = findFirstDefined(TITLE_CANDIDATES, result.titleCandidates), subtitle = findFirstDefined(SUBTITLE_CANDIDATES, result.subtitleCandidates, title), preview = {
1056
+ title: String(title || `${result._type}: ${result._id}`),
1057
+ subtitle: subtitle || void 0,
1058
+ media: normalizeMedia(result.media, projectId, dataset)
1059
+ }, status = {
1109
1060
  ...draftResult?._updatedAt && { lastEditedDraftAt: draftResult._updatedAt },
1110
1061
  ...publishedResult?._updatedAt && { lastEditedPublishedAt: publishedResult._updatedAt }
1111
1062
  };
@@ -1116,37 +1067,18 @@ function processPreviewQuery({
1116
1067
  })
1117
1068
  );
1118
1069
  }
1119
- function createPreviewQuery(documentIds, documentTypes, schema) {
1120
- const documentIdsByDocumentType = Array.from(documentIds).reduce(
1121
- (acc, id) => {
1122
- const documentType = documentTypes[id];
1123
- if (!documentType) return acc;
1124
- const ids = acc[documentType] ?? /* @__PURE__ */ new Set();
1125
- return ids.add(id), acc[documentType] = ids, acc;
1126
- },
1127
- {}
1128
- ), projections = Object.keys(documentIdsByDocumentType).map((documentType) => {
1129
- const projection = getProjectionForSchemaType(schema, documentType), projectionHash = hashString(projection);
1130
- return { documentType, projection, projectionHash };
1131
- }).reduce((acc, { documentType, projection, projectionHash }) => {
1132
- const obj = acc[projectionHash] ?? { documentTypes: /* @__PURE__ */ new Set(), projection };
1133
- return obj.documentTypes.add(documentType), acc[projectionHash] = obj, acc;
1134
- }, {}), query = `[${Object.entries(projections).map(([projectionHash, { projection }]) => `...*[_id in $__ids_${projectionHash}]{_id,_type,_updatedAt,"select":${projection}}`).join(",")}]`, params = Object.fromEntries(
1135
- Object.entries(projections).map(([projectionHash, value]) => {
1136
- const idsInProjection = Array.from(
1137
- Array.from(value.documentTypes).map((documentType) => documentIdsByDocumentType[documentType] ?? /* @__PURE__ */ new Set()).reduce((acc, next) => {
1138
- for (const i2 of next) acc.add(i2);
1139
- return acc;
1140
- }, /* @__PURE__ */ new Set())
1141
- ).flatMap((id) => [getPublishedId(id), getDraftId(id)]);
1142
- return [`__ids_${projectionHash}`, Array.from(idsInProjection)];
1143
- })
1144
- );
1145
- return { query, params };
1070
+ function createPreviewQuery(documentIds) {
1071
+ const allIds = Array.from(documentIds).flatMap((id) => [getPublishedId(id), getDraftId(id)]), projection = getPreviewProjection(), queryHash = hashString(projection);
1072
+ return {
1073
+ query: `*[_id in $__ids_${queryHash}]${projection}`,
1074
+ params: {
1075
+ [`__ids_${queryHash}`]: allIds
1076
+ }
1077
+ };
1146
1078
  }
1147
1079
  const BATCH_DEBOUNCE_TIME$1 = 50, subscribeToStateAndFetchBatches$1 = createInternalAction(
1148
1080
  ({ state, instance }) => function() {
1149
- const client$ = getClientState(instance, { apiVersion: "vX" }).observable, schema$ = getSchemaState(instance).observable, documentTypes$ = state.observable.pipe(
1081
+ const client$ = getClientState(instance, { apiVersion: "vX" }).observable, documentTypes$ = state.observable.pipe(
1150
1082
  map((i2) => i2.documentTypes),
1151
1083
  distinctUntilChanged()
1152
1084
  ), lastLiveEventId$ = state.observable.pipe(
@@ -1173,27 +1105,25 @@ const BATCH_DEBOUNCE_TIME$1 = 50, subscribeToStateAndFetchBatches$1 = createInte
1173
1105
  withLatestFrom(documentTypes$),
1174
1106
  map(([[, ids], documentTypes]) => ({ ids, documentTypes }))
1175
1107
  );
1176
- return combineLatest([newSubscriberIds$, lastLiveEventId$, client$, schema$]).pipe(
1177
- switchMap$1(([{ ids, documentTypes }, lastLiveEventId, client, schema]) => {
1108
+ return combineLatest([newSubscriberIds$, lastLiveEventId$, client$]).pipe(
1109
+ switchMap$1(([{ ids }, lastLiveEventId, client]) => {
1178
1110
  if (!ids.size) return EMPTY;
1179
- const { query, params } = createPreviewQuery(ids, documentTypes, schema);
1111
+ const { query, params } = createPreviewQuery(ids);
1180
1112
  return client.observable.fetch(query, params, {
1181
1113
  filterResponse: !1,
1182
1114
  returnQuery: !1,
1183
1115
  perspective: "drafts",
1184
1116
  tag: PREVIEW_TAG,
1185
1117
  lastLiveEventId
1186
- }).pipe(map((response) => ({ ...response, ids, schema, documentTypes })));
1118
+ }).pipe(map((response) => ({ ...response, ids })));
1187
1119
  }),
1188
- map(({ ids, result, syncTags, documentTypes, schema }) => ({
1120
+ map(({ ids, result, syncTags }) => ({
1189
1121
  syncTags,
1190
1122
  values: processPreviewQuery({
1191
1123
  projectId: instance.identity.projectId,
1192
1124
  dataset: instance.identity.dataset,
1193
1125
  ids,
1194
- documentTypes,
1195
- results: result,
1196
- schema
1126
+ results: result
1197
1127
  })
1198
1128
  }))
1199
1129
  ).subscribe({
@@ -4384,7 +4314,7 @@ function createSharedListener(instance) {
4384
4314
  {
4385
4315
  events: ["mutation", "welcome", "reconnect"],
4386
4316
  includeResult: !1,
4387
- tag: "sdk.document-listener"
4317
+ tag: "document-listener"
4388
4318
  // // from manual testing, it seems like mendoza patches may be
4389
4319
  // // causing some ambiguity/wonkiness
4390
4320
  // includeMutations: false,
@@ -4590,7 +4520,6 @@ const _resolveDocument = createAction(documentStore, () => function(doc) {
4590
4520
  switchMap$1(
4591
4521
  (client) => client.observable.request({
4592
4522
  uri: `/projects/${projectId}/datasets/${dataset}/acl`,
4593
- // TODO: audit tags
4594
4523
  tag: "acl.get",
4595
4524
  withCredentials: !0
4596
4525
  })
@@ -4704,7 +4633,8 @@ const _applyActions = createAction(documentStore, ({ state }) => {
4704
4633
  return getClient(instance, { scope: "global", apiVersion: API_VERSION }).request({
4705
4634
  method: "GET",
4706
4635
  uri: `access/${resourceType}/${resourceId}/users`,
4707
- query: nextCursor ? { nextCursor, limit: limit.toString() } : { limit: limit.toString() }
4636
+ query: nextCursor ? { nextCursor, limit: limit.toString() } : { limit: limit.toString() },
4637
+ tag: "users"
4708
4638
  });
4709
4639
  }, loadMore = createAction(usersStore, ({ state, instance }) => async function() {
4710
4640
  const { users, nextCursor, options } = state.get(), { resourceType, resourceId, limit } = options;
@@ -4845,7 +4775,7 @@ const _applyActions = createAction(documentStore, ({ state }) => {
4845
4775
  ({ state, instance }) => function() {
4846
4776
  const liveMessages$ = getClientState(instance, { apiVersion: "vX" }).observable.pipe(
4847
4777
  switchMap$1(
4848
- (client) => client.live.events({ includeDrafts: !!client.config().token, tag: "TODO_TAG" })
4778
+ (client) => client.live.events({ includeDrafts: !!client.config().token, tag: "query-store" })
4849
4779
  ),
4850
4780
  share(),
4851
4781
  filter$1((e3) => e3.type === "message")
@@ -4912,7 +4842,7 @@ const _resolveQuery = createAction(queryStore, ({ state }) => function(query, {
4912
4842
  );
4913
4843
  return firstValueFrom(race([resolved$, aborted$]));
4914
4844
  });
4915
- var version = "0.0.0-alpha.15";
4845
+ var version = "0.0.0-alpha.17";
4916
4846
  const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
4917
4847
  export {
4918
4848
  AuthStateType,