@sanity/client 8.0.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +265 -0
  2. package/dist/{browserUpload-CQgx9YYo.js → browserUpload-2tz6Sdqp.js} +4 -3
  3. package/dist/browserUpload-2tz6Sdqp.js.map +1 -0
  4. package/dist/{browserUpload-icWlVP15.js → browserUpload-CwpNx7Vl.js} +4 -3
  5. package/dist/browserUpload-CwpNx7Vl.js.map +1 -0
  6. package/dist/{config-a8VajuEY.js → config-3wiPP-sZ.js} +2 -2
  7. package/dist/config-3wiPP-sZ.js.map +1 -0
  8. package/dist/csm.js +2 -2
  9. package/dist/csm.js.map +1 -1
  10. package/dist/index.d.ts +17 -11
  11. package/dist/index.js +610 -136
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.node.d.ts +918 -26
  14. package/dist/index.node.js +559 -66
  15. package/dist/index.node.js.map +1 -1
  16. package/dist/media-library.d.ts +1 -1
  17. package/dist/{request-CJxcN16k.js → request-BhMuKj0D.js} +10 -9
  18. package/dist/request-BhMuKj0D.js.map +1 -0
  19. package/dist/{request-k7VS_NnC.js → request-SnMg7nUX.js} +10 -9
  20. package/dist/request-SnMg7nUX.js.map +1 -0
  21. package/dist/{resolveEditInfo-sq7yF78q.js → resolveEditInfo-Cz-smq3a.js} +17 -3
  22. package/dist/resolveEditInfo-Cz-smq3a.js.map +1 -0
  23. package/dist/stega.js +1 -1
  24. package/dist/{stegaEncodeSourceMap-DkoIlutY.js → stegaEncodeSourceMap-DbM2fTN4.js} +8 -2
  25. package/dist/stegaEncodeSourceMap-DbM2fTN4.js.map +1 -0
  26. package/dist/{stegaEncodeSourceMap-B2fGArSf.js → stegaEncodeSourceMap-YR3NQ3iz.js} +2 -2
  27. package/dist/{stegaEncodeSourceMap-B2fGArSf.js.map → stegaEncodeSourceMap-YR3NQ3iz.js.map} +1 -1
  28. package/dist/{types-CUxZSgB2.d.ts → types-nJhm5Nyq.d.ts} +910 -24
  29. package/package.json +26 -11
  30. package/src/SanityClient.ts +39 -20
  31. package/src/assets/AssetsClient.ts +54 -5
  32. package/src/collaboration/CollaborationCommentsClient.ts +387 -0
  33. package/src/collaboration/comments.ts +313 -0
  34. package/src/collaboration/types.ts +252 -0
  35. package/src/csm/applySourceDocuments.ts +2 -4
  36. package/src/csm/draftUtils.ts +23 -4
  37. package/src/data/dataMethods.ts +9 -20
  38. package/src/data/eventsource.ts +71 -41
  39. package/src/data/listen.ts +20 -5
  40. package/src/data/live.ts +17 -9
  41. package/src/data/resolveEventSourceFetch.ts +9 -1
  42. package/src/defineCreateClient.ts +5 -1
  43. package/src/functions/FunctionsClient.ts +66 -0
  44. package/src/functions/invoke.ts +176 -0
  45. package/src/http/browserUpload.ts +1 -0
  46. package/src/http/errors.ts +2 -1
  47. package/src/http/request.ts +8 -14
  48. package/src/mediaLibrary/MediaLibraryVideoClient.ts +1 -1
  49. package/src/types.ts +420 -4
  50. package/src/validators.ts +1 -1
  51. package/src/warnings.ts +7 -1
  52. package/dist/browserUpload-CQgx9YYo.js.map +0 -1
  53. package/dist/browserUpload-icWlVP15.js.map +0 -1
  54. package/dist/config-a8VajuEY.js.map +0 -1
  55. package/dist/request-CJxcN16k.js.map +0 -1
  56. package/dist/request-k7VS_NnC.js.map +0 -1
  57. package/dist/resolveEditInfo-sq7yF78q.js.map +0 -1
  58. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +0 -1
@@ -1,5 +1,7 @@
1
1
  import { t as require_dist } from "./dist-C9ExSk2R.js";
2
- import { a as ServerError, c as isHttpError, i as CorsOriginError, l as isQueryParseError, o as formatQueryParseError, r as ClientError, t as defineRequester } from "./request-k7VS_NnC.js";
2
+ import { a as ServerError, c as isHttpError, i as CorsOriginError, l as isQueryParseError, o as formatQueryParseError, r as ClientError, t as defineRequester } from "./request-SnMg7nUX.js";
3
+ import { t as isRecord } from "./isRecord-Kfmt-nk-.js";
4
+ import { isTimeoutError } from "get-it";
3
5
  import { debug } from "get-it/middleware";
4
6
  import { Observable, catchError, concat, defer, finalize, isObservable, lastValueFrom, map, merge, mergeMap, of, share, tap, throwError, timer } from "rxjs";
5
7
  import { getDraftId, getPublishedId, getVersionFromId, getVersionId, isDraftId, isVersionId } from "@sanity/client/csm";
