@sanity/sdk 2.18.0 → 3.0.0-rc.1

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 (53) hide show
  1. package/dist/_chunks-dts/createGroqSearchFilter.d.ts +233 -12
  2. package/dist/_chunks-dts/createGroqSearchFilter.d.ts.map +1 -1
  3. package/dist/_chunks-es/_internal.js +1 -0
  4. package/dist/_chunks-es/_internal.js.map +1 -1
  5. package/dist/_chunks-es/createGroqSearchFilter.js +284 -6
  6. package/dist/_chunks-es/createGroqSearchFilter.js.map +1 -1
  7. package/dist/_chunks-es/telemetryManager.js +2 -2
  8. package/dist/_exports/_internal.d.ts +2 -2
  9. package/dist/_exports/_internal.d.ts.map +1 -1
  10. package/dist/_exports/_internal.js +3 -1
  11. package/dist/index.d.ts +599 -185
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +492 -337
  14. package/dist/index.js.map +1 -1
  15. package/package.json +7 -7
  16. package/src/_exports/_internal.ts +11 -0
  17. package/src/_exports/index.ts +57 -12
  18. package/src/access/checkPermissions.test.ts +55 -0
  19. package/src/access/checkPermissions.ts +54 -0
  20. package/src/applications/applications.test-d.ts +83 -0
  21. package/src/applications/applications.test.ts +130 -0
  22. package/src/applications/applications.ts +364 -0
  23. package/src/applications/userApplications.test.ts +126 -0
  24. package/src/applications/userApplications.ts +261 -0
  25. package/src/auth/getOrganizationVerificationState.test.ts +7 -7
  26. package/src/auth/getOrganizationVerificationState.ts +4 -4
  27. package/src/document/documentStore.concurrency.test.ts +313 -22
  28. package/src/installations/installations.test-d.ts +68 -0
  29. package/src/installations/installations.test.ts +62 -0
  30. package/src/installations/installations.ts +202 -0
  31. package/src/organization/organization.test-d.ts +18 -84
  32. package/src/organization/organization.test.ts +11 -11
  33. package/src/organization/organization.ts +26 -54
  34. package/src/organizations/organizations.test-d.ts +11 -32
  35. package/src/organizations/organizations.test.ts +8 -8
  36. package/src/organizations/organizations.ts +29 -54
  37. package/src/project/project.test-d.ts +19 -75
  38. package/src/project/project.test.ts +57 -10
  39. package/src/project/project.ts +33 -52
  40. package/src/projects/projects.test-d.ts +15 -21
  41. package/src/projects/projects.test.ts +8 -8
  42. package/src/projects/projects.ts +25 -49
  43. package/src/store/fetcherStore.test-d.ts +121 -0
  44. package/src/store/fetcherStore.test.ts +299 -0
  45. package/src/store/fetcherStore.ts +801 -0
  46. package/src/utils/buildQuery.test.ts +14 -0
  47. package/src/utils/buildQuery.ts +17 -0
  48. package/src/utils/includeShape.ts +36 -0
  49. package/src/utils/setCleanupTimeout.ts +21 -8
  50. package/dist/_chunks-es/version.js +0 -7
  51. package/dist/_chunks-es/version.js.map +0 -1
  52. package/src/utils/defineIntent.test.ts +0 -477
  53. package/src/utils/defineIntent.ts +0 -244
@@ -1,6 +1,8 @@
1
- import { createImageUrlBuilder } from "@sanity/image-url";
2
- import { Observable, map, distinctUntilChanged, shareReplay, skip, defer, finalize, filter, exhaustMap, timer, switchMap, takeWhile, catchError, EMPTY, fromEvent, retry, BehaviorSubject, combineLatest, startWith, tap, NEVER, first, firstValueFrom, race, pairwise, mergeMap, groupBy, of, share } from "rxjs";
3
1
  import { createClient, CorsOriginError, DisconnectError, ConnectionFailedError } from "@sanity/client";
2
+ import { createImageUrlBuilder } from "@sanity/image-url";
3
+ import "groq";
4
+ import { Observable, map, distinctUntilChanged, shareReplay, skip, defer, finalize, filter, exhaustMap, timer, switchMap, takeWhile, catchError, EMPTY, fromEvent, retry, BehaviorSubject, combineLatest, startWith, tap, pairwise, mergeMap, groupBy, of, share, NEVER, first, firstValueFrom, race, Subscription } from "rxjs";
5
+ import "@sanity/types";
4
6
  import { devtools } from "zustand/middleware";