@@ -80,7 +82,7 @@ const createWarningPrinter = (message) => once((...args) => console.warn(message
80
82
  "Since you haven't set a value for `useCdn`, we will deliver content using our",
81
83
  "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
82
84
  "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
83
- ]), printCdnPreviewDraftsWarning = createWarningPrinter(["The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.", "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]), printPreviewDraftsDeprecationWarning = createWarningPrinter(["The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version"]), printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", `See ${generateHelpUrl("js-client-browser-token")} for more information and how to hide this warning.`]), printCredentialedTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token, but also provided `withCredentials: true`.", "This is no longer supported - only token will be used - remove `withCredentials: true`."]), printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", `See ${generateHelpUrl("js-client-api-version")}`]), printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]), printCreateVersionWithBaseIdWarning = createWarningPrinter(["You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead."]), printDeprecatedUriOptionWarning = createWarningPrinter(["The `uri` request option has been renamed to `url`.", "Please update your code to use `url` instead. Support for `uri` will be removed in a future version."]), printDeprecatedResourceConfigWarning = createWarningPrinter(["The `~experimental_resource` configuration property has been renamed to `resource`.", "Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."]), defaultConfig = {
85
+ ]), printCdnPreviewDraftsWarning = createWarningPrinter(["The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.", "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]), printPreviewDraftsDeprecationWarning = createWarningPrinter(["The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version"]), printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", `See ${generateHelpUrl("js-client-browser-token")} for more information and how to hide this warning.`]), printCredentialedTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token, but also provided `withCredentials: true`.", "This is no longer supported - only token will be used - remove `withCredentials: true`."]), printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", `See ${generateHelpUrl("js-client-api-version")}`]), printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]), printCreateVersionWithBaseIdWarning = createWarningPrinter(["You have called `createVersion()` with a defined `document`.", "If you are creating a version of a document that already exists, prefer providing `baseId` and `releaseId` instead."]), printDeprecatedUriOptionWarning = createWarningPrinter(["The `uri` request option has been renamed to `url`.", "Please update your code to use `url` instead. Support for `uri` will be removed in a future version."]), printDeprecatedResourceConfigWarning = createWarningPrinter(["The `~experimental_resource` configuration property has been renamed to `resource`.", "Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version."]), defaultConfig = {
84
86
  apiHost: "https://api.sanity.io",
85
87
  apiVersion: "1",
86
88
  useProjectHostname: !0,
@@ -133,11 +135,12 @@ const initConfig = (config, prevConfig) => {
133
135
  return projectBased ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
134
136
  };
135
137
  /**
136
- * @public
137
138
  * Thrown when the EventSource connection could not be established, or was rejected by the server.
138
139
  * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
139
140
  * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
140
141
  * stream with this class so consumers can react — check `status` for the rejection code.
142
+ *
143
+ * @public
141
144
  */
142
145
  var ConnectionFailedError = class extends Error {
143
146
  name = "ConnectionFailedError";
@@ -208,26 +211,30 @@ function connectEventSource(initEventSource, events) {
208
211
  */
209
212
  function connectWithESInstance(es, events) {
210
213
  return new Observable((observer) => {
211
- let emitOpen = events.includes("open"), emitReconnect = events.includes("reconnect");
214
+ let requestedEvents = new Set(events), isRequestedEvent = (type) => requestedEvents.has(type), emitOpen = isRequestedEvent("open");
212
215
  function onError(evt) {
213
216
  if ("data" in evt) {
214
217
  let [parseError, event] = parseEvent(evt);
215
- observer.error(parseError ? new MessageParseError("Unable to parse EventSource error message", { cause: parseError }) : new MessageError(event.data.message, event));
218
+ observer.error(parseError || !event ? new MessageParseError("Unable to parse EventSource error message", { cause: parseError }) : new MessageError(isRecord(event.data) && typeof event.data.message == "string" ? event.data.message : "", event));
216
219
  return;
217
220
  }
218
- let rawStatus = evt.code, status = typeof rawStatus == "number" ? rawStatus : void 0;
219
- if (status !== void 0) {
220
- observer.error(new ConnectionFailedError("EventSource connection failed", { status }));
221
+ if (evt.code !== void 0) {
222
+ observer.error(new ConnectionFailedError("EventSource connection failed", { status: evt.code }));
221
223
  return;
222
224
  }
223
- es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError("EventSource connection failed")) : emitReconnect && observer.next({ type: "reconnect" });
225
+ if (es.readyState === es.CLOSED) observer.error(new ConnectionFailedError("EventSource connection failed"));
226
+ else {
227
+ let type = "reconnect";
228
+ isRequestedEvent(type) && observer.next({ type });
229
+ }
224
230
  }
225
231
  function onOpen() {
226
- observer.next({ type: "open" });
232
+ let type = "open";
233
+ isRequestedEvent(type) && observer.next({ type });
227
234
  }
228
235
  function onMessage(message) {
229
236
  let [parseError, event] = parseEvent(message);
230
- if (parseError) {
237
+ if (parseError || !event) {
231
238
  observer.error(new MessageParseError("Unable to parse EventSource message", { cause: parseError }));
232
239
  return;
233
240
  }
@@ -237,10 +244,10 @@ function connectWithESInstance(es, events) {
237
244
  return;
238
245
  }
239
246
  if (message.type === "disconnect") {
240
- observer.error(new DisconnectError(`Server disconnected client: ${event.data?.reason || "unknown error"}`));
247
+ observer.error(new DisconnectError(`Server disconnected client: ${isRecord(event.data) && typeof event.data.reason == "string" && event.data.reason || "unknown error"}`));
241
248
  return;
242
249
  }
243
- observer.next({
250
+ isRequestedEvent(message.type) && observer.next({
244
251
  type: message.type,
245
252
  id: message.lastEventId,
246
253
  ...event.data ? { data: event.data } : {}
@@ -266,8 +273,16 @@ function parseEvent(message) {
266
273
  }
267
274
  }
268
275
  function extractErrorMessage(err, tag) {
269
- let error = err.error;
270
- return error ? isQueryParseError(error) ? formatQueryParseError(error, tag) : error.description ? error.description : typeof error == "string" ? error : JSON.stringify(error, null, 2) : err.message || "Unknown listener error";
276
+ let error = isRecord(err) ? err.error : void 0;
277
+ if (!error) {
278
+ let message = isRecord(err) ? err.message : void 0;
279
+ return typeof message == "string" && message || "Unknown listener error";
280
+ }
281
+ if (isRecord(error)) {
282
+ if (isQueryParseError(error)) return formatQueryParseError(error, tag);
283
+ if (typeof error.description == "string") return error.description;
284
+ }
285
+ return typeof error == "string" ? error : JSON.stringify(error, null, 2);
271
286
  }
272
287
  function isEmptyObject(data) {
273
288
  for (let _ in data) return !1;
@@ -711,7 +726,7 @@ function _fetchRequest(_stega, _params, options) {
711
726
  }
712
727
  /** @internal */
713
728
  function _fetchObservable(client, httpRequest, _stega, query, _params = {}, options = {}) {
714
- return _observe(options.signal, (signal) => _fetch(client, httpRequest, _stega, query, _params, {
729
+ return _observe(options.signal, (signal) => _fetch$1(client, httpRequest, _stega, query, _params, {
715
730
  ...options,
716
731
  signal
717
732
  }));
@@ -721,12 +736,12 @@ function _fetchObservable(client, httpRequest, _stega, query, _params = {}, opti
721
736
  *
722
737
  * @internal
723
738
  */
724
- function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
739
+ function _fetch$1(client, httpRequest, _stega, query, _params = {}, options = {}) {
725
740
  let { stega, params, mapResponse, reqOpts } = _fetchRequest(_stega, _params, options), request = _dataRequest(client, httpRequest, "query", {
726
741
  query,
727
742
  params
728
743
  }, reqOpts);
729
- return stega.enabled ? Promise.all([request, import("./stegaEncodeSourceMap-DkoIlutY.js")]).then(([res, { stegaEncodeSourceMap }]) => {
744
+ return stega.enabled ? Promise.all([request, import("./stegaEncodeSourceMap-DbM2fTN4.js")]).then(([res, { stegaEncodeSourceMap }]) => {
730
745
  let result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
731
746
  return mapResponse({
732
747
  ...res,
@@ -874,7 +889,7 @@ function _createVersionFromBaseObservable(client, httpRequest, publishedId, base
874
889
  }
875
890
  /** @internal */
876
891
  function _deleteObservable(client, httpRequest, selection, options) {
877
- return _observe(options?.signal, (signal) => _delete(client, httpRequest, selection, {
892
+ return _observe(options?.signal, (signal) => _delete$1(client, httpRequest, selection, {
878
893
  ...options,
879
894
  signal
880
895
  }));
@@ -969,8 +984,6 @@ function _mapDataResponse(res, isMutation, returnFirst, returnDocuments) {
969
984
  };
970
985
  }
971
986
  /**
972
- * Promise-based sibling of {@link _dataRequestObservable}.
973
- *
974
987
  * @internal
975
988
  */
976
989
  function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
@@ -981,7 +994,7 @@ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
981
994
  * @internal
982
995
  */
983
996
  function _createObservable(client, httpRequest, doc, op, options = {}) {
984
- return _observe(options.signal, (signal) => _create(client, httpRequest, doc, op, {
997
+ return _observe(options.signal, (signal) => _create$1(client, httpRequest, doc, op, {
985
998
  ...options,
986
999
  signal
987
1000
  }));
@@ -991,7 +1004,7 @@ function _createObservable(client, httpRequest, doc, op, options = {}) {
991
1004
  *
992
1005
  * @internal
993
1006
  */
994
- function _create(client, httpRequest, doc, op, options = {}) {
1007
+ function _create$1(client, httpRequest, doc, op, options = {}) {
995
1008
  let mutation = { [op]: doc }, opts = Object.assign({
996
1009
  returnFirst: !0,
997
1010
  returnDocuments: !0
@@ -1028,7 +1041,7 @@ function _mutate(client, httpRequest, mutations, options) {
1028
1041
  *
1029
1042
  * @internal
1030
1043
  */
1031
- function _delete(client, httpRequest, selection, options) {
1044
+ function _delete$1(client, httpRequest, selection, options) {
1032
1045
  return _dataRequest(client, httpRequest, "mutate", { mutations: [{ delete: getSelection(selection) }] }, options);
1033
1046
  }
1034
1047
  /**
@@ -1037,7 +1050,7 @@ function _delete(client, httpRequest, selection, options) {
1037
1050
  * @internal
1038
1051
  */
1039
1052
  function _createIfNotExists(client, httpRequest, doc, options) {
1040
- return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
1053
+ return requireDocumentId("createIfNotExists", doc), _create$1(client, httpRequest, doc, "createIfNotExists", options);
1041
1054
  }
1042
1055
  /**
1043
1056
  * Promise-based sibling of {@link _createOrReplaceObservable}.
@@ -1045,7 +1058,7 @@ function _createIfNotExists(client, httpRequest, doc, options) {
1045
1058
  * @internal
1046
1059
  */
1047
1060
  function _createOrReplace(client, httpRequest, doc, options) {
1048
- return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
1061
+ return requireDocumentId("createOrReplace", doc), _create$1(client, httpRequest, doc, "createOrReplace", options);
1049
1062
  }
1050
1063
  /**
1051
1064
  * Promise-based sibling of {@link _createVersionObservable}.
@@ -1195,7 +1208,7 @@ function _observe(userSignal, run) {
1195
1208
  * @internal
1196
1209
  */
1197
1210
  function _request(client, httpRequest, options) {
1198
- return httpRequest(_prepareRequest(client, options)).then((body) => body);
1211
+ return httpRequest(_prepareRequest(client, options), client.config().requestHandler).then((body) => body);
1199
1212
  }
1200
1213
  /**
1201
1214
  * Execute an HTTP request through the regular pipeline and resolve to the
@@ -1436,9 +1449,22 @@ var ObservableAgentsActionClient = class {
1436
1449
  }
1437
1450
  upload(assetType, body, options) {
1438
1451
  let observable = _upload(this.#client, this.#httpRequest, assetType, body, options);
1439
- return lastValueFrom(observable.pipe(filter((event) => event.type === "response"), map$1((event) => event.body.document)));
1452
+ return lastValueFrom(observable.pipe(filter((event) => event.type === "response"), map$1((event) => pluckUploadedAsset(event.body))));
1440
1453
  }
1441
1454
  };
1455
+ /**
1456
+ * Content Lake's upload endpoint responds with `{document: ...}`; the Media
1457
+ * Library upload endpoint responds with `{asset: ...}` instead (a
1458
+ * `sanity.asset` document, not a Content Lake asset document). Narrowing on
1459
+ * the response body itself - rather than on the client's `resource` config -
1460
+ * keeps this correct regardless of how the two are ever wired together.
1461
+ */
1462
+ function isMediaLibraryUploadBody(body) {
1463
+ return "asset" in body;
1464
+ }
1465
+ function pluckUploadedAsset(body) {
1466
+ return isMediaLibraryUploadBody(body) ? body.asset : body.document;
1467
+ }
1442
1468
  function _upload(client, _httpRequest, assetType, body, opts = {}) {
1443
1469
  validateAssetType(assetType);
1444
1470
  let meta = opts.extract || void 0;
@@ -1465,7 +1491,7 @@ function _upload(client, _httpRequest, assetType, body, opts = {}) {
1465
1491
  body
1466
1492
  };
1467
1493
  return typeof XMLHttpRequest < "u" ? defer(async () => {
1468
- let { uploadWithProgress } = await import("./browserUpload-icWlVP15.js"), req = _prepareRequest(client, { ...baseRequest });
1494
+ let { uploadWithProgress } = await import("./browserUpload-2tz6Sdqp.js"), req = _prepareRequest(client, { ...baseRequest });
1469
1495
  return uploadWithProgress({
1470
1496
  url: appendQuery(req.url, req.query),
1471
1497
  method: req.method ?? "POST",
@@ -1552,9 +1578,18 @@ function resolveEventSourceFetch(config, options = {}) {
1552
1578
  return credentials !== void 0 && (mergedInit.credentials = credentials), baseFetch(typeof url == "string" ? url : url.href, mergedInit);
1553
1579
  };
1554
1580
  }
1581
+ /**
1582
+ * The fetch the client's own transport resolves for this config: the
1583
+ * configured `resolveFetch` (honouring an explicit `proxy`) if present,
1584
+ * otherwise the global fetch. Shared by the EventSource connection and the
1585
+ * `/check/cors` probe so both resolve identically.
1586
+ *
1587
+ * @internal
1588
+ */
1555
1589
  function pickBaseFetch(config) {
1556
1590
  return config.resolveFetch ? config.resolveFetch(typeof config.proxy == "string" ? config.proxy : void 0) : globalThis.fetch.bind(globalThis);
1557
1591
  }
1592
+ /** @internal */
1558
1593
  const possibleOptions = [
1559
1594
  "includePreviousRevision",
1560
1595
  "includeResult",
@@ -1566,8 +1601,8 @@ const possibleOptions = [
1566
1601
  "tag"
1567
1602
  ], defaultOptions = { includeResult: !0 };
1568
1603
  /** @public */
1569
- function _listen(query, params, opts = {}) {
1570
- let config = this.config(), { url, token, withCredentials, requestTagPrefix, headers: configHeaders } = config, tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = {
1604
+ function _listen$1(query, params, opts = {}) {
1605
+ let { url, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = {
1571
1606
  ...defaults_default(opts, defaultOptions),
1572
1607
  tag
1573
1608
  }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({
@@ -1579,7 +1614,12 @@ function _listen(query, params, opts = {}) {
1579
1614
  }
1580
1615
  }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
1581
1616
  if (uri.length > 14800) return throwError(() => /* @__PURE__ */ Error("Query too large for listener"));
1582
- let listenFor = options.events ? options.events : ["mutation"], headers = {};
1617
+ let listenFor = options.events ? options.events : ["mutation"];
1618
+ return _connectListenEventSource(this, uri, listenFor);
1619
+ }
1620
+ /** @internal */
1621
+ function _connectListenEventSource(client, uri, listenFor) {
1622
+ let config = client.config(), { token, withCredentials, headers: configHeaders } = config, headers = {};
1583
1623
  token && (headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(headers, configHeaders);
1584
1624
  let initEventSource = () => new EventSource(uri, { fetch: resolveEventSourceFetch(config, {
1585
1625
  headers: Object.keys(headers).length ? headers : void 0,
@@ -1590,6 +1630,358 @@ function _listen(query, params, opts = {}) {
1590
1630
  ..."data" in event ? event.data : {}
1591
1631
  })));
1592
1632
  }
1633
+ /** @internal */
1634
+ const possibleRequestOptions = [
1635
+ "headers",
1636
+ "signal",
1637
+ "tag",
1638
+ "timeout",
1639
+ "token"
1640
+ ];
1641
+ function commentUrl(id) {
1642
+ if (!id) throw Error("Comment ID must be provided");
1643
+ return `/collaboration/comments/${encodeURIComponent(id)}`;
1644
+ }
1645
+ function resolveCommentResource(client) {
1646
+ let { resource, projectId, dataset } = client.config();
1647
+ if (resource) return resource;
1648
+ if (projectId && dataset) return {
1649
+ type: "dataset",
1650
+ id: `${projectId}.${dataset}`
1651
+ };
1652
+ throw Error("`resource` or `projectId` and `dataset` must be configured to use collaboration comments");
1653
+ }
1654
+ function resourceQuery(client) {
1655
+ let { collaboration } = client.config(), organizationId = collaboration?.organizationId;
1656
+ if (!organizationId) throw Error("`collaboration.organizationId` must be configured to use collaboration comments");
1657
+ let resource = resolveCommentResource(client);
1658
+ return {
1659
+ organizationId,
1660
+ resourceId: resource.id,
1661
+ resourceType: resource.type
1662
+ };
1663
+ }
1664
+ /** @internal */
1665
+ function _getTargetDocumentRef(client, documentId) {
1666
+ if (!documentId) throw Error("Document ID must be provided");
1667
+ let resource = resolveCommentResource(client);
1668
+ return `${resource.type}:${resource.id}:${getPublishedId(documentId)}`;
1669
+ }
1670
+ function write(client, httpRequest, method, url, body, options = {}) {
1671
+ return _requestObservable(client, httpRequest, {
1672
+ method,
1673
+ url,
1674
+ body,
1675
+ query: {
1676
+ ...resourceQuery(client),
1677
+ ...options.transactionId ? { transactionId: options.transactionId } : {}
1678
+ },
1679
+ ...pick(options, possibleRequestOptions)
1680
+ });
1681
+ }
1682
+ /**
1683
+ * `commentId` picks the written comment out of the results: a status update
1684
+ * cascades to the comment's replies, and the API leaves the results unordered.
1685
+ * Creates pass the requested `_id`, which is undefined when the API assigns
1686
+ * one, and always come back with a single result.
1687
+ */
1688
+ function writeDocument(commentId, ...args) {
1689
+ return write(...args).pipe(map$1(({ results }) => {
1690
+ let result = commentId ? results.find(({ id }) => id === commentId) : results[0];
1691
+ if (!result?.document) throw Error("Comment write did not return a comment document");
1692
+ return result.document;
1693
+ }));
1694
+ }
1695
+ function writeMutationResult(...args) {
1696
+ return write(...args).pipe(map$1(({ transactionId, results }) => ({
1697
+ transactionId,
1698
+ documentIds: results.map((result) => result.id),
1699
+ results
1700
+ })));
1701
+ }
1702
+ /** @internal */
1703
+ function _create(client, httpRequest, body, options) {
1704
+ return writeDocument(body._id, client, httpRequest, "POST", "/collaboration/comments", body, options);
1705
+ }
1706
+ /** @internal */
1707
+ function _update(client, httpRequest, id, body, options) {
1708
+ return writeDocument(id, client, httpRequest, "PATCH", commentUrl(id), body, options);
1709
+ }
1710
+ /** @internal */
1711
+ function _delete(client, httpRequest, id, options) {
1712
+ return writeMutationResult(client, httpRequest, "DELETE", commentUrl(id), void 0, options);
1713
+ }
1714
+ /** @internal */
1715
+ function _addReaction(client, httpRequest, id, shortName, options) {
1716
+ return writeDocument(id, client, httpRequest, "POST", `${commentUrl(id)}/reactions`, { shortName }, options);
1717
+ }
1718
+ /** @internal */
1719
+ function _removeReaction(client, httpRequest, id, shortName, options) {
1720
+ return writeDocument(id, client, httpRequest, "DELETE", `${commentUrl(id)}/reactions/${encodeURIComponent(shortName)}`, void 0, options);
1721
+ }
1722
+ /** @internal */
1723
+ function _fetch(client, httpRequest, query, params, options) {
1724
+ let search = resourceQuery(client);
1725
+ return _requestObservable(client, httpRequest, {
1726
+ ...encodeQueryString({
1727
+ query,
1728
+ params
1729
+ }).length < 11264 ? {
1730
+ method: "GET",
1731
+ url: `/collaboration/comments/query${encodeQueryString({
1732
+ query,
1733
+ params,
1734
+ options: search
1735
+ })}`
1736
+ } : {
1737
+ method: "POST",
1738
+ url: "/collaboration/comments/query",
1739
+ query: search,
1740
+ body: {
1741
+ query,
1742
+ params: params ?? {}
1743
+ }
1744
+ },
1745
+ ...pick(options || {}, possibleRequestOptions)
1746
+ }).pipe(map$1((response) => response.result));
1747
+ }
1748
+ /** @internal */
1749
+ function _listen(client, query, params, options) {
1750
+ let opts = options ?? {}, { requestTagPrefix } = client.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, listenOpts = pick({
1751
+ ...defaults_default(opts, defaultOptions),
1752
+ tag
1753
+ }, possibleOptions), qs = encodeQueryString({
1754
+ query,
1755
+ params,
1756
+ options: {
1757
+ ...listenOpts,
1758
+ ...resourceQuery(client)
1759
+ }
1760
+ }), uri = `${client.getUrl("/collaboration/comments/listen")}${qs}`;
1761
+ return uri.length > 14800 ? throwError(() => /* @__PURE__ */ Error("Query too large for listener")) : _connectListenEventSource(client, uri, opts.events ? opts.events : ["mutation"]);
1762
+ }
1763
+ /**
1764
+ * Comments on the configured organization resource.
1765
+ *
1766
+ * Requires `collaboration.organizationId`, plus either `resource` or `projectId` and `dataset`.
1767
+ *
1768
+ * @alpha
1769
+ */
1770
+ var ObservableCollaborationCommentsClient = class {
1771
+ #client;
1772
+ #httpRequest;
1773
+ constructor(client, httpRequest) {
1774
+ this.#client = client, this.#httpRequest = httpRequest;
1775
+ }
1776
+ /**
1777
+ * Create a comment or reply on the configured resource.
1778
+ *
1779
+ * A top-level comment requires `target`; a reply requires `parentCommentId` (never both).
1780
+ * Replies inherit `target`, `status`, and `threadId` from the parent comment.
1781
+ *
1782
+ * @param body - Comment to create
1783
+ * @param options - Optional request options
1784
+ * @returns The created comment
1785
+ */
1786
+ create(body, options) {
1787
+ return _create(this.#client, this.#httpRequest, body, options);
1788
+ }
1789
+ /**
1790
+ * Update an existing comment.
1791
+ *
1792
+ * Updating `status` cascades to the comment's replies.
1793
+ *
1794
+ * @param id - Comment document ID
1795
+ * @param body - Fields to update
1796
+ * @param options - Optional request options
1797
+ * @returns The updated comment
1798
+ */
1799
+ update(id, body, options) {
1800
+ return _update(this.#client, this.#httpRequest, id, body, options);
1801
+ }
1802
+ /**
1803
+ * Delete a comment and its replies.
1804
+ *
1805
+ * @param id - Comment document ID
1806
+ * @param options - Optional request options
1807
+ * @returns Mutation result, where `documentIds` covers the comment and every deleted reply
1808
+ */
1809
+ delete(id, options) {
1810
+ return _delete(this.#client, this.#httpRequest, id, options);
1811
+ }
1812
+ /**
1813
+ * Add the current user's reaction to a comment.
1814
+ *
1815
+ * @param id - Comment document ID
1816
+ * @param shortName - Emoji short name, for example `:+1:`
1817
+ * @param options - Optional request options
1818
+ * @returns The comment, with the reaction applied
1819
+ */
1820
+ addReaction(id, shortName, options) {
1821
+ return _addReaction(this.#client, this.#httpRequest, id, shortName, options);
1822
+ }
1823
+ /**
1824
+ * Remove the current user's reaction from a comment.
1825
+ *
1826
+ * @param id - Comment document ID
1827
+ * @param shortName - Emoji short name, for example `:+1:`
1828
+ * @param options - Optional request options
1829
+ * @returns The comment, with the reaction removed
1830
+ */
1831
+ removeReaction(id, shortName, options) {
1832
+ return _removeReaction(this.#client, this.#httpRequest, id, shortName, options);
1833
+ }
1834
+ /**
1835
+ * Build the global document reference used by `target.document._ref`, for use in
1836
+ * queries and listeners.
1837
+ *
1838
+ * The reference is built from the configured `resource` and the published ID of
1839
+ * the given document ID, since comment references always use published IDs.
1840
+ *
1841
+ * @example
1842
+ * ```ts
1843
+ * client.collaboration.comments.listen(
1844
+ * '*[_type == "sanity.comment" && target.document._ref == $ref]',
1845
+ * {ref: client.collaboration.comments.getTargetDocumentRef('doc-1')},
1846
+ * )
1847
+ * ```
1848
+ *
1849
+ * @param documentId - Document ID, in published, draft or version form
1850
+ * @returns Global document reference, of the form `resourceType:resourceId:documentId`
1851
+ */
1852
+ getTargetDocumentRef(documentId) {
1853
+ return _getTargetDocumentRef(this.#client, documentId);
1854
+ }
1855
+ /**
1856
+ * Fetch comments on the configured resource.
1857
+ *
1858
+ * Takes the same `query` and `params` as `client.fetch`, and switches from a
1859
+ * GET to a POST for queries too large for the request URL in the same way,
1860
+ * but queries the comments endpoint, which accepts none of the query options
1861
+ * `client.fetch` does (`perspective`, `useCdn`, `filterResponse`,
1862
+ * `resultSourceMap`, stega).
1863
+ *
1864
+ * The query runs against the organization store, which is not scoped to
1865
+ * comments, so filter on `_type == "sanity.comment"`.
1866
+ *
1867
+ * @param query - GROQ-query to perform
1868
+ * @param params - Optional query parameters
1869
+ * @param options - Optional request options
1870
+ */
1871
+ fetch(query, params, options) {
1872
+ return _fetch(this.#client, this.#httpRequest, query, params, options);
1873
+ }
1874
+ listen(query, params, options) {
1875
+ return _listen(this.#client, query, params, options);
1876
+ }
1877
+ }, CollaborationCommentsClient = class {
1878
+ #client;
1879
+ #httpRequest;
1880
+ constructor(client, httpRequest) {
1881
+ this.#client = client, this.#httpRequest = httpRequest;
1882
+ }
1883
+ /**
1884
+ * Create a comment or reply on the configured resource.
1885
+ *
1886
+ * A top-level comment requires `target`; a reply requires `parentCommentId` (never both).
1887
+ * Replies inherit `target`, `status`, and `threadId` from the parent comment.
1888
+ *
1889
+ * @param body - Comment to create
1890
+ * @param options - Optional request options
1891
+ * @returns The created comment
1892
+ */
1893
+ create(body, options) {
1894
+ return lastValueFrom(_create(this.#client, this.#httpRequest, body, options));
1895
+ }
1896
+ /**
1897
+ * Update an existing comment.
1898
+ *
1899
+ * Updating `status` cascades to the comment's replies.
1900
+ *
1901
+ * @param id - Comment document ID
1902
+ * @param body - Fields to update
1903
+ * @param options - Optional request options
1904
+ * @returns The updated comment
1905
+ */
1906
+ update(id, body, options) {
1907
+ return lastValueFrom(_update(this.#client, this.#httpRequest, id, body, options));
1908
+ }
1909
+ /**
1910
+ * Delete a comment and its replies.
1911
+ *
1912
+ * @param id - Comment document ID
1913
+ * @param options - Optional request options
1914
+ * @returns Mutation result, where `documentIds` covers the comment and every deleted reply
1915
+ */
1916
+ delete(id, options) {
1917
+ return lastValueFrom(_delete(this.#client, this.#httpRequest, id, options));
1918
+ }
1919
+ /**
1920
+ * Add the current user's reaction to a comment.
1921
+ *
1922
+ * @param id - Comment document ID
1923
+ * @param shortName - Emoji short name, for example `:+1:`
1924
+ * @param options - Optional request options
1925
+ * @returns The comment, with the reaction applied
1926
+ */
1927
+ addReaction(id, shortName, options) {
1928
+ return lastValueFrom(_addReaction(this.#client, this.#httpRequest, id, shortName, options));
1929
+ }
1930
+ /**
1931
+ * Remove the current user's reaction from a comment.
1932
+ *
1933
+ * @param id - Comment document ID
1934
+ * @param shortName - Emoji short name, for example `:+1:`
1935
+ * @param options - Optional request options
1936
+ * @returns The comment, with the reaction removed
1937
+ */
1938
+ removeReaction(id, shortName, options) {
1939
+ return lastValueFrom(_removeReaction(this.#client, this.#httpRequest, id, shortName, options));
1940
+ }
1941
+ /**
1942
+ * Build the global document reference used by `target.document._ref`, for use in
1943
+ * queries and listeners.
1944
+ *
1945
+ * The reference is built from the configured `resource` and the published ID of
1946
+ * the given document ID, since comment references always use published IDs.
1947
+ *
1948
+ * @example
1949
+ * ```ts
1950
+ * const comments = await client.collaboration.comments.fetch(
1951
+ * '*[_type == "sanity.comment" && target.document._ref == $ref]',
1952
+ * {ref: client.collaboration.comments.getTargetDocumentRef('doc-1')},
1953
+ * )
1954
+ * ```
1955
+ *
1956
+ * @param documentId - Document ID, in published, draft or version form
1957
+ * @returns Global document reference, of the form `resourceType:resourceId:documentId`
1958
+ */
1959
+ getTargetDocumentRef(documentId) {
1960
+ return _getTargetDocumentRef(this.#client, documentId);
1961
+ }
1962
+ /**
1963
+ * Fetch comments on the configured resource.
1964
+ *
1965
+ * Takes the same `query` and `params` as `client.fetch`, and switches from a
1966
+ * GET to a POST for queries too large for the request URL in the same way,
1967
+ * but queries the comments endpoint, which accepts none of the query options
1968
+ * `client.fetch` does (`perspective`, `useCdn`, `filterResponse`,
1969
+ * `resultSourceMap`, stega).
1970
+ *
1971
+ * The query runs against the organization store, which is not scoped to
1972
+ * comments, so filter on `_type == "sanity.comment"`.
1973
+ *
1974
+ * @param query - GROQ-query to perform
1975
+ * @param params - Optional query parameters
1976
+ * @param options - Optional request options
1977
+ */
1978
+ fetch(query, params, options) {
1979
+ return lastValueFrom(_fetch(this.#client, this.#httpRequest, query, params, options));
1980
+ }
1981
+ listen(query, params, options) {
1982
+ return _listen(this.#client, query, params, options);
1983
+ }
1984
+ };
1593
1985
  /**
1594
1986
  * A variant of share that takes a predicate function to determine which value to replay to new subscribers
1595
1987
  * @param configOrPredicate - Predicate function to determine which value to replay
@@ -1651,7 +2043,7 @@ var LiveClient = class {
1651
2043
  "welcome",
1652
2044
  "reconnect",
1653
2045
  "goaway"
1654
- ]), checkCors = checkCorsObservable(new URL(this.#client.getUrl("/check/cors", !1)), projectId, eventSourceWithCredentials), observable = events.pipe(reconnectOnConnectionFailure(), mergeMap((event) => event.type === "reconnect" ? checkCors.pipe(mergeMap(() => of(event))) : of(event)), catchError((err) => err instanceof CorsOriginError ? throwError(() => err) : checkCors.pipe(mergeMap(() => {
2046
+ ]), checkCors = checkCorsObservable(new URL(this.#client.getUrl("/check/cors", !1)), projectId, eventSourceWithCredentials, pickBaseFetch(config)), observable = events.pipe(reconnectOnConnectionFailure(), mergeMap((event) => event.type === "reconnect" ? checkCors.pipe(mergeMap(() => of(event))) : of(event)), catchError((err) => err instanceof CorsOriginError ? throwError(() => err) : checkCors.pipe(mergeMap(() => {
1655
2047
  throw err;
1656
2048
  }))), map$1((event) => {
1657
2049
  if (event.type === "message") {
@@ -1704,34 +2096,33 @@ var LiveClient = class {
1704
2096
  * In all of those cases the caller's original underlying error from the
1705
2097
  * EventSource is allowed to propagate unchanged.
1706
2098
  */
1707
- function checkCorsObservable(url, projectId, requireCredentials) {
2099
+ function checkCorsObservable(url, projectId, requireCredentials, fetcher) {
1708
2100
  return new Observable((observer) => {
1709
2101
  let controller = new AbortController(), { signal } = controller;
1710
- return fetch(url, {
2102
+ return fetcher(url.href, {
1711
2103
  method: "GET",
1712
- mode: "cors",
1713
2104
  credentials: "omit",
1714
2105
  signal
1715
2106
  }).then((response) => {
1716
- if (!(signal.aborted || !response.ok)) return response.json();
1717
- }).then((body) => {
1718
- if (!signal.aborted) {
1719
- if (requireCredentials && body?.result?.withCredentials === !1) {
1720
- observer.error(new CorsOriginError({
1721
- projectId,
1722
- credentials: !0
1723
- }));
1724
- return;
1725
- }
1726
- if (body?.result?.allowed === !1) {
1727
- observer.error(new CorsOriginError({
1728
- projectId,
1729
- credentials: requireCredentials
1730
- }));
1731
- return;
1732
- }
1733
- observer.next(), observer.complete();
2107
+ if (!(signal.aborted || !response.ok)) return response.text();
2108
+ }).then((text) => {
2109
+ if (signal.aborted) return;
2110
+ let parsed = text === void 0 ? void 0 : JSON.parse(text), result = isRecord(parsed) ? parsed.result : void 0;
2111
+ if (requireCredentials && isRecord(result) && result.withCredentials === !1) {
2112
+ observer.error(new CorsOriginError({
2113
+ projectId,
2114
+ credentials: !0
2115
+ }));
2116
+ return;
1734
2117
  }
2118
+ if (isRecord(result) && result.allowed === !1) {
2119
+ observer.error(new CorsOriginError({
2120
+ projectId,
2121
+ credentials: requireCredentials
2122
+ }));
2123
+ return;
2124
+ }
2125
+ observer.next(), observer.complete();
1735
2126
  }).catch(() => {
1736
2127
  signal.aborted || observer.closed || (observer.next(), observer.complete());
1737
2128
  }), () => controller.abort();
@@ -1901,8 +2292,106 @@ function _modify(client, httpRequest, method, name, options) {
1901
2292
  tag: null
1902
2293
  });
1903
2294
  }
2295
+ /** Function resource types in a blueprint are namespaced under this prefix. */
2296
+ const scopeHeaders = (config, request) => {
2297
+ let organizationId = request?.organizationId || config.organizationId;
2298
+ if (organizationId) return {
2299
+ "X-Sanity-Scope-Type": "organization",
2300
+ "X-Sanity-Scope-Id": organizationId
2301
+ };
2302
+ let { projectId } = config;
2303
+ if (!projectId) throw Error("`functions.invoke()` requires a `projectId` to be set in the client config, or an `organizationId` for a stack deployed at organization scope");
2304
+ return {
2305
+ "X-Sanity-Scope-Type": "project",
2306
+ "X-Sanity-Scope-Id": projectId
2307
+ };
2308
+ }, resolveStackId = (config, request) => {
2309
+ let stackId = request?.stackId || config.stackId;
2310
+ if (!stackId) throw Error("`functions.invoke()` requires a `stackId`, either in the client config or on the request. Function names are only unique within a stack.");
2311
+ return stackId;
2312
+ };
2313
+ /**
2314
+ * The invoke route is keyed by function id, but callers know functions by the
2315
+ * name declared in the blueprint. Names are unique within a stack, so the stack
2316
+ * both makes the name resolvable and confines the call to its own functions.
2317
+ *
2318
+ * @internal
2319
+ */
2320
+ function _resolveFunctionId(client, httpRequest, functionName, stackId, headers, request) {
2321
+ return _requestObservable(client, httpRequest, {
2322
+ method: "GET",
2323
+ url: `/blueprints/stacks/${stackId}`,
2324
+ headers,
2325
+ signal: request?.signal
2326
+ }).pipe(map((stack) => {
2327
+ let match = (stack?.resources || []).find((resource) => resource.type?.startsWith("sanity.function.") && resource.name === functionName);
2328
+ if (!match) throw Error(`Function "${functionName}" not found in stack "${stackId}"`);
2329
+ if (!match.externalId) throw Error(`Function "${functionName}" is declared in stack "${stackId}" but is not deployed`);
2330
+ if (match.type !== "sanity.function.pubsub") throw Error(`Function invocation is not supported for ${match.type}`);
2331
+ return match.externalId;
2332
+ }));
2333
+ }
1904
2334
  /** @internal */
1905
- var ObservableMediaLibraryVideoClient = class {
2335
+ function _invoke(client, httpRequest, functionName, request) {
2336
+ return defer(() => {
2337
+ let config = client.config(), headers = scopeHeaders(config, request);
2338
+ return _resolveFunctionId(client, httpRequest, functionName, resolveStackId(config, request), headers, request).pipe(mergeMap((functionId) => _requestObservable(client, httpRequest, {
2339
+ method: "POST",
2340
+ url: `/functions/${functionId}/invoke`,
2341
+ headers,
2342
+ body: { event: { data: request?.event?.data ?? {} } },
2343
+ timeout: request?.timeout,
2344
+ signal: request?.signal
2345
+ })));
2346
+ });
2347
+ }
2348
+ /** @public */
2349
+ var ObservableFunctionsClient = class {
2350
+ #client;
2351
+ #httpRequest;
2352
+ constructor(client, httpRequest) {
2353
+ this.#client = client, this.#httpRequest = httpRequest;
2354
+ }
2355
+ /**
2356
+ * Invoke a deployed function by its blueprint name.
2357
+ *
2358
+ * The name is resolved within the stack given by `stackId` on the request or
2359
+ * the client config. Passes the function's return value once it finishes.
2360
+ *
2361
+ * @param functionName - name of the function, as declared in the blueprint
2362
+ * @param request - payload and request options
2363
+ */
2364
+ invoke(functionName, request) {
2365
+ return _invoke(this.#client, this.#httpRequest, functionName, request);
2366
+ }
2367
+ }, FunctionsClient = class {
2368
+ #client;
2369
+ #httpRequest;
2370
+ constructor(client, httpRequest) {
2371
+ this.#client = client, this.#httpRequest = httpRequest;
2372
+ }
2373
+ /**
2374
+ * Invoke a deployed function by its blueprint name.
2375
+ *
2376
+ * The name is resolved within the stack given by `stackId` on the request or
2377
+ * the client config, which costs one extra request per call. Rejects if the
2378
+ * stack has no function by that name, or if the name resolves to anything
2379
+ * other than a `sanity.function.pubsub` function.
2380
+ *
2381
+ * The lookup is scoped to `projectId`, or to `organizationId` when one is set
2382
+ * for a stack deployed at organization scope.
2383
+ *
2384
+ * The request stays open until the function finishes, and resolves with its
2385
+ * return value, or `undefined` if it returns nothing. Long-running functions
2386
+ * may need an explicit `timeout`.
2387
+ *
2388
+ * @param functionName - name of the function, as declared in the blueprint
2389
+ * @param request - payload and request options
2390
+ */
2391
+ invoke(functionName, request) {
2392
+ return lastValueFrom(_invoke(this.#client, this.#httpRequest, functionName, request));
2393
+ }
2394
+ }, ObservableMediaLibraryVideoClient = class {
1906
2395
  #client;
1907
2396
  #httpRequest;
1908
2397
  constructor(client, httpRequest) {
@@ -2558,6 +3047,8 @@ var ObservableReleasesClient = class {
2558
3047
  projects;
2559
3048
  users;
2560
3049
  agent;
3050
+ collaboration;
3051
+ functions;
2561
3052
  releases;
2562
3053
  /**
2563
3054
  * Private properties
@@ -2567,9 +3058,9 @@ var ObservableReleasesClient = class {
2567
3058
  /**
2568
3059
  * Instance properties
2569
3060
  */
2570
- listen = _listen;
3061
+ listen = _listen$1;
2571
3062
  constructor(httpRequest, config = defaultConfig) {
2572
- this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest), this.agent = { action: new ObservableAgentsActionClient(this, this.#httpRequest) }, this.releases = new ObservableReleasesClient(this, this.#httpRequest);
3063
+ this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest), this.agent = { action: new ObservableAgentsActionClient(this, this.#httpRequest) }, this.collaboration = { comments: new ObservableCollaborationCommentsClient(this, this.#httpRequest) }, this.functions = new ObservableFunctionsClient(this, this.#httpRequest), this.releases = new ObservableReleasesClient(this, this.#httpRequest);
2573
3064
  }
2574
3065
  /**
2575
3066
  * Clone the client - returns a new instance
@@ -2792,6 +3283,8 @@ var ObservableReleasesClient = class {
2792
3283
  projects;
2793
3284
  users;
2794
3285
  agent;
3286
+ collaboration;
3287
+ functions;
2795
3288
  releases;
2796
3289
  /**
2797
3290
  * Observable version of the Sanity client, with the same configuration as the promise-based one
@@ -2805,9 +3298,9 @@ var ObservableReleasesClient = class {
2805
3298
  /**
2806
3299
  * Instance properties
2807
3300
  */
2808
- listen = _listen;
3301
+ listen = _listen$1;
2809
3302
  constructor(httpRequest, config = defaultConfig) {
2810
- this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new MediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.agent = { action: new AgentActionsClient(this, this.#httpRequest) }, this.releases = new ReleasesClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);
3303
+ this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.mediaLibrary = { video: new MediaLibraryVideoClient(this, this.#httpRequest) }, this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.agent = { action: new AgentActionsClient(this, this.#httpRequest) }, this.collaboration = { comments: new CollaborationCommentsClient(this, this.#httpRequest) }, this.functions = new FunctionsClient(this, this.#httpRequest), this.releases = new ReleasesClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);
2811
3304
  }
2812
3305
  /**
2813
3306
  * Clone the client - returns a new instance
@@ -2837,7 +3330,7 @@ var ObservableReleasesClient = class {
2837
3330
  });
2838
3331
  }
2839
3332
  fetch(query, params, options) {
2840
- return _fetch(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
3333
+ return _fetch$1(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
2841
3334
  }
2842
3335
  getDocument(id, options) {
2843
3336
  if (options?.includeAllVersions === !0) return _getDocument(this, this.#httpRequest, id, {
@@ -2875,7 +3368,7 @@ var ObservableReleasesClient = class {
2875
3368
  return _documentsExists(this, this.#httpRequest, ids, options);
2876
3369
  }
2877
3370
  create(document, options) {
2878
- return _create(this, this.#httpRequest, document, "create", options);
3371
+ return _create$1(this, this.#httpRequest, document, "create", options);
2879
3372
  }
2880
3373
  createIfNotExists(document, options) {
2881
3374
  return _createIfNotExists(this, this.#httpRequest, document, options);
@@ -2896,7 +3389,7 @@ var ObservableReleasesClient = class {
2896
3389
  return _createVersion(this, this.#httpRequest, documentVersion, versionPublishedId, options);
2897
3390
  }
2898
3391
  delete(selection, options) {
2899
- return _delete(this, this.#httpRequest, selection, options);
3392
+ return _delete$1(this, this.#httpRequest, selection, options);
2900
3393
  }
2901
3394
  /**
2902
3395
  * @public
@@ -3049,10 +3542,10 @@ function defineCreateClientExports(envOptions, ClassConstructor) {
3049
3542
  ignoreWarnings: config.ignoreWarnings,
3050
3543
  maxRetries: config.maxRetries,
3051
3544
  retryDelay: config.retryDelay
3052
- }), httpRequest = async (options) => (await clientRequesterPromise({
3545
+ }), performRequest = async (options) => (await clientRequesterPromise({
3053
3546
  redirect: "manual",
3054
3547
  ...options
3055
- })).body;
3548
+ })).body, httpRequest = (options, requestHandler) => requestHandler ? requestHandler(options, performRequest) : performRequest(options);
3056
3549
  return new ClassConstructor(httpRequest, {
3057
3550
  ...config,
3058
3551
  requester: clientRequester,
@@ -3069,7 +3562,7 @@ function defineDeprecatedCreateClient(createClient) {
3069
3562
  return printNoDefaultExport(), createClient(config);
3070
3563
  };
3071
3564
  }
3072
- var name = "@sanity/client", version = "8.0.0";
3565
+ var name = "@sanity/client", version = "8.2.0";
3073
3566
  const log = createDebug("sanity:client");
3074
3567
  function isNodeReadableStream(value) {
3075
3568
  return typeof value != "object" || !value || !("pipe" in value) ? !1 : typeof value.pipe == "function";
@@ -3126,6 +3619,6 @@ const middleware = [
3126
3619
  middleware,
3127
3620
  resolveFetch
3128
3621
  }, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);
3129
- export { BasePatch, BaseTransaction, ChannelError, ClientError, ConnectionFailedError, CorsOriginError, DisconnectError, EXPERIMENTAL_API_WARNING, MessageError, MessageParseError, ObservablePatch, ObservableSanityClient, ObservableTransaction, Patch, SanityClient, ServerError, Transaction, connectEventSource, createClient, deprecatedCreateClient as default, formatQueryParseError, isHttpError, isQueryParseError, requester, validateApiPerspective };
3622
+ export { BasePatch, BaseTransaction, ChannelError, ClientError, ConnectionFailedError, CorsOriginError, DisconnectError, EXPERIMENTAL_API_WARNING, MessageError, MessageParseError, ObservablePatch, ObservableSanityClient, ObservableTransaction, Patch, SanityClient, ServerError, Transaction, connectEventSource, createClient, deprecatedCreateClient as default, formatQueryParseError, isHttpError, isQueryParseError, isTimeoutError, requester, validateApiPerspective };
3130
3623
 
3131
3624
  //# sourceMappingURL=index.node.js.map