5
7
  import { createStore } from "zustand/vanilla";
6
8
  import { createSelector } from "reselect";
@@ -1262,9 +1264,17 @@ const ARCHIVED_RELEASE_STATES = ["archived", "published"], STABLE_EMPTY_RELEASES
1262
1264
  // bindActionByResource keyFn destructures { resource } from the first param, so pass {} when no options
1263
1265
  _boundGetPerspectiveState(instance, ...rest.length ? rest : [{}])
1264
1266
  );
1267
+ function unref(timer2) {
1268
+ const t = timer2;
1269
+ typeof t == "object" && t !== null && "unref" in t && typeof t.unref == "function" && t.unref();
1270
+ }
1265
1271
  function setCleanupTimeout(fn, delay) {
1266
- const timer2 = setTimeout(fn, delay), t = timer2;
1267
- return typeof t == "object" && t !== null && "unref" in t && typeof t.unref == "function" && t.unref(), timer2;
1272
+ const timer2 = setTimeout(fn, delay);
1273
+ return unref(timer2), timer2;
1274
+ }
1275
+ function setCleanupInterval(fn, delay) {
1276
+ const timer2 = setInterval(fn, delay);
1277
+ return unref(timer2), timer2;
1268
1278
  }
1269
1279
  const QUERY_STATE_CLEAR_DELAY = 1e3, QUERY_STORE_API_VERSION = "v2025-05-06", QUERY_STORE_DEFAULT_PERSPECTIVE = "drafts", setQueryError = (key, error) => (prev) => {
1270
1280
  const prevQuery = prev.queries[key];
@@ -1456,7 +1466,273 @@ const _resolveQuery = bindActionByResource(
1456
1466
  };
1457
1467
  return promise.then(releaseSubscriber, releaseSubscriber), promise;
1458
1468
  }
1459
- ), API_VERSION = "vX", PROJECT_API_VERSION = "2025-07-18", USERS_STATE_CLEAR_DELAY = 5e3, DEFAULT_USERS_BATCH_SIZE = 100, getUsersKey = (instance, {
1469
+ ), DEFAULT_STALE_TIME = 3e4, DEFAULT_GC_TIME = 3e5, definitions = /* @__PURE__ */ new Map(), inflight = /* @__PURE__ */ new Map(), gcTimers = /* @__PURE__ */ new Map(), intervalTimers = /* @__PURE__ */ new Map(), snapshotCache = /* @__PURE__ */ new WeakMap(), PENDING_SNAPSHOT = {
1470
+ status: "pending",
1471
+ data: void 0,
1472
+ error: void 0,
1473
+ isFetching: !1,
1474
+ dataUpdatedAt: void 0
1475
+ }, entryKey = (fetcherName, rawKey) => `${fetcherName}:${rawKey}`, computeTags = (def, data, params) => typeof def.tags == "function" ? def.tags(data, ...params) : def.tags ?? [], isUpdaterFn = (updater) => typeof updater == "function", applyUpdater = (updater, current) => isUpdaterFn(updater) ? updater(current) : updater, needsFetch = (entry, def) => entry.isFetching ? !1 : entry.status !== "success" ? !0 : entry.forcedStale || Date.now() - (entry.dataUpdatedAt ?? 0) >= (def.staleTime ?? DEFAULT_STALE_TIME), asTyped = (entry) => entry, toSnapshot = (entry) => {
1476
+ if (!entry) return PENDING_SNAPSHOT;
1477
+ const cached = snapshotCache.get(entry);
1478
+ if (cached) return cached;
1479
+ let snapshot;
1480
+ return entry.status === "success" ? snapshot = {
1481
+ status: "success",
1482
+ data: entry.data,
1483
+ error: entry.error,
1484
+ isFetching: entry.isFetching,
1485
+ dataUpdatedAt: entry.dataUpdatedAt
1486
+ } : entry.status === "error" ? snapshot = {
1487
+ status: "error",
1488
+ data: void 0,
1489
+ error: entry.error,
1490
+ isFetching: entry.isFetching,
1491
+ dataUpdatedAt: void 0
1492
+ } : snapshot = {
1493
+ status: "pending",
1494
+ data: void 0,
1495
+ error: void 0,
1496
+ isFetching: entry.isFetching,
1497
+ dataUpdatedAt: void 0
1498
+ }, snapshotCache.set(entry, snapshot), snapshot;
1499
+ }, cacheStore = {
1500
+ name: "FetcherCache",
1501
+ getInitialState: () => ({ entries: {} }),
1502
+ initialize: () => () => {
1503
+ for (const timer2 of gcTimers.values()) clearTimeout(timer2);
1504
+ for (const timer2 of intervalTimers.values()) clearInterval(timer2);
1505
+ for (const fetch of inflight.values()) fetch.sub.unsubscribe();
1506
+ gcTimers.clear(), intervalTimers.clear(), inflight.clear();
1507
+ }
1508
+ }, updateEntry = (state, key, actionName, updater) => {
1509
+ state.set(actionName, (prev) => {
1510
+ const next = updater(prev.entries[key]);
1511
+ if (next === prev.entries[key]) return prev;
1512
+ const entries = { ...prev.entries };
1513
+ return next === void 0 ? delete entries[key] : entries[key] = next, { entries };
1514
+ });
1515
+ }, baseEntry = (def, key, instance, params) => {
1516
+ const seeded = def.initialData?.(instance, ...params);
1517
+ return seeded ? {
1518
+ fetcherName: def.name,
1519
+ key,
1520
+ params,
1521
+ instance,
1522
+ status: "success",
1523
+ data: seeded.data,
1524
+ error: void 0,
1525
+ dataUpdatedAt: seeded.dataUpdatedAt,
1526
+ isFetching: !1,
1527
+ version: 0,
1528
+ forcedStale: !1,
1529
+ tags: computeTags(def, seeded.data, params),
1530
+ subscriptions: 0
1531
+ } : {
1532
+ fetcherName: def.name,
1533
+ key,
1534
+ params,
1535
+ instance,
1536
+ status: "pending",
1537
+ data: void 0,
1538
+ error: void 0,
1539
+ dataUpdatedAt: void 0,
1540
+ isFetching: !1,
1541
+ version: 0,
1542
+ forcedStale: !1,
1543
+ tags: [],
1544
+ subscriptions: 0
1545
+ };
1546
+ }, startFetch = (state, def, instance, params, force) => {
1547
+ const key = entryKey(def.name, def.getKey(instance, ...params)), existing = inflight.get(key);
1548
+ if (existing && !force) return existing.promise;
1549
+ existing && (existing.sub.unsubscribe(), inflight.delete(key)), updateEntry(state, key, "fetchStart", (prev) => ({
1550
+ ...prev ?? baseEntry(def, key, instance, params),
1551
+ isFetching: !0
1552
+ }));
1553
+ const startVersion = state.get().entries[key]?.version ?? 0;
1554
+ let resolve, reject;
1555
+ const promise = new Promise((res, rej) => {
1556
+ resolve = res, reject = rej;
1557
+ });
1558
+ existing && promise.then(existing.resolve, existing.reject);
1559
+ const sub = new Subscription();
1560
+ return inflight.set(key, { sub, promise, resolve, reject, startVersion }), sub.add(
1561
+ def.fetch(instance)(...params).subscribe({
1562
+ next: (data) => {
1563
+ const current = state.get().entries[key];
1564
+ if (current && current.version !== startVersion) {
1565
+ inflight.delete(key), current.isFetching && updateEntry(
1566
+ state,
1567
+ key,
1568
+ "fetchDiscard",
1569
+ (prev) => prev && { ...prev, isFetching: !1 }
1570
+ ), resolve(current.data), sub.unsubscribe();
1571
+ return;
1572
+ }
1573
+ updateEntry(state, key, "fetchSuccess", (prev) => ({
1574
+ ...prev ?? baseEntry(def, key, instance, params),
1575
+ status: "success",
1576
+ data,
1577
+ error: void 0,
1578
+ dataUpdatedAt: Date.now(),
1579
+ isFetching: !1,
1580
+ forcedStale: !1,
1581
+ tags: computeTags(def, data, params)
1582
+ })), resolve(data);
1583
+ },
1584
+ error: (error) => {
1585
+ updateEntry(state, key, "fetchError", (prev) => prev && (prev.status === "success" ? { ...prev, error, isFetching: !1 } : { ...prev, status: "error", error, isFetching: !1 })), inflight.delete(key), reject(error);
1586
+ },
1587
+ complete: () => {
1588
+ inflight.delete(key), state.get().entries[key]?.isFetching && updateEntry(state, key, "fetchSettle", (prev) => prev && { ...prev, isFetching: !1 });
1589
+ }
1590
+ })
1591
+ ), promise;
1592
+ }, detach = (promise) => {
1593
+ promise.catch(() => {
1594
+ });
1595
+ }, markStale = (state, key) => updateEntry(state, key, "markStale", (prev) => prev && { ...prev, forcedStale: !0 }), startInterval = (state, def, instance, params, key) => {
1596
+ if (!def.refetchInterval || intervalTimers.has(key)) return;
1597
+ const timer2 = setCleanupInterval(() => {
1598
+ if (typeof document < "u" && document.hidden) return;
1599
+ const entry = state.get().entries[key];
1600
+ entry && entry.subscriptions > 0 && detach(startFetch(state, def, instance, params, !0));
1601
+ }, def.refetchInterval);
1602
+ intervalTimers.set(key, timer2);
1603
+ }, scheduleGc = (state, def, key) => {
1604
+ if (gcTimers.has(key)) return;
1605
+ const entry = state.get().entries[key];
1606
+ if (!entry || entry.subscriptions > 0) return;
1607
+ const timer2 = setCleanupTimeout(() => {
1608
+ gcTimers.delete(key);
1609
+ const fetch = inflight.get(key);
1610
+ fetch && (fetch.sub.unsubscribe(), inflight.delete(key)), updateEntry(state, key, "gc", () => {
1611
+ });
1612
+ }, def.gcTime ?? DEFAULT_GC_TIME);
1613
+ gcTimers.set(key, timer2);
1614
+ }, invalidateByTags = bindActionGlobally(
1615
+ cacheStore,
1616
+ ({ state }, targets) => {
1617
+ const refetches = [];
1618
+ for (const [key, entry] of Object.entries(state.get().entries)) {
1619
+ if (!entry.tags.some(
1620
+ (tag) => targets.some(
1621
+ (target) => tag.type === target.type && (target.id === void 0 || tag.id === target.id)
1622
+ )
1623
+ ) || (markStale(state, key), entry.subscriptions <= 0)) continue;
1624
+ const def = definitions.get(entry.fetcherName);
1625
+ def && refetches.push(
1626
+ startFetch(state, def, entry.instance, entry.params, !0).catch(() => {
1627
+ })
1628
+ );
1629
+ }
1630
+ return Promise.all(refetches).then(() => {
1631
+ });
1632
+ }
1633
+ );
1634
+ function defineFetcher(definition) {
1635
+ const def = definition;
1636
+ definitions.set(definition.name, def);
1637
+ const getState = bindActionGlobally(
1638
+ cacheStore,
1639
+ createStateSourceAction({
1640
+ selector: ({ state, instance }, ...params) => {
1641
+ const key = entryKey(def.name, def.getKey(instance, ...params)), entry = state.entries[key];
1642
+ return toSnapshot(entry && asTyped(entry));
1643
+ },
1644
+ onSubscribe: ({ state, instance }, ...params) => {
1645
+ const key = entryKey(def.name, def.getKey(instance, ...params)), pendingGc = gcTimers.get(key);
1646
+ return pendingGc && (clearTimeout(pendingGc), gcTimers.delete(key)), updateEntry(state, key, "subscribe", (prev) => ({
1647
+ ...prev ?? baseEntry(def, key, instance, params),
1648
+ instance,
1649
+ subscriptions: (prev?.subscriptions ?? 0) + 1
1650
+ })), startInterval(state, def, instance, params, key), queueMicrotask(() => {
1651
+ const entry = state.get().entries[key];
1652
+ entry && entry.subscriptions > 0 && needsFetch(entry, def) && detach(startFetch(state, def, instance, params, !1));
1653
+ }), () => {
1654
+ updateEntry(
1655
+ state,
1656
+ key,
1657
+ "unsubscribe",
1658
+ (prev) => prev && { ...prev, subscriptions: Math.max(0, prev.subscriptions - 1) }
1659
+ );
1660
+ const entry = state.get().entries[key];
1661
+ if (!entry || entry.subscriptions > 0) return;
1662
+ const interval = intervalTimers.get(key);
1663
+ interval && (clearInterval(interval), intervalTimers.delete(key)), scheduleGc(state, def, key);
1664
+ };
1665
+ }
1666
+ })
1667
+ ), resolveState = (instance, ...params) => firstValueFrom(
1668
+ getState(instance, ...params).observable.pipe(
1669
+ filter(
1670
+ (snapshot) => snapshot.status !== "pending"
1671
+ ),
1672
+ map((snapshot) => {
1673
+ if (snapshot.status === "error") throw snapshot.error;
1674
+ return snapshot.data;
1675
+ })
1676
+ )
1677
+ ), invalidate = bindActionGlobally(
1678
+ cacheStore,
1679
+ ({ state, instance }, ...params) => {
1680
+ const key = entryKey(def.name, def.getKey(instance, ...params));
1681
+ markStale(state, key);
1682
+ const entry = state.get().entries[key];
1683
+ entry && entry.subscriptions > 0 && detach(startFetch(state, def, instance, params, !0));
1684
+ }
1685
+ ), invalidateAll = bindActionGlobally(cacheStore, ({ state }) => {
1686
+ const prefix = `${def.name}:`;
1687
+ for (const [key, entry] of Object.entries(state.get().entries))
1688
+ key.startsWith(prefix) && (markStale(state, key), entry.subscriptions > 0 && detach(startFetch(state, def, entry.instance, entry.params, !0)));
1689
+ }), refetch = bindActionGlobally(
1690
+ cacheStore,
1691
+ ({ state, instance }, ...params) => {
1692
+ const key = entryKey(def.name, def.getKey(instance, ...params)), promise = startFetch(state, def, instance, params, !0);
1693
+ return scheduleGc(state, def, key), promise;
1694
+ }
1695
+ ), setData = bindActionGlobally(
1696
+ cacheStore,
1697
+ ({ state, instance }, params, updater) => {
1698
+ const key = entryKey(def.name, def.getKey(instance, ...params));
1699
+ let previous;
1700
+ return updateEntry(state, key, "setData", (prev) => {
1701
+ previous = prev;
1702
+ const from = asTyped(prev ?? baseEntry(def, key, instance, params)), nextData = applyUpdater(updater, from.data);
1703
+ return {
1704
+ ...from,
1705
+ status: "success",
1706
+ data: nextData,
1707
+ dataUpdatedAt: from.dataUpdatedAt ?? Date.now(),
1708
+ version: from.version + 1,
1709
+ tags: computeTags(def, nextData, params)
1710
+ };
1711
+ }), scheduleGc(state, def, key), { undo: () => updateEntry(state, key, "undoSetData", () => previous) };
1712
+ }
1713
+ );
1714
+ return { getState, resolveState, invalidate, invalidateAll, refetch, setData };
1715
+ }
1716
+ function defineMutation(definition) {
1717
+ return (instance, input) => {
1718
+ const undos = [], write = (fetcher, params, updater) => {
1719
+ undos.push(fetcher.setData(instance, params, updater).undo);
1720
+ };
1721
+ return definition.onMutate?.(write, input), firstValueFrom(definition.mutationFn(instance)(input)).then(
1722
+ (result) => {
1723
+ definition.onSuccess?.(write, result, input);
1724
+ const targets = typeof definition.invalidates == "function" ? definition.invalidates(result, input) : definition.invalidates ?? [], invalidated = targets.length ? invalidateByTags(instance, targets) : Promise.resolve();
1725
+ return { data: result, invalidated };
1726
+ },
1727
+ (error) => {
1728
+ for (let i = undos.length - 1; i >= 0; i--) undos[i]();
1729
+ throw error;
1730
+ }
1731
+ );
1732
+ };
1733
+ }
1734
+ var version = "3.0.0-rc.1";
1735
+ const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`, API_VERSION = "vX", PROJECT_API_VERSION = "2025-07-18", USERS_STATE_CLEAR_DELAY = 5e3, DEFAULT_USERS_BATCH_SIZE = 100, getUsersKey = (instance, {
1460
1736
  resourceType,
1461
1737
  organizationId,
1462
1738
  batchSize = DEFAULT_USERS_BATCH_SIZE,
@@ -1516,6 +1792,7 @@ function createGroqSearchFilter(query) {
1516
1792
  export {
1517
1793
  API_VERSION,
1518
1794
  AuthStateType,
1795
+ CORE_SDK_VERSION,
1519
1796
  DEFAULT_API_VERSION$1 as DEFAULT_API_VERSION,
1520
1797
  PREVIEW_PROJECTION,
1521
1798
  PROJECT_API_VERSION,
@@ -1534,6 +1811,8 @@ export {
1534
1811
  createLoggedInAuthState,
1535
1812
  createLogger,
1536
1813
  createStateSourceAction,
1814
+ defineFetcher,
1815
+ defineMutation,
1537
1816
  defineStore,
1538
1817
  getActiveReleasesState,
1539
1818
  getAllReleasesState,
@@ -1549,7 +1828,6 @@ export {
1549
1828
  getCurrentUserState,
1550
1829
  getDashboardOrganizationId,
1551
1830
  getDefaultLocation,
1552
- getEnv,
1553
1831
  getIsInDashboardState,
1554
1832
  getLoginUrlState,
1555
1833
  getPerspectiveState,