@sanity/client 7.26.2 → 8.0.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 (130) hide show
  1. package/README.md +5 -377
  2. package/dist/browserUpload-CQgx9YYo.js +86 -0
  3. package/dist/browserUpload-CQgx9YYo.js.map +1 -0
  4. package/dist/browserUpload-icWlVP15.js +86 -0
  5. package/dist/browserUpload-icWlVP15.js.map +1 -0
  6. package/dist/config-a8VajuEY.js +126 -0
  7. package/dist/config-a8VajuEY.js.map +1 -0
  8. package/dist/csm.d.ts +122 -335
  9. package/dist/csm.js +79 -91
  10. package/dist/csm.js.map +1 -1
  11. package/dist/dist-C9ExSk2R.js +73 -0
  12. package/dist/dist-C9ExSk2R.js.map +1 -0
  13. package/dist/dist-Z8cIRxoB.js +69 -0
  14. package/dist/dist-Z8cIRxoB.js.map +1 -0
  15. package/dist/index.d.ts +107 -6723
  16. package/dist/index.js +2822 -2847
  17. package/dist/index.js.map +1 -1
  18. package/dist/{index.d.cts → index.node.d.ts} +4291 -5328
  19. package/dist/index.node.js +3131 -0
  20. package/dist/index.node.js.map +1 -0
  21. package/dist/isRecord-Kfmt-nk-.js +7 -0
  22. package/dist/isRecord-Kfmt-nk-.js.map +1 -0
  23. package/dist/media-library.d.ts +9 -100
  24. package/dist/media-library.js +36 -14
  25. package/dist/media-library.js.map +1 -1
  26. package/dist/request-CJxcN16k.js +372 -0
  27. package/dist/request-CJxcN16k.js.map +1 -0
  28. package/dist/request-k7VS_NnC.js +354 -0
  29. package/dist/request-k7VS_NnC.js.map +1 -0
  30. package/dist/resolveEditInfo-sq7yF78q.js +325 -0
  31. package/dist/resolveEditInfo-sq7yF78q.js.map +1 -0
  32. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  33. package/dist/stega.d.ts +78 -7137
  34. package/dist/stega.js +27 -20
  35. package/dist/stega.js.map +1 -1
  36. package/dist/stegaClean-C18wLWau.js +21 -0
  37. package/dist/stegaClean-C18wLWau.js.map +1 -0
  38. package/dist/stegaEncodeSourceMap-B2fGArSf.js +163 -0
  39. package/dist/stegaEncodeSourceMap-B2fGArSf.js.map +1 -0
  40. package/dist/stegaEncodeSourceMap-DkoIlutY.js +367 -0
  41. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +1 -0
  42. package/dist/{index.browser.d.cts → types-CUxZSgB2.d.ts} +3956 -5256
  43. package/dist/types-CfGzbXrl.d.ts +108 -0
  44. package/package.json +64 -141
  45. package/src/SanityClient.ts +82 -117
  46. package/src/agent/actions/AgentActionsClient.ts +12 -12
  47. package/src/agent/actions/commonTypes.ts +2 -1
  48. package/src/agent/actions/generate.ts +26 -6
  49. package/src/agent/actions/patch.ts +27 -7
  50. package/src/agent/actions/prompt.ts +19 -5
  51. package/src/agent/actions/transform.ts +23 -5
  52. package/src/agent/actions/translate.ts +23 -5
  53. package/src/assets/AssetsClient.ts +71 -23
  54. package/src/csm/applySourceDocuments.ts +3 -1
  55. package/src/csm/createEditUrl.ts +1 -1
  56. package/src/csm/draftUtils.ts +0 -1
  57. package/src/csm/index.ts +2 -2
  58. package/src/csm/studioPath.ts +2 -1
  59. package/src/csm/types.ts +8 -2
  60. package/src/data/dataMethods.ts +801 -349
  61. package/src/data/eventsource.ts +13 -10
  62. package/src/data/listen.ts +18 -23
  63. package/src/data/live.ts +44 -27
  64. package/src/data/resolveEventSourceFetch.ts +96 -0
  65. package/src/datasets/DatasetsClient.ts +58 -41
  66. package/src/defineCreateClient.ts +35 -23
  67. package/src/http/browserMiddleware.ts +7 -1
  68. package/src/http/browserUpload.ts +162 -0
  69. package/src/http/errors.ts +60 -6
  70. package/src/http/nodeMiddleware.ts +94 -30
  71. package/src/http/request.ts +310 -87
  72. package/src/http/requestOptions.ts +131 -15
  73. package/src/{index.browser.ts → index.node.ts} +9 -4
  74. package/src/index.ts +4 -3
  75. package/src/mediaLibrary/MediaLibraryVideoClient.ts +26 -11
  76. package/src/projects/ProjectsClient.ts +18 -16
  77. package/src/releases/ReleasesClient.ts +38 -33
  78. package/src/stega/index.ts +1 -2
  79. package/src/stega/stegaEncodeSourceMap.ts +5 -0
  80. package/src/stega/types.ts +2 -2
  81. package/src/types.ts +148 -105
  82. package/src/users/UsersClient.ts +10 -14
  83. package/src/util/shareReplayLatest.ts +1 -1
  84. package/src/warnings.ts +6 -1
  85. package/dist/_chunks-cjs/config.cjs +0 -206
  86. package/dist/_chunks-cjs/config.cjs.map +0 -1
  87. package/dist/_chunks-cjs/isRecord.cjs +0 -6
  88. package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
  89. package/dist/_chunks-cjs/resolveEditInfo.cjs +0 -334
  90. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +0 -1
  91. package/dist/_chunks-cjs/stegaClean.cjs +0 -46
  92. package/dist/_chunks-cjs/stegaClean.cjs.map +0 -1
  93. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +0 -388
  94. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +0 -1
  95. package/dist/_chunks-es/config.js +0 -207
  96. package/dist/_chunks-es/config.js.map +0 -1
  97. package/dist/_chunks-es/isRecord.js +0 -7
  98. package/dist/_chunks-es/isRecord.js.map +0 -1
  99. package/dist/_chunks-es/resolveEditInfo.js +0 -335
  100. package/dist/_chunks-es/resolveEditInfo.js.map +0 -1
  101. package/dist/_chunks-es/stegaClean.js +0 -47
  102. package/dist/_chunks-es/stegaClean.js.map +0 -1
  103. package/dist/_chunks-es/stegaEncodeSourceMap.js +0 -389
  104. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  105. package/dist/csm.cjs +0 -99
  106. package/dist/csm.cjs.map +0 -1
  107. package/dist/csm.d.cts +0 -391
  108. package/dist/index.browser.cjs +0 -3106
  109. package/dist/index.browser.cjs.map +0 -1
  110. package/dist/index.browser.d.ts +0 -6802
  111. package/dist/index.browser.js +0 -3082
  112. package/dist/index.browser.js.map +0 -1
  113. package/dist/index.cjs +0 -2946
  114. package/dist/index.cjs.map +0 -1
  115. package/dist/media-library.cjs +0 -20
  116. package/dist/media-library.cjs.map +0 -1
  117. package/dist/media-library.d.cts +0 -117
  118. package/dist/stega.browser.cjs +0 -29
  119. package/dist/stega.browser.cjs.map +0 -1
  120. package/dist/stega.browser.d.cts +0 -7200
  121. package/dist/stega.browser.d.ts +0 -7200
  122. package/dist/stega.browser.js +0 -24
  123. package/dist/stega.browser.js.map +0 -1
  124. package/dist/stega.cjs +0 -29
  125. package/dist/stega.cjs.map +0 -1
  126. package/dist/stega.d.cts +0 -7200
  127. package/src/data/eventsourcePolyfill.ts +0 -7
  128. package/umd/.gitkeep +0 -1
  129. package/umd/sanityClient.js +0 -6543
  130. package/umd/sanityClient.min.js +0 -6
@@ -0,0 +1,3131 @@
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";
3
+ import { debug } from "get-it/middleware";
4
+ import { Observable, catchError, concat, defer, finalize, isObservable, lastValueFrom, map, merge, mergeMap, of, share, tap, throwError, timer } from "rxjs";
5
+ import { getDraftId, getPublishedId, getVersionFromId, getVersionId, isDraftId, isVersionId } from "@sanity/client/csm";
6
+ import { filter, finalize as finalize$1, map as map$1, mergeAll } from "rxjs/operators";
7
+ import { EventSource } from "eventsource";
8
+ import { customAlphabet } from "nanoid";
9
+ import { Readable } from "node:stream";
10
+ import { createNodeFetch } from "get-it/node";
11
+ import { createDebug } from "obug";
12
+ function generateHelpUrl(slug) {
13
+ return "https://www.sanity.io/help/" + slug;
14
+ }
15
+ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = [
16
+ "before",
17
+ "after",
18
+ "replace"
19
+ ], dataset = (name) => {
20
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) throw Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
21
+ }, projectId = (id) => {
22
+ if (!/^[-a-z0-9]+$/i.test(id)) throw Error("`projectId` can only contain only a-z, 0-9 and dashes");
23
+ }, validateAssetType = (type) => {
24
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) throw Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
25
+ }, validateObject = (op, val) => {
26
+ if (typeof val != "object" || !val || Array.isArray(val)) throw Error(`${op}() takes an object of properties`);
27
+ }, validateDocumentId = (op, id) => {
28
+ if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) throw Error(`${op}(): "${id}" is not a valid document ID`);
29
+ }, requireDocumentId = (op, doc) => {
30
+ if (!doc._id) throw Error(`${op}() requires that the document contains an ID ("_id" property)`);
31
+ validateDocumentId(op, doc._id);
32
+ }, validateDocumentType = (op, type) => {
33
+ if (typeof type != "string") throw Error(`\`${op}()\`: \`${type}\` is not a valid document type`);
34
+ }, requireDocumentType = (op, doc) => {
35
+ if (!doc._type) throw Error(`\`${op}()\` requires that the document contains a type (\`_type\` property)`);
36
+ validateDocumentType(op, doc._type);
37
+ }, validateVersionIdMatch = (builtVersionId, document) => {
38
+ if (document._id && document._id !== builtVersionId) throw Error(`The provided document ID (\`${document._id}\`) does not match the generated version ID (\`${builtVersionId}\`)`);
39
+ }, validateInsert = (at, selector, items) => {
40
+ let signature = "insert(at, selector, items)";
41
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
42
+ let valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
43
+ throw Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
44
+ }
45
+ if (typeof selector != "string") throw Error(`${signature} takes a "selector"-argument which must be a string`);
46
+ if (!Array.isArray(items)) throw Error(`${signature} takes an "items"-argument which must be an array`);
47
+ }, hasDataset = (config) => {
48
+ if (config.dataset) return config.dataset;
49
+ let resource = config.resource;
50
+ if (resource && resource.type === "dataset") {
51
+ let segments = resource.id.split(".");
52
+ if (segments.length !== 2) throw Error("Dataset resource ID must be in the format \"project.dataset\"");
53
+ return segments[1];
54
+ }
55
+ throw Error("`dataset` must be provided to perform queries");
56
+ }, requestTag = (tag) => {
57
+ if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) throw Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
58
+ return tag;
59
+ }, resourceConfig = (config) => {
60
+ let resource = config.resource;
61
+ if (!resource) throw Error("`resource` must be provided to perform resource queries");
62
+ let { type, id } = resource;
63
+ switch (type) {
64
+ case "dataset":
65
+ if (id.split(".").length !== 2) throw Error("Dataset resource ID must be in the format \"project.dataset\"");
66
+ return;
67
+ case "dashboard":
68
+ case "media-library":
69
+ case "canvas": return;
70
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
71
+ }
72
+ }, resourceGuard = (service, config) => {
73
+ if (config.resource) throw Error(`\`${service}\` does not support resource-based operations`);
74
+ }, EXPERIMENTAL_API_WARNING = "This is an experimental API version";
75
+ function once(fn) {
76
+ let didCall = !1, returnValue;
77
+ return (...args) => didCall ? returnValue : (returnValue = fn(...args), didCall = !0, returnValue);
78
+ }
79
+ const createWarningPrinter = (message) => once((...args) => console.warn(message.join(" "), ...args)), printCdnAndWithCredentialsWarning = createWarningPrinter(["Because you set `withCredentials` to true, we will override your `useCdn`", "setting to be false since (cookie-based) credentials are never set on the CDN"]), printCdnWarning = createWarningPrinter([
80
+ "Since you haven't set a value for `useCdn`, we will deliver content using our",
81
+ "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
82
+ "`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 = {
84
+ apiHost: "https://api.sanity.io",
85
+ apiVersion: "1",
86
+ useProjectHostname: !0,
87
+ stega: { enabled: !1 }
88
+ }, LOCALHOSTS = [
89
+ "localhost",
90
+ "127.0.0.1",
91
+ "0.0.0.0"
92
+ ], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
93
+ function validateApiVersion(apiVersion) {
94
+ if (apiVersion === "1" || apiVersion === "X") return;
95
+ let apiDate = new Date(apiVersion);
96
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0)) throw Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
97
+ }
98
+ /**
99
+ * @internal - it may have breaking changes in any release
100
+ */
101
+ function validateApiPerspective(perspective) {
102
+ if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes("raw")) throw TypeError("Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives");
103
+ }
104
+ const initConfig = (config, prevConfig) => {
105
+ let specifiedConfig = {
106
+ ...prevConfig,
107
+ ...config,
108
+ stega: {
109
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
110
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
111
+ }
112
+ };
113
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
114
+ let newConfig = {
115
+ ...defaultConfig,
116
+ ...specifiedConfig
117
+ };
118
+ newConfig["~experimental_resource"] && !newConfig.resource && (printDeprecatedResourceConfigWarning(), newConfig.resource = newConfig["~experimental_resource"]);
119
+ let resourceConfig$1 = newConfig.resource, projectBased = newConfig.useProjectHostname && !resourceConfig$1;
120
+ if (typeof Promise > "u") {
121
+ let helpUrl = generateHelpUrl("js-client-promise-polyfill");
122
+ throw Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
123
+ }
124
+ if (projectBased && !newConfig.projectId) throw Error("Configuration must contain `projectId`");
125
+ if (resourceConfig$1 && resourceConfig(newConfig), newConfig.perspective !== void 0 && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig) throw Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");
126
+ if ("encodeSourceMapAtPath" in newConfig) throw Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");
127
+ if (typeof newConfig.stega.enabled != "boolean") throw Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
128
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0) throw Error("stega.studioUrl must be defined when stega.enabled is true");
129
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function") throw Error(`stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`);
130
+ let isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname), hasToken = !!newConfig.token;
131
+ newConfig.withCredentials && hasToken && (printCredentialedTokenWarning(), newConfig.withCredentials = !1), isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : newConfig.useCdn === void 0 && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
132
+ let hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? "apicdn.sanity.io" : host;
133
+ 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
+ };
135
+ /**
136
+ * @public
137
+ * Thrown when the EventSource connection could not be established, or was rejected by the server.
138
+ * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
139
+ * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
140
+ * stream with this class so consumers can react — check `status` for the rejection code.
141
+ */
142
+ var ConnectionFailedError = class extends Error {
143
+ name = "ConnectionFailedError";
144
+ /**
145
+ * HTTP status code of the rejected connection attempt, if known.
146
+ * Only set when the EventSource implementation exposes it — the `eventsource`
147
+ * package used by the client does (as `code` on its error events), while
148
+ * native EventSource implementations (browser and Node.js) do not.
149
+ */
150
+ status;
151
+ constructor(message, options = {}) {
152
+ let { status, ...errorOptions } = options;
153
+ super(message, errorOptions), this.status = status;
154
+ }
155
+ }, DisconnectError = class extends Error {
156
+ name = "DisconnectError";
157
+ reason;
158
+ constructor(message, reason, options = {}) {
159
+ super(message, options), this.reason = reason;
160
+ }
161
+ }, ChannelError = class extends Error {
162
+ name = "ChannelError";
163
+ data;
164
+ constructor(message, data) {
165
+ super(message), this.data = data;
166
+ }
167
+ }, MessageError = class extends Error {
168
+ name = "MessageError";
169
+ data;
170
+ constructor(message, data, options = {}) {
171
+ super(message, options), this.data = data;
172
+ }
173
+ }, MessageParseError = class extends Error {
174
+ name = "MessageParseError";
175
+ };
176
+ const REQUIRED_EVENTS = ["channelError", "disconnect"];
177
+ /**
178
+ * Sanity API specific EventSource handler shared between the listen and live APIs
179
+ *
180
+ * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance
181
+ * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)
182
+ * via the passed `initEventSource` function which must return an EventSource instance.
183
+ *
184
+ * Possible errors to be thrown on the returned observable are:
185
+ * - {@link MessageError}
186
+ * - {@link MessageParseError}
187
+ * - {@link ChannelError}
188
+ * - {@link DisconnectError}
189
+ * - {@link ConnectionFailedError}
190
+ *
191
+ * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance
192
+ * @param events - an array of named events from the API to listen for.
193
+ *
194
+ * @internal
195
+ */
196
+ function connectEventSource(initEventSource, events) {
197
+ return defer(() => {
198
+ let es = initEventSource();
199
+ return isObservable(es) ? es : of(es);
200
+ }).pipe(mergeMap((es) => connectWithESInstance(es, events)));
201
+ }
202
+ /**
203
+ * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for
204
+ * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.
205
+ *
206
+ * @param es - The EventSource instance
207
+ * @param events - List of event names to listen for
208
+ */
209
+ function connectWithESInstance(es, events) {
210
+ return new Observable((observer) => {
211
+ let emitOpen = events.includes("open"), emitReconnect = events.includes("reconnect");
212
+ function onError(evt) {
213
+ if ("data" in evt) {
214
+ 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));
216
+ return;
217
+ }
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
+ return;
222
+ }
223
+ es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError("EventSource connection failed")) : emitReconnect && observer.next({ type: "reconnect" });
224
+ }
225
+ function onOpen() {
226
+ observer.next({ type: "open" });
227
+ }
228
+ function onMessage(message) {
229
+ let [parseError, event] = parseEvent(message);
230
+ if (parseError) {
231
+ observer.error(new MessageParseError("Unable to parse EventSource message", { cause: parseError }));
232
+ return;
233
+ }
234
+ if (message.type === "channelError") {
235
+ let tag = new URL(es.url).searchParams.get("tag");
236
+ observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data));
237
+ return;
238
+ }
239
+ if (message.type === "disconnect") {
240
+ observer.error(new DisconnectError(`Server disconnected client: ${event.data?.reason || "unknown error"}`));
241
+ return;
242
+ }
243
+ observer.next({
244
+ type: message.type,
245
+ id: message.lastEventId,
246
+ ...event.data ? { data: event.data } : {}
247
+ });
248
+ }
249
+ es.addEventListener("error", onError), emitOpen && es.addEventListener("open", onOpen);
250
+ let cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== "error" && type !== "open" && type !== "reconnect");
251
+ return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {
252
+ es.removeEventListener("error", onError), emitOpen && es.removeEventListener("open", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();
253
+ };
254
+ });
255
+ }
256
+ function parseEvent(message) {
257
+ try {
258
+ let data = typeof message.data == "string" && JSON.parse(message.data);
259
+ return [null, {
260
+ type: message.type,
261
+ id: message.lastEventId,
262
+ ...isEmptyObject(data) ? {} : { data }
263
+ }];
264
+ } catch (err) {
265
+ return [err, null];
266
+ }
267
+ }
268
+ 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";
271
+ }
272
+ function isEmptyObject(data) {
273
+ for (let _ in data) return !1;
274
+ return !0;
275
+ }
276
+ function getSelection(sel) {
277
+ if (typeof sel == "string") return { id: sel };
278
+ if (Array.isArray(sel)) return {
279
+ query: "*[_id in $ids]",
280
+ params: { ids: sel }
281
+ };
282
+ if (typeof sel == "object" && sel && "query" in sel && typeof sel.query == "string") return "params" in sel && typeof sel.params == "object" && sel.params !== null ? {
283
+ query: sel.query,
284
+ params: sel.params
285
+ } : { query: sel.query };
286
+ let selectionOpts = [
287
+ "* Document ID (<docId>)",
288
+ "* Array of document IDs",
289
+ "* Object containing `query`"
290
+ ].join("\n");
291
+ throw Error(`Unknown selection - must be one of:\n\n${selectionOpts}`);
292
+ }
293
+ /** @internal */
294
+ var BasePatch = class {
295
+ selection;
296
+ operations;
297
+ constructor(selection, operations = {}) {
298
+ this.selection = selection, this.operations = operations;
299
+ }
300
+ /**
301
+ * Sets the given attributes to the document. Does NOT merge objects.
302
+ * The operation is added to the current patch, ready to be commited by `commit()`
303
+ *
304
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
305
+ */
306
+ set(attrs) {
307
+ return this._assign("set", attrs);
308
+ }
309
+ /**
310
+ * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
311
+ * The operation is added to the current patch, ready to be commited by `commit()`
312
+ *
313
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
314
+ */
315
+ setIfMissing(attrs) {
316
+ return this._assign("setIfMissing", attrs);
317
+ }
318
+ /**
319
+ * Performs a "diff-match-patch" operation on the string attributes provided.
320
+ * The operation is added to the current patch, ready to be commited by `commit()`
321
+ *
322
+ * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
323
+ */
324
+ diffMatchPatch(attrs) {
325
+ return validateObject("diffMatchPatch", attrs), this._assign("diffMatchPatch", attrs);
326
+ }
327
+ /**
328
+ * Unsets the attribute paths provided.
329
+ * The operation is added to the current patch, ready to be commited by `commit()`
330
+ *
331
+ * @param attrs - Attribute paths to unset.
332
+ */
333
+ unset(attrs) {
334
+ if (!Array.isArray(attrs)) throw Error("unset(attrs) takes an array of attributes to unset, non-array given");
335
+ return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;
336
+ }
337
+ /**
338
+ * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
339
+ *
340
+ * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
341
+ */
342
+ inc(attrs) {
343
+ return this._assign("inc", attrs);
344
+ }
345
+ /**
346
+ * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
347
+ *
348
+ * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
349
+ */
350
+ dec(attrs) {
351
+ return this._assign("dec", attrs);
352
+ }
353
+ /**
354
+ * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
355
+ *
356
+ * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
357
+ * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
358
+ * @param items - Array of items to insert/replace
359
+ */
360
+ insert(at, selector, items) {
361
+ return validateInsert(at, selector, items), this._assign("insert", {
362
+ [at]: selector,
363
+ items
364
+ });
365
+ }
366
+ /**
367
+ * Append the given items to the array at the given JSONPath
368
+ *
369
+ * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
370
+ * @param items - Array of items to append to the array
371
+ */
372
+ append(selector, items) {
373
+ return this.insert("after", `${selector}[-1]`, items);
374
+ }
375
+ /**
376
+ * Prepend the given items to the array at the given JSONPath
377
+ *
378
+ * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
379
+ * @param items - Array of items to prepend to the array
380
+ */
381
+ prepend(selector, items) {
382
+ return this.insert("before", `${selector}[0]`, items);
383
+ }
384
+ /**
385
+ * Change the contents of an array by removing existing elements and/or adding new elements.
386
+ *
387
+ * @param selector - Attribute or JSONPath expression for array
388
+ * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
389
+ * @param deleteCount - An integer indicating the number of old array elements to remove.
390
+ * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
391
+ */
392
+ splice(selector, start, deleteCount, items) {
393
+ let delAll = deleteCount === void 0 || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), rangeSelector = `${selector}[${startIndex}:${startIndex < 0 && delCount >= 0 ? "" : delCount}]`;
394
+ return this.insert("replace", rangeSelector, items || []);
395
+ }
396
+ /**
397
+ * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
398
+ *
399
+ * @param rev - Revision to lock the patch to
400
+ */
401
+ ifRevisionId(rev) {
402
+ return this.operations.ifRevisionID = rev, this;
403
+ }
404
+ /**
405
+ * Return a plain JSON representation of the patch
406
+ */
407
+ serialize() {
408
+ return {
409
+ ...getSelection(this.selection),
410
+ ...this.operations
411
+ };
412
+ }
413
+ /**
414
+ * Return a plain JSON representation of the patch
415
+ */
416
+ toJSON() {
417
+ return this.serialize();
418
+ }
419
+ /**
420
+ * Clears the patch of all operations
421
+ */
422
+ reset() {
423
+ return this.operations = {}, this;
424
+ }
425
+ _assign(op, props, merge = !0) {
426
+ return validateObject(op, props), this.operations = Object.assign({}, this.operations, { [op]: Object.assign({}, merge && this.operations[op] || {}, props) }), this;
427
+ }
428
+ _set(op, props) {
429
+ return this._assign(op, props, !1);
430
+ }
431
+ }, ObservablePatch = class ObservablePatch extends BasePatch {
432
+ #client;
433
+ constructor(selection, operations, client) {
434
+ super(selection, operations), this.#client = client;
435
+ }
436
+ /**
437
+ * Clones the patch
438
+ */
439
+ clone() {
440
+ return new ObservablePatch(this.selection, { ...this.operations }, this.#client);
441
+ }
442
+ commit(options) {
443
+ if (!this.#client) throw Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
444
+ let returnFirst = typeof this.selection == "string", opts = Object.assign({
445
+ returnFirst,
446
+ returnDocuments: !0
447
+ }, options);
448
+ return this.#client.mutate({ patch: this.serialize() }, opts);
449
+ }
450
+ }, Patch = class Patch extends BasePatch {
451
+ #client;
452
+ constructor(selection, operations, client) {
453
+ super(selection, operations), this.#client = client;
454
+ }
455
+ /**
456
+ * Clones the patch
457
+ */
458
+ clone() {
459
+ return new Patch(this.selection, { ...this.operations }, this.#client);
460
+ }
461
+ commit(options) {
462
+ if (!this.#client) throw Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
463
+ let returnFirst = typeof this.selection == "string", opts = Object.assign({
464
+ returnFirst,
465
+ returnDocuments: !0
466
+ }, options);
467
+ return this.#client.mutate({ patch: this.serialize() }, opts);
468
+ }
469
+ };
470
+ const defaultMutateOptions = { returnDocuments: !1 };
471
+ /** @internal */
472
+ var BaseTransaction = class {
473
+ operations;
474
+ trxId;
475
+ constructor(operations = [], transactionId) {
476
+ this.operations = operations, this.trxId = transactionId;
477
+ }
478
+ /**
479
+ * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
480
+ * The operation is added to the current transaction, ready to be commited by `commit()`
481
+ *
482
+ * @param doc - Document to create. Requires a `_type` property.
483
+ */
484
+ create(doc) {
485
+ return validateObject("create", doc), this._add({ create: doc });
486
+ }
487
+ /**
488
+ * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
489
+ * The operation is added to the current transaction, ready to be commited by `commit()`
490
+ *
491
+ * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
492
+ */
493
+ createIfNotExists(doc) {
494
+ let op = "createIfNotExists";
495
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
496
+ }
497
+ /**
498
+ * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
499
+ * The operation is added to the current transaction, ready to be commited by `commit()`
500
+ *
501
+ * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
502
+ */
503
+ createOrReplace(doc) {
504
+ let op = "createOrReplace";
505
+ return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
506
+ }
507
+ /**
508
+ * Deletes the document with the given document ID
509
+ * The operation is added to the current transaction, ready to be commited by `commit()`
510
+ *
511
+ * @param documentId - Document ID to delete
512
+ */
513
+ delete(documentId) {
514
+ return validateDocumentId("delete", documentId), this._add({ delete: { id: documentId } });
515
+ }
516
+ transactionId(id) {
517
+ return id ? (this.trxId = id, this) : this.trxId;
518
+ }
519
+ /**
520
+ * Return a plain JSON representation of the transaction
521
+ */
522
+ serialize() {
523
+ return [...this.operations];
524
+ }
525
+ /**
526
+ * Return a plain JSON representation of the transaction
527
+ */
528
+ toJSON() {
529
+ return this.serialize();
530
+ }
531
+ /**
532
+ * Clears the transaction of all operations
533
+ */
534
+ reset() {
535
+ return this.operations = [], this;
536
+ }
537
+ _add(mut) {
538
+ return this.operations.push(mut), this;
539
+ }
540
+ }, Transaction = class Transaction extends BaseTransaction {
541
+ #client;
542
+ constructor(operations, client, transactionId) {
543
+ super(operations, transactionId), this.#client = client;
544
+ }
545
+ /**
546
+ * Clones the transaction
547
+ */
548
+ clone() {
549
+ return new Transaction([...this.operations], this.#client, this.trxId);
550
+ }
551
+ commit(options) {
552
+ if (!this.#client) throw Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
553
+ return this.#client.mutate(this.serialize(), Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {}));
554
+ }
555
+ patch(patchOrDocumentId, patchOps) {
556
+ let isBuilder = typeof patchOps == "function", isPatch = typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == "object" && ("query" in patchOrDocumentId || "id" in patchOrDocumentId);
557
+ if (isPatch) return this._add({ patch: patchOrDocumentId.serialize() });
558
+ if (isBuilder) {
559
+ let patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));
560
+ if (!(patch instanceof Patch)) throw Error("function passed to `patch()` must return the patch");
561
+ return this._add({ patch: patch.serialize() });
562
+ }
563
+ if (isMutationSelection) {
564
+ let patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);
565
+ return this._add({ patch: patch.serialize() });
566
+ }
567
+ return this._add({ patch: {
568
+ id: patchOrDocumentId,
569
+ ...patchOps
570
+ } });
571
+ }
572
+ }, ObservableTransaction = class ObservableTransaction extends BaseTransaction {
573
+ #client;
574
+ constructor(operations, client, transactionId) {
575
+ super(operations, transactionId), this.#client = client;
576
+ }
577
+ /**
578
+ * Clones the transaction
579
+ */
580
+ clone() {
581
+ return new ObservableTransaction([...this.operations], this.#client, this.trxId);
582
+ }
583
+ commit(options) {
584
+ if (!this.#client) throw Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
585
+ return this.#client.mutate(this.serialize(), Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {}));
586
+ }
587
+ patch(patchOrDocumentId, patchOps) {
588
+ let isBuilder = typeof patchOps == "function";
589
+ if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof ObservablePatch) return this._add({ patch: patchOrDocumentId.serialize() });
590
+ if (isBuilder) {
591
+ let patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));
592
+ if (!(patch instanceof ObservablePatch)) throw Error("function passed to `patch()` must return the patch");
593
+ return this._add({ patch: patch.serialize() });
594
+ }
595
+ return this._add({ patch: {
596
+ id: patchOrDocumentId,
597
+ ...patchOps
598
+ } });
599
+ }
600
+ };
601
+ /**
602
+ * Project the public request options (`timeout: 0` to disable,
603
+ * `withCredentials`, `maxRedirects`, the function/object-form `fetch`, ...)
604
+ * plus the client config into a get-it v9 fetch-shaped request. This is the
605
+ * single translation boundary between the client's public option names and
606
+ * the transport — everything below it speaks get-it v9.
607
+ *
608
+ * Reads the live client config, so reconfiguration via `client.config()` /
609
+ * `withConfig()` (token, headers, proxy, ...) applies to subsequent requests.
610
+ *
611
+ * @internal
612
+ */
613
+ function requestOptions(config, overrides = {}) {
614
+ let headers = {};
615
+ config.headers && Object.assign(headers, config.headers);
616
+ let token = overrides.token || config.token;
617
+ token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers["X-Sanity-Project-ID"] = config.projectId);
618
+ let request = {
619
+ url: overrides.url,
620
+ headers: Object.assign(headers, overrides.headers || {})
621
+ };
622
+ overrides.method && (request.method = overrides.method), overrides.body !== void 0 && (request.body = overrides.body), overrides.query && (request.query = expandQueryArrays(overrides.query)), overrides.signal && (request.signal = overrides.signal), (overrides.withCredentials === void 0 ? config.withCredentials : overrides.withCredentials) && (request.credentials = "include"), typeof overrides.maxRedirects == "number" && (request.redirect = overrides.maxRedirects === 0 ? "manual" : "follow");
623
+ let timeout = overrides.timeout === void 0 ? config.timeout : overrides.timeout;
624
+ request.timeout = timeout === void 0 ? 3e5 : timeout !== 0 && timeout, overrides.useAbortSignal === !1 && !request.signal && (request.timeout = typeof request.timeout == "number" && request.timeout > 0 && {
625
+ total: request.timeout,
626
+ signal: !1
627
+ });
628
+ let fetchOption = typeof overrides.fetch == "object" && typeof config.fetch == "object" ? {
629
+ ...config.fetch,
630
+ ...overrides.fetch
631
+ } : overrides.fetch || config.fetch;
632
+ return typeof fetchOption == "function" ? request.fetch = fetchOption : typeof fetchOption == "object" && fetchOption && (request.meta = {
633
+ ...request.meta,
634
+ fetchInit: fetchOption
635
+ }), !request.fetch && config.resolveFetch && (request.fetch = config.resolveFetch(typeof config.proxy == "string" ? config.proxy : void 0)), typeof overrides.maxRetries == "number" && (request.maxRetries = overrides.maxRetries), typeof config.lineage == "string" && config.lineage && (request.meta = {
636
+ ...request.meta,
637
+ lineage: config.lineage
638
+ }), request;
639
+ }
640
+ /**
641
+ * Expand array-valued query params into repeated keys.
642
+ *
643
+ * get-it v9 stringifies a plain object's values directly, so passing
644
+ * `{meta: ['palette', 'location']}` would produce `?meta=palette,location`
645
+ * — which Content Lake doesn't recognise. Repeated keys
646
+ * (`?meta=palette&meta=location`) are produced via `URLSearchParams`.
647
+ */
648
+ function expandQueryArrays(query) {
649
+ if (query instanceof URLSearchParams || !query || typeof query != "object" || !Object.values(query).some(Array.isArray)) return query;
650
+ let params = new URLSearchParams();
651
+ for (let [key, value] of Object.entries(query)) if (value != null) {
652
+ if (Array.isArray(value)) for (let item of value) item != null && params.append(key, `${item}`);
653
+ else params.append(key, `${value}`);
654
+ }
655
+ return params;
656
+ }
657
+ var import_dist = require_dist();
658
+ /**
659
+ * Can take a `result` JSON from a `const {result} = client.fetch(query, params, {filterResponse: false})`
660
+ * and remove all stega-encoded data from it.
661
+ * If the result type has strings branded as `StegaString` (by `ClientReturnStega` or `stegaBrand()`),
662
+ * the brand is stripped and the original string type is restored.
663
+ * @public
664
+ */
665
+ function stegaClean(result) {
666
+ return (0, import_dist.vercelStegaClean)(result);
667
+ }
668
+ const encodeQueryString = ({ query, params = {}, options = {} }) => {
669
+ let searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;
670
+ tag && searchParams.append("tag", tag), searchParams.append("query", query);
671
+ for (let [key, value] of Object.entries(params)) value !== void 0 && searchParams.append(`$${key}`, JSON.stringify(value));
672
+ for (let [key, value] of Object.entries(opts)) value && searchParams.append(key, `${value}`);
673
+ return returnQuery === !1 && searchParams.append("returnQuery", "false"), includeMutations === !1 && searchParams.append("includeMutations", "false"), `?${searchParams}`;
674
+ }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : param === void 0 ? defValue : param, getMutationQuery = (options = {}) => ({
675
+ dryRun: options.dryRun,
676
+ returnIds: !0,
677
+ returnDocuments: excludeFalsey(options.returnDocuments, !0),
678
+ visibility: options.visibility || "sync",
679
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
680
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
681
+ }), indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), Object.create(null));
682
+ /**
683
+ * Resolve the effective stega config, cleaned params, response mapper and
684
+ * transport request options for a `fetch()` call. Shared by the observable and
685
+ * promise paths.
686
+ *
687
+ * @internal
688
+ */
689
+ function _fetchRequest(_stega, _params, options) {
690
+ let stega = "stega" in options ? {
691
+ ..._stega,
692
+ ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
693
+ } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
694
+ useAbortSignal: options.signal !== void 0,
695
+ resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
696
+ ...options,
697
+ returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
698
+ };
699
+ return {
700
+ stega,
701
+ params,
702
+ mapResponse,
703
+ reqOpts: cache !== void 0 || next !== void 0 ? {
704
+ ...opts,
705
+ fetch: {
706
+ cache,
707
+ next
708
+ }
709
+ } : opts
710
+ };
711
+ }
712
+ /** @internal */
713
+ function _fetchObservable(client, httpRequest, _stega, query, _params = {}, options = {}) {
714
+ return _observe(options.signal, (signal) => _fetch(client, httpRequest, _stega, query, _params, {
715
+ ...options,
716
+ signal
717
+ }));
718
+ }
719
+ /**
720
+ * Promise-based sibling of {@link _fetchObservable}.
721
+ *
722
+ * @internal
723
+ */
724
+ function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
725
+ let { stega, params, mapResponse, reqOpts } = _fetchRequest(_stega, _params, options), request = _dataRequest(client, httpRequest, "query", {
726
+ query,
727
+ params
728
+ }, reqOpts);
729
+ return stega.enabled ? Promise.all([request, import("./stegaEncodeSourceMap-DkoIlutY.js")]).then(([res, { stegaEncodeSourceMap }]) => {
730
+ let result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
731
+ return mapResponse({
732
+ ...res,
733
+ result
734
+ });
735
+ }) : request.then(mapResponse);
736
+ }
737
+ /** @internal */
738
+ function _getDocumentObservable(client, httpRequest, id, opts = {}) {
739
+ return _observe(opts.signal, (signal) => _request(client, httpRequest, _getDocumentOptions(client, id, {
740
+ ...opts,
741
+ signal
742
+ })).then((body) => _mapGetDocument(body, opts.includeAllVersions)));
743
+ }
744
+ /** @internal */
745
+ function _getDocument(client, httpRequest, id, opts = {}) {
746
+ return _request(client, httpRequest, _getDocumentOptions(client, id, opts)).then((body) => _mapGetDocument(body, opts.includeAllVersions));
747
+ }
748
+ /**
749
+ * Resolve the document id (honoring `releaseId`) and build the transport
750
+ * request options for {@link _getDocumentObservable}. Shared by the observable and
751
+ * promise paths.
752
+ *
753
+ * @internal
754
+ */
755
+ function _getDocumentOptions(client, id, opts) {
756
+ let docId = id;
757
+ if (opts.releaseId) {
758
+ let versionId = getVersionFromId(id);
759
+ if (!versionId) {
760
+ if (isDraftId(id)) throw Error(`The document ID (\`${id}\`) is a draft, but \`options.releaseId\` is set as \`${opts.releaseId}\``);
761
+ docId = getVersionId(id, opts.releaseId);
762
+ } else if (versionId !== opts.releaseId) throw Error(`The document ID (\`${id}\`) is already a version of \`${versionId}\` release, but this does not match the provided \`options.releaseId\` (\`${opts.releaseId}\`)`);
763
+ }
764
+ return {
765
+ url: _getDataUrl(client, "doc", docId),
766
+ tag: opts.tag,
767
+ signal: opts.signal,
768
+ query: opts.includeAllVersions === void 0 ? void 0 : { includeAllVersions: opts.includeAllVersions }
769
+ };
770
+ }
771
+ function _mapGetDocument(body, includeAllVersions) {
772
+ let documents = body.documents;
773
+ return documents ? includeAllVersions ? documents : documents[0] : includeAllVersions ? [] : void 0;
774
+ }
775
+ /** @internal */
776
+ function _getDocumentsObservable(client, httpRequest, ids, opts = {}) {
777
+ return _observe(opts.signal, (signal) => _getDocuments(client, httpRequest, ids, {
778
+ ...opts,
779
+ signal
780
+ }));
781
+ }
782
+ /**
783
+ * Promise-based sibling of {@link _getDocumentsObservable}.
784
+ *
785
+ * @internal
786
+ */
787
+ function _getDocuments(client, httpRequest, ids, opts = {}) {
788
+ return _request(client, httpRequest, _getDocumentsOptions(client, ids, opts)).then((body) => _mapGetDocuments(body, ids));
789
+ }
790
+ function _getDocumentsOptions(client, ids, opts) {
791
+ return {
792
+ url: _getDataUrl(client, "doc", ids.join(",")),
793
+ tag: opts.tag,
794
+ signal: opts.signal
795
+ };
796
+ }
797
+ function _mapGetDocuments(body, ids) {
798
+ let indexed = indexBy(body.documents || [], (doc) => doc._id);
799
+ return ids.map((id) => indexed[id] || null);
800
+ }
801
+ /** @internal */
802
+ function _documentsExistsObservable(client, httpRequest, ids, opts = {}) {
803
+ return _observe(opts.signal, (signal) => _documentsExists(client, httpRequest, ids, {
804
+ ...opts,
805
+ signal
806
+ }));
807
+ }
808
+ /**
809
+ * Promise-based sibling of {@link _documentsExistsObservable}. Checks document
810
+ * existence in batches, resolving to the set of IDs that exist.
811
+ *
812
+ * @internal
813
+ */
814
+ async function _documentsExists(client, httpRequest, ids, opts = {}) {
815
+ let existing = /* @__PURE__ */ new Set();
816
+ if (ids.length === 0) return existing;
817
+ for (let i = 0; i < ids.length; i += 100) {
818
+ let batchIds = ids.slice(i, i + 100), body = await _request(client, httpRequest, {
819
+ url: _getDataUrl(client, "doc", batchIds.map(encodeURIComponent).join(",")),
820
+ tag: opts.tag,
821
+ signal: opts.signal,
822
+ query: { excludeContent: !0 }
823
+ }), missing = /* @__PURE__ */ new Set();
824
+ for (let omitted of body.omitted || []) omitted.reason === "existence" && missing.add(omitted.id);
825
+ for (let id of batchIds) missing.has(id) || existing.add(id);
826
+ }
827
+ return existing;
828
+ }
829
+ /** @internal */
830
+ function _getReleaseDocumentsObservable(client, httpRequest, releaseId, opts = {}) {
831
+ return _observe(opts.signal, (signal) => _getReleaseDocuments(client, httpRequest, releaseId, {
832
+ ...opts,
833
+ signal
834
+ }));
835
+ }
836
+ /**
837
+ * Promise-based sibling of {@link _getReleaseDocumentsObservable}.
838
+ *
839
+ * @internal
840
+ */
841
+ function _getReleaseDocuments(client, httpRequest, releaseId, opts = {}) {
842
+ return _dataRequest(client, httpRequest, "query", {
843
+ query: "*[sanity::partOfRelease($releaseId)]",
844
+ params: { releaseId }
845
+ }, opts);
846
+ }
847
+ /** @internal */
848
+ function _createIfNotExistsObservable(client, httpRequest, doc, options) {
849
+ return _observe(options?.signal, (signal) => _createIfNotExists(client, httpRequest, doc, {
850
+ ...options,
851
+ signal
852
+ }));
853
+ }
854
+ /** @internal */
855
+ function _createOrReplaceObservable(client, httpRequest, doc, options) {
856
+ return _observe(options?.signal, (signal) => _createOrReplace(client, httpRequest, doc, {
857
+ ...options,
858
+ signal
859
+ }));
860
+ }
861
+ /** @internal */
862
+ function _createVersionObservable(client, httpRequest, doc, publishedId, options) {
863
+ return _observe(options?.signal, (signal) => _createVersion(client, httpRequest, doc, publishedId, {
864
+ ...options,
865
+ signal
866
+ }));
867
+ }
868
+ /** @internal */
869
+ function _createVersionFromBaseObservable(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options) {
870
+ return _observe(options?.signal, (signal) => _createVersionFromBase(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, {
871
+ ...options,
872
+ signal
873
+ }));
874
+ }
875
+ /** @internal */
876
+ function _deleteObservable(client, httpRequest, selection, options) {
877
+ return _observe(options?.signal, (signal) => _delete(client, httpRequest, selection, {
878
+ ...options,
879
+ signal
880
+ }));
881
+ }
882
+ /** @internal */
883
+ function _discardVersionObservable(client, httpRequest, versionId, purge = !1, options) {
884
+ return _observe(options?.signal, (signal) => _discardVersion(client, httpRequest, versionId, purge, {
885
+ ...options,
886
+ signal
887
+ }));
888
+ }
889
+ /** @internal */
890
+ function _replaceVersionObservable(client, httpRequest, doc, options) {
891
+ return _observe(options?.signal, (signal) => _replaceVersion(client, httpRequest, doc, {
892
+ ...options,
893
+ signal
894
+ }));
895
+ }
896
+ /** @internal */
897
+ function _unpublishVersionObservable(client, httpRequest, versionId, publishedId, options) {
898
+ return _observe(options?.signal, (signal) => _unpublishVersion(client, httpRequest, versionId, publishedId, {
899
+ ...options,
900
+ signal
901
+ }));
902
+ }
903
+ /** @internal */
904
+ function _mutateObservable(client, httpRequest, mutations, options) {
905
+ return _observe(options?.signal, (signal) => _mutate(client, httpRequest, mutations, {
906
+ ...options,
907
+ signal
908
+ }));
909
+ }
910
+ /**
911
+ * @internal
912
+ */
913
+ function _actionObservable(client, httpRequest, actions, options) {
914
+ return _observe(options?.signal, (signal) => _action(client, httpRequest, actions, {
915
+ ...options,
916
+ signal
917
+ }));
918
+ }
919
+ /**
920
+ * Build the transport request options for a data endpoint (`query` / `mutate`
921
+ * / `actions`). Shared by the observable and promise request paths.
922
+ *
923
+ * @internal
924
+ */
925
+ function _dataRequestOptions(client, endpoint, body, options = {}) {
926
+ let isMutation = endpoint === "mutate", isAction = endpoint === "actions", isQuery = endpoint === "query", strQuery = isMutation || isAction ? "" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < 11264, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode } = options, url = _getDataUrl(client, endpoint, stringQuery);
927
+ return {
928
+ reqOptions: {
929
+ method: useGet ? "GET" : "POST",
930
+ url,
931
+ body: useGet ? void 0 : body,
932
+ query: isMutation && getMutationQuery(options),
933
+ timeout,
934
+ headers,
935
+ token,
936
+ tag,
937
+ returnQuery,
938
+ perspective: options.perspective,
939
+ variant: options.variant,
940
+ resultSourceMap: options.resultSourceMap,
941
+ lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,
942
+ cacheMode,
943
+ canUseCdn: isQuery,
944
+ signal: options.signal,
945
+ fetch: options.fetch,
946
+ useAbortSignal: options.useAbortSignal,
947
+ useCdn: options.useCdn
948
+ },
949
+ isMutation,
950
+ returnFirst
951
+ };
952
+ }
953
+ /**
954
+ * Shape the raw response body of a data request. For mutations this reduces
955
+ * the API response to documents or ids; everything else passes through. Pure
956
+ * function shared by the observable and promise request paths.
957
+ *
958
+ * @internal
959
+ */
960
+ function _mapDataResponse(res, isMutation, returnFirst, returnDocuments) {
961
+ if (!isMutation) return res;
962
+ let results = res.results || [];
963
+ if (returnDocuments) return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
964
+ let key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
965
+ return {
966
+ transactionId: res.transactionId,
967
+ results,
968
+ [key]: ids
969
+ };
970
+ }
971
+ /**
972
+ * Promise-based sibling of {@link _dataRequestObservable}.
973
+ *
974
+ * @internal
975
+ */
976
+ function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
977
+ let { reqOptions, isMutation, returnFirst } = _dataRequestOptions(client, endpoint, body, options);
978
+ return _request(client, httpRequest, reqOptions).then((res) => _mapDataResponse(res, isMutation, returnFirst, options.returnDocuments));
979
+ }
980
+ /**
981
+ * @internal
982
+ */
983
+ function _createObservable(client, httpRequest, doc, op, options = {}) {
984
+ return _observe(options.signal, (signal) => _create(client, httpRequest, doc, op, {
985
+ ...options,
986
+ signal
987
+ }));
988
+ }
989
+ /**
990
+ * Promise-based sibling of {@link _createObservable}.
991
+ *
992
+ * @internal
993
+ */
994
+ function _create(client, httpRequest, doc, op, options = {}) {
995
+ let mutation = { [op]: doc }, opts = Object.assign({
996
+ returnFirst: !0,
997
+ returnDocuments: !0
998
+ }, options);
999
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
1000
+ }
1001
+ /**
1002
+ * Promise-based sibling of {@link _actionObservable}.
1003
+ *
1004
+ * @internal
1005
+ */
1006
+ function _action(client, httpRequest, actions, options) {
1007
+ return _dataRequest(client, httpRequest, "actions", {
1008
+ actions: Array.isArray(actions) ? actions : [actions],
1009
+ transactionId: options && options.transactionId || void 0,
1010
+ skipCrossDatasetReferenceValidation: options && options.skipCrossDatasetReferenceValidation || void 0,
1011
+ dryRun: options && options.dryRun || void 0
1012
+ }, options);
1013
+ }
1014
+ /**
1015
+ * Promise-based sibling of {@link _mutateObservable}.
1016
+ *
1017
+ * @internal
1018
+ */
1019
+ function _mutate(client, httpRequest, mutations, options) {
1020
+ let mut;
1021
+ return mut = mutations instanceof Patch || mutations instanceof ObservablePatch ? { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mutations.serialize() : mutations, _dataRequest(client, httpRequest, "mutate", {
1022
+ mutations: Array.isArray(mut) ? mut : [mut],
1023
+ transactionId: options && options.transactionId || void 0
1024
+ }, options);
1025
+ }
1026
+ /**
1027
+ * Promise-based sibling of {@link _deleteObservable}.
1028
+ *
1029
+ * @internal
1030
+ */
1031
+ function _delete(client, httpRequest, selection, options) {
1032
+ return _dataRequest(client, httpRequest, "mutate", { mutations: [{ delete: getSelection(selection) }] }, options);
1033
+ }
1034
+ /**
1035
+ * Promise-based sibling of {@link _createIfNotExistsObservable}.
1036
+ *
1037
+ * @internal
1038
+ */
1039
+ function _createIfNotExists(client, httpRequest, doc, options) {
1040
+ return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
1041
+ }
1042
+ /**
1043
+ * Promise-based sibling of {@link _createOrReplaceObservable}.
1044
+ *
1045
+ * @internal
1046
+ */
1047
+ function _createOrReplace(client, httpRequest, doc, options) {
1048
+ return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
1049
+ }
1050
+ /**
1051
+ * Promise-based sibling of {@link _createVersionObservable}.
1052
+ *
1053
+ * @internal
1054
+ */
1055
+ function _createVersion(client, httpRequest, doc, publishedId, options) {
1056
+ return requireDocumentId("createVersion", doc), requireDocumentType("createVersion", doc), printCreateVersionWithBaseIdWarning(), _action(client, httpRequest, {
1057
+ actionType: "sanity.action.document.version.create",
1058
+ publishedId,
1059
+ document: doc
1060
+ }, options);
1061
+ }
1062
+ /**
1063
+ * Promise-based sibling of {@link _createVersionFromBaseObservable}.
1064
+ *
1065
+ * @internal
1066
+ */
1067
+ function _createVersionFromBase(client, httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options) {
1068
+ if (!baseId) throw Error("`createVersion()` requires `baseId` when no `document` is provided");
1069
+ if (!publishedId) throw Error("`createVersion()` requires `publishedId` when `baseId` is provided");
1070
+ return validateDocumentId("createVersion", baseId), validateDocumentId("createVersion", publishedId), _action(client, httpRequest, {
1071
+ actionType: "sanity.action.document.version.create",
1072
+ publishedId,
1073
+ baseId,
1074
+ versionId: releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId),
1075
+ ifBaseRevisionId
1076
+ }, options);
1077
+ }
1078
+ /**
1079
+ * Promise-based sibling of {@link _discardVersionObservable}.
1080
+ *
1081
+ * @internal
1082
+ */
1083
+ function _discardVersion(client, httpRequest, versionId, purge = !1, options) {
1084
+ return _action(client, httpRequest, {
1085
+ actionType: "sanity.action.document.version.discard",
1086
+ versionId,
1087
+ purge
1088
+ }, options);
1089
+ }
1090
+ /**
1091
+ * Promise-based sibling of {@link _replaceVersionObservable}.
1092
+ *
1093
+ * @internal
1094
+ */
1095
+ function _replaceVersion(client, httpRequest, doc, options) {
1096
+ return requireDocumentId("replaceVersion", doc), requireDocumentType("replaceVersion", doc), _action(client, httpRequest, {
1097
+ actionType: "sanity.action.document.version.replace",
1098
+ document: doc
1099
+ }, options);
1100
+ }
1101
+ /**
1102
+ * Promise-based sibling of {@link _unpublishVersionObservable}.
1103
+ *
1104
+ * @internal
1105
+ */
1106
+ function _unpublishVersion(client, httpRequest, versionId, publishedId, options) {
1107
+ return _action(client, httpRequest, {
1108
+ actionType: "sanity.action.document.version.unpublish",
1109
+ versionId,
1110
+ publishedId
1111
+ }, options);
1112
+ }
1113
+ const hasDataConfig = (client) => {
1114
+ let config = client.config();
1115
+ return config.dataset !== void 0 && config.projectId !== void 0 || config.resource !== void 0;
1116
+ }, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "query")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "mutate")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "doc", "")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "listen")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, "history", "")), isData = (client, uri) => uri.startsWith("/data/") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);
1117
+ /**
1118
+ * Build the final request options (URL, headers, query params, etc.) used by
1119
+ * both the regular request pipeline and the asset upload path.
1120
+ *
1121
+ * @internal
1122
+ */
1123
+ function _prepareRequest(client, options) {
1124
+ options.uri !== void 0 && printDeprecatedUriOptionWarning();
1125
+ let uri = options.uri || options.url;
1126
+ if (typeof uri != "string") throw TypeError("Request options must include a `url`");
1127
+ let config = client.config(), canUseCdn = options.canUseCdn === void 0 ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && isData(client, uri) : options.canUseCdn, useCdn = (options.useCdn ?? config.useCdn) && canUseCdn, tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
1128
+ if (tag && options.tag !== null && (options.query = {
1129
+ tag: requestTag(tag),
1130
+ ...options.query
1131
+ }), [
1132
+ "GET",
1133
+ "HEAD",
1134
+ "POST"
1135
+ ].indexOf(options.method || "GET") >= 0 && isQuery(client, uri)) {
1136
+ let resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
1137
+ resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = {
1138
+ resultSourceMap,
1139
+ ...options.query
1140
+ });
1141
+ let perspectiveOption = options.perspective || config.perspective;
1142
+ perspectiveOption !== void 0 && (perspectiveOption === "previewDrafts" && printPreviewDraftsDeprecationWarning(), validateApiPerspective(perspectiveOption), options.query = {
1143
+ perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption,
1144
+ ...options.query
1145
+ }, (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || perspectiveOption === "previewDrafts" || perspectiveOption === "drafts") && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning()));
1146
+ let variantOption = options.variant || config.variant;
1147
+ typeof variantOption == "string" && (options.query = {
1148
+ variant: variantOption,
1149
+ ...options.query
1150
+ }), typeof variantOption == "object" && (options.query = {
1151
+ variantCondition: variantConditionsToQueryArray(variantOption),
1152
+ ...options.query
1153
+ }), options.lastLiveEventId && (options.query = {
1154
+ ...options.query,
1155
+ lastLiveEventId: options.lastLiveEventId
1156
+ }), options.returnQuery === !1 && (options.query = {
1157
+ returnQuery: "false",
1158
+ ...options.query
1159
+ }), useCdn && options.cacheMode == "noStale" && (options.query = {
1160
+ cacheMode: "noStale",
1161
+ ...options.query
1162
+ });
1163
+ }
1164
+ return requestOptions(config, Object.assign({}, options, { url: _getUrl(client, uri, useCdn) }));
1165
+ }
1166
+ /**
1167
+ * Wrap a promise-returning request in a cold, single-value Observable.
1168
+ *
1169
+ * Each subscription invokes `run` with a fresh `AbortSignal` that is aborted
1170
+ * when the subscriber unsubscribes — so unsubscribing cancels the in-flight
1171
+ * `fetch`. A caller-supplied `userSignal` is chained in too, so the request
1172
+ * still aborts when the caller's own signal fires. The single resolved value
1173
+ * (or rejection) is forwarded to the subscriber.
1174
+ *
1175
+ * This is the bridge that lets the observable client surface reuse the exact
1176
+ * same promise implementations as the promise client surface, with no
1177
+ * duplicated request logic.
1178
+ *
1179
+ * @internal
1180
+ */
1181
+ function _observe(userSignal, run) {
1182
+ return new Observable((subscriber) => {
1183
+ let controller = new AbortController();
1184
+ return run(userSignal ? AbortSignal.any([userSignal, controller.signal]) : controller.signal).then((value) => {
1185
+ subscriber.next(value), subscriber.complete();
1186
+ }, (err) => subscriber.error(err)), () => controller.abort();
1187
+ });
1188
+ }
1189
+ /**
1190
+ * Promise-based sibling of {@link _requestObservable}. Resolves directly to
1191
+ * the parsed response body without ever constructing an Observable. The abort
1192
+ * signal is honored by the underlying `fetch` (it is threaded onto the request
1193
+ * options), so no RxJS-level teardown is required.
1194
+ *
1195
+ * @internal
1196
+ */
1197
+ function _request(client, httpRequest, options) {
1198
+ return httpRequest(_prepareRequest(client, options)).then((body) => body);
1199
+ }
1200
+ /**
1201
+ * Execute an HTTP request through the regular pipeline and resolve to the
1202
+ * parsed response body. Observable wrapper over {@link _request}.
1203
+ *
1204
+ * @internal
1205
+ */
1206
+ function _requestObservable(client, httpRequest, options) {
1207
+ return _observe(options.signal, (signal) => _request(client, httpRequest, {
1208
+ ...options,
1209
+ signal
1210
+ }));
1211
+ }
1212
+ /**
1213
+ * Execute an asset upload through the underlying requester directly,
1214
+ * exposing the full upload event stream (progress + response).
1215
+ *
1216
+ * Bypasses the body-only `HttpRequest` boundary so progress events from the
1217
+ * transport layer can surface to consumers, reading the resolved requester
1218
+ * straight off the initialized config.
1219
+ *
1220
+ * @internal
1221
+ */
1222
+ function _uploadObservable(client, options) {
1223
+ let reqOptions = _prepareRequest(client, options), requester = client.config().requester, request = new Observable((subscriber) => requester(reqOptions).subscribe(subscriber)).pipe(filter((event) => event?.type === "progress" || event?.type === "response"), map$1((event) => event.type === "progress" ? {
1224
+ type: "progress",
1225
+ stage: event.stage,
1226
+ percent: event.percent,
1227
+ total: event.total,
1228
+ loaded: event.loaded,
1229
+ lengthComputable: event.lengthComputable
1230
+ } : {
1231
+ type: "response",
1232
+ body: event.body
1233
+ }));
1234
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
1235
+ }
1236
+ /**
1237
+ * @internal
1238
+ */
1239
+ function _getDataUrl(client, operation, path) {
1240
+ let config = client.config();
1241
+ if (config.resource) return resourceConfig(config), `${resourceDataBase(config)}/${path === void 0 ? operation : `${operation}/${path}`}`.replace(/\/($|\?)/, "$1");
1242
+ let baseUri = `/${operation}/${hasDataset(config)}`;
1243
+ return `/data${path === void 0 ? baseUri : `${baseUri}/${path}`}`.replace(/\/($|\?)/, "$1");
1244
+ }
1245
+ /**
1246
+ * @internal
1247
+ */
1248
+ function _getUrl(client, uri, canUseCdn = !1) {
1249
+ let { url, cdnUrl } = client.config();
1250
+ return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
1251
+ }
1252
+ /**
1253
+ * @internal
1254
+ */
1255
+ function _withAbortSignal(signal) {
1256
+ return (input) => new Observable((observer) => {
1257
+ let abort = () => observer.error(_createAbortError(signal));
1258
+ if (signal && signal.aborted) {
1259
+ abort();
1260
+ return;
1261
+ }
1262
+ let subscription = input.subscribe(observer);
1263
+ return signal.addEventListener("abort", abort), () => {
1264
+ signal.removeEventListener("abort", abort), subscription.unsubscribe();
1265
+ };
1266
+ });
1267
+ }
1268
+ /**
1269
+ * `DOMException` is globally available in every supported runtime
1270
+ * (Node 22.12+ and all modern browsers), so we can construct one directly.
1271
+ *
1272
+ * @internal
1273
+ */
1274
+ function _createAbortError(signal) {
1275
+ return new DOMException(signal?.reason ?? "The operation was aborted.", "AbortError");
1276
+ }
1277
+ const resourceDataBase = (config) => {
1278
+ let resource = config.resource;
1279
+ if (!resource) throw Error("`resource` must be provided to perform resource queries");
1280
+ let { type, id } = resource;
1281
+ switch (type) {
1282
+ case "dataset": {
1283
+ let segments = id.split(".");
1284
+ if (segments.length !== 2) throw Error("Dataset ID must be in the format \"project.dataset\"");
1285
+ return `/projects/${segments[0]}/datasets/${segments[1]}`;
1286
+ }
1287
+ case "canvas": return `/canvases/${id}`;
1288
+ case "media-library": return `/media-libraries/${id}`;
1289
+ case "dashboard": return `/dashboards/${id}`;
1290
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
1291
+ }
1292
+ };
1293
+ function variantConditionsToQueryArray(variantConditions) {
1294
+ return Object.entries(variantConditions).map(([condition, value]) => `${condition}:${value}`).toSorted();
1295
+ }
1296
+ function _generateObservable(client, httpRequest, request) {
1297
+ return _requestObservable(client, httpRequest, {
1298
+ method: "POST",
1299
+ url: `/agent/action/generate/${hasDataset(client.config())}`,
1300
+ body: request
1301
+ });
1302
+ }
1303
+ function _generate(client, httpRequest, request) {
1304
+ return _request(client, httpRequest, {
1305
+ method: "POST",
1306
+ url: `/agent/action/generate/${hasDataset(client.config())}`,
1307
+ body: request
1308
+ });
1309
+ }
1310
+ function _patch(client, httpRequest, request) {
1311
+ return _request(client, httpRequest, {
1312
+ method: "POST",
1313
+ url: `/agent/action/patch/${hasDataset(client.config())}`,
1314
+ body: request
1315
+ });
1316
+ }
1317
+ function _prompt(client, httpRequest, request) {
1318
+ return _request(client, httpRequest, {
1319
+ method: "POST",
1320
+ url: `/agent/action/prompt/${hasDataset(client.config())}`,
1321
+ body: request
1322
+ });
1323
+ }
1324
+ function _transformObservable(client, httpRequest, request) {
1325
+ return _requestObservable(client, httpRequest, {
1326
+ method: "POST",
1327
+ url: `/agent/action/transform/${hasDataset(client.config())}`,
1328
+ body: request
1329
+ });
1330
+ }
1331
+ function _transform(client, httpRequest, request) {
1332
+ return _request(client, httpRequest, {
1333
+ method: "POST",
1334
+ url: `/agent/action/transform/${hasDataset(client.config())}`,
1335
+ body: request
1336
+ });
1337
+ }
1338
+ function _translateObservable(client, httpRequest, request) {
1339
+ return _requestObservable(client, httpRequest, {
1340
+ method: "POST",
1341
+ url: `/agent/action/translate/${hasDataset(client.config())}`,
1342
+ body: request
1343
+ });
1344
+ }
1345
+ function _translate(client, httpRequest, request) {
1346
+ return _request(client, httpRequest, {
1347
+ method: "POST",
1348
+ url: `/agent/action/translate/${hasDataset(client.config())}`,
1349
+ body: request
1350
+ });
1351
+ }
1352
+ /** @public */
1353
+ var ObservableAgentsActionClient = class {
1354
+ #client;
1355
+ #httpRequest;
1356
+ constructor(client, httpRequest) {
1357
+ this.#client = client, this.#httpRequest = httpRequest;
1358
+ }
1359
+ /**
1360
+ * Run an instruction to generate content in a target document.
1361
+ * @param request - instruction request
1362
+ */
1363
+ generate(request) {
1364
+ return _generateObservable(this.#client, this.#httpRequest, request);
1365
+ }
1366
+ /**
1367
+ * Transform a target document based on a source.
1368
+ * @param request - translation request
1369
+ */
1370
+ transform(request) {
1371
+ return _transformObservable(this.#client, this.#httpRequest, request);
1372
+ }
1373
+ /**
1374
+ * Translate a target document based on a source.
1375
+ * @param request - translation request
1376
+ */
1377
+ translate(request) {
1378
+ return _translateObservable(this.#client, this.#httpRequest, request);
1379
+ }
1380
+ }, AgentActionsClient = class {
1381
+ #client;
1382
+ #httpRequest;
1383
+ constructor(client, httpRequest) {
1384
+ this.#client = client, this.#httpRequest = httpRequest;
1385
+ }
1386
+ /**
1387
+ * Run an instruction to generate content in a target document.
1388
+ * @param request - instruction request
1389
+ */
1390
+ generate(request) {
1391
+ return _generate(this.#client, this.#httpRequest, request);
1392
+ }
1393
+ /**
1394
+ * Transform a target document based on a source.
1395
+ * @param request - translation request
1396
+ */
1397
+ transform(request) {
1398
+ return _transform(this.#client, this.#httpRequest, request);
1399
+ }
1400
+ /**
1401
+ * Translate a target document based on a source.
1402
+ * @param request - translation request
1403
+ */
1404
+ translate(request) {
1405
+ return _translate(this.#client, this.#httpRequest, request);
1406
+ }
1407
+ /**
1408
+ * Run a raw instruction and return the result either as text or json
1409
+ * @param request - prompt request
1410
+ */
1411
+ prompt(request) {
1412
+ return _prompt(this.#client, this.#httpRequest, request);
1413
+ }
1414
+ /**
1415
+ * Patch a document using a schema aware API.
1416
+ * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
1417
+ * @param request - instruction request
1418
+ */
1419
+ patch(request) {
1420
+ return _patch(this.#client, this.#httpRequest, request);
1421
+ }
1422
+ }, ObservableAssetsClient = class {
1423
+ #client;
1424
+ #httpRequest;
1425
+ constructor(client, httpRequest) {
1426
+ this.#client = client, this.#httpRequest = httpRequest;
1427
+ }
1428
+ upload(assetType, body, options) {
1429
+ return _upload(this.#client, this.#httpRequest, assetType, body, options);
1430
+ }
1431
+ }, AssetsClient = class {
1432
+ #client;
1433
+ #httpRequest;
1434
+ constructor(client, httpRequest) {
1435
+ this.#client = client, this.#httpRequest = httpRequest;
1436
+ }
1437
+ upload(assetType, body, options) {
1438
+ 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)));
1440
+ }
1441
+ };
1442
+ function _upload(client, _httpRequest, assetType, body, opts = {}) {
1443
+ validateAssetType(assetType);
1444
+ let meta = opts.extract || void 0;
1445
+ meta && !meta.length && (meta = ["none"]);
1446
+ let config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, isMediaLibrary = config.resource?.type === "media-library", query = isMediaLibrary ? {
1447
+ title,
1448
+ filename
1449
+ } : {
1450
+ label,
1451
+ title,
1452
+ description,
1453
+ filename,
1454
+ meta,
1455
+ creditLine
1456
+ };
1457
+ source && !isMediaLibrary && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url);
1458
+ let headers = options.contentType ? { "Content-Type": options.contentType } : {}, baseRequest = {
1459
+ tag,
1460
+ method: "POST",
1461
+ timeout: options.timeout || 0,
1462
+ url: buildAssetUploadUrl(config, assetType),
1463
+ headers,
1464
+ query,
1465
+ body
1466
+ };
1467
+ return typeof XMLHttpRequest < "u" ? defer(async () => {
1468
+ let { uploadWithProgress } = await import("./browserUpload-icWlVP15.js"), req = _prepareRequest(client, { ...baseRequest });
1469
+ return uploadWithProgress({
1470
+ url: appendQuery(req.url, req.query),
1471
+ method: req.method ?? "POST",
1472
+ headers: req.headers,
1473
+ body,
1474
+ withCredentials: req.credentials === "include",
1475
+ timeout: typeof req.timeout == "object" ? req.timeout.total : req.timeout,
1476
+ signal: req.signal
1477
+ });
1478
+ }).pipe(mergeAll()) : _uploadObservable(client, baseRequest);
1479
+ }
1480
+ function appendQuery(url, query) {
1481
+ if (!query) return url;
1482
+ let qs = (query instanceof URLSearchParams ? query : new URLSearchParams(Object.entries(query).flatMap(([key, value]) => value == null ? [] : [[key, `${value}`]]))).toString();
1483
+ return qs ? url + (url.includes("?") ? "&" : "?") + qs : url;
1484
+ }
1485
+ function buildAssetUploadUrl(config, assetType) {
1486
+ let assetTypeEndpoint = assetType === "image" ? "images" : "files", resource = config.resource;
1487
+ if (resource) {
1488
+ let { type, id } = resource;
1489
+ switch (type) {
1490
+ case "dataset": throw Error("Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.");
1491
+ case "canvas": return `/canvases/${id}/assets/${assetTypeEndpoint}`;
1492
+ case "media-library": return `/media-libraries/${id}/upload`;
1493
+ case "dashboard": return `/dashboards/${id}/assets/${assetTypeEndpoint}`;
1494
+ default: throw Error(`Unsupported resource type: ${type.toString()}`);
1495
+ }
1496
+ }
1497
+ return `assets/${assetTypeEndpoint}/${hasDataset(config)}`;
1498
+ }
1499
+ function optionsFromFile(opts, file) {
1500
+ return typeof File > "u" || !(file instanceof File) ? opts : Object.assign({
1501
+ filename: opts.preserveFilename === !1 ? void 0 : file.name,
1502
+ contentType: file.type
1503
+ }, opts);
1504
+ }
1505
+ var defaults_default = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = obj[prop] === void 0 ? defaults[prop] : obj[prop], target), {});
1506
+ const pick = (obj, props) => props.reduce((selection, prop) => (obj[prop] === void 0 || (selection[prop] = obj[prop]), selection), {}), RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429]);
1507
+ /**
1508
+ * Note: connection failure is not the same as network disconnect which may happen more frequent.
1509
+ * The EventSource instance will automatically reconnect in case of a network disconnect, however,
1510
+ * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these
1511
+ */
1512
+ function reconnectOnConnectionFailure() {
1513
+ return function(source) {
1514
+ return source.pipe(catchError((err, caught) => err instanceof ConnectionFailedError && (typeof err.status != "number" || err.status < 400 || err.status >= 500 || RETRYABLE_STATUSES.has(err.status)) ? concat(of({ type: "reconnect" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err)));
1515
+ };
1516
+ }
1517
+ /**
1518
+ * Build a `fetch` implementation suitable for the `eventsource` package's
1519
+ * `fetch` option. Routes the EventSource connection through the same
1520
+ * transport layer the rest of the client uses, so things like the
1521
+ * test-fetch override, the per-request `proxy` config, and `HTTPS_PROXY`
1522
+ * env-var support apply to SSE too.
1523
+ *
1524
+ * Resolution order on each request:
1525
+ *
1526
+ * 1. `config.resolveFetch(config.proxy)` if set — the client's fetch
1527
+ * resolver, so SSE uses the same transport as regular requests:
1528
+ * custom fetch variants (incl. the test suite's injected mock),
1529
+ * undici configuration, an explicit `proxy` config, and env-proxy
1530
+ * support all apply to SSE too. The Node entry supplies get-it's
1531
+ * undici-backed fetch (threading the resolver through the env
1532
+ * instead of importing `get-it/node` directly keeps `undici` out of
1533
+ * the browser bundle); the browser entry leaves it unset.
1534
+ * 2. `globalThis.fetch`. Note that Node's global fetch does NOT read
1535
+ * proxy env vars (that is opt-in via `NODE_USE_ENV_PROXY`), which
1536
+ * is one of the reasons step 1 exists.
1537
+ *
1538
+ * The returned fetch always merges `options.headers` into the outgoing
1539
+ * request, regardless of which underlying fetch was picked.
1540
+ *
1541
+ * @internal
1542
+ */
1543
+ function resolveEventSourceFetch(config, options = {}) {
1544
+ let extraHeaders = options.headers, credentials = options.withCredentials ? "include" : void 0;
1545
+ return function eventSourceFetch(url, init) {
1546
+ let baseFetch = pickBaseFetch(config), mergedInit = { ...init };
1547
+ if (extraHeaders) {
1548
+ let headers = new Headers(init?.headers);
1549
+ for (let [key, value] of Object.entries(extraHeaders)) headers.set(key, value);
1550
+ mergedInit.headers = headers;
1551
+ }
1552
+ return credentials !== void 0 && (mergedInit.credentials = credentials), baseFetch(typeof url == "string" ? url : url.href, mergedInit);
1553
+ };
1554
+ }
1555
+ function pickBaseFetch(config) {
1556
+ return config.resolveFetch ? config.resolveFetch(typeof config.proxy == "string" ? config.proxy : void 0) : globalThis.fetch.bind(globalThis);
1557
+ }
1558
+ const possibleOptions = [
1559
+ "includePreviousRevision",
1560
+ "includeResult",
1561
+ "includeMutations",
1562
+ "includeAllVersions",
1563
+ "visibility",
1564
+ "effectFormat",
1565
+ "enableResume",
1566
+ "tag"
1567
+ ], defaultOptions = { includeResult: !0 };
1568
+ /** @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 = {
1571
+ ...defaults_default(opts, defaultOptions),
1572
+ tag
1573
+ }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({
1574
+ query,
1575
+ params,
1576
+ options: {
1577
+ tag,
1578
+ ...listenOpts
1579
+ }
1580
+ }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
1581
+ if (uri.length > 14800) return throwError(() => /* @__PURE__ */ Error("Query too large for listener"));
1582
+ let listenFor = options.events ? options.events : ["mutation"], headers = {};
1583
+ token && (headers.Authorization = `Bearer ${token}`), configHeaders && Object.assign(headers, configHeaders);
1584
+ let initEventSource = () => new EventSource(uri, { fetch: resolveEventSourceFetch(config, {
1585
+ headers: Object.keys(headers).length ? headers : void 0,
1586
+ withCredentials
1587
+ }) });
1588
+ return connectEventSource(initEventSource, listenFor).pipe(reconnectOnConnectionFailure(), filter((event) => listenFor.includes(event.type)), map$1((event) => ({
1589
+ type: event.type,
1590
+ ..."data" in event ? event.data : {}
1591
+ })));
1592
+ }
1593
+ /**
1594
+ * A variant of share that takes a predicate function to determine which value to replay to new subscribers
1595
+ * @param configOrPredicate - Predicate function to determine which value to replay
1596
+ * @param config - Optional ShareConfig
1597
+ */
1598
+ function shareReplayLatest(configOrPredicate, config) {
1599
+ return _shareReplayLatest(typeof configOrPredicate == "function" ? {
1600
+ predicate: configOrPredicate,
1601
+ ...config
1602
+ } : configOrPredicate);
1603
+ }
1604
+ function _shareReplayLatest(config) {
1605
+ return (source) => {
1606
+ let latest, emitted = !1, { predicate, ...shareConfig } = config, wrapped = source.pipe(tap((value) => {
1607
+ config.predicate(value) && (emitted = !0, latest = value);
1608
+ }), finalize(() => {
1609
+ emitted = !1, latest = void 0;
1610
+ }), share(shareConfig)), emitLatest = new Observable((subscriber) => {
1611
+ emitted && subscriber.next(latest), subscriber.complete();
1612
+ });
1613
+ return merge(wrapped, emitLatest);
1614
+ };
1615
+ }
1616
+ const requiredApiVersion = "2021-03-25";
1617
+ /**
1618
+ * @public
1619
+ */
1620
+ var LiveClient = class {
1621
+ #client;
1622
+ constructor(client) {
1623
+ this.#client = client;
1624
+ }
1625
+ /**
1626
+ * Requires `apiVersion` to be `2021-03-25` or later.
1627
+ */
1628
+ events({ includeDrafts = !1, tag: _tag, waitFor } = {}) {
1629
+ let config = this.#client.config(), { projectId, apiVersion: _apiVersion, token, withCredentials, requestTagPrefix, headers: configHeaders } = config, apiVersion = _apiVersion.replace(/^v/, "");
1630
+ if (apiVersion !== "X" && apiVersion < requiredApiVersion) throw Error(`The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`);
1631
+ if (includeDrafts && !token && !withCredentials) throw Error("The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.");
1632
+ let path = _getDataUrl(this.#client, "live/events"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(".") : _tag;
1633
+ tag && url.searchParams.set("tag", tag), includeDrafts && url.searchParams.set("includeDrafts", "true"), waitFor && url.searchParams.set("waitFor", waitFor);
1634
+ let eventSourceHeaders = {};
1635
+ includeDrafts && token && (eventSourceHeaders.Authorization = `Bearer ${token}`), configHeaders && Object.assign(eventSourceHeaders, configHeaders);
1636
+ let eventSourceWithCredentials = !!(includeDrafts && withCredentials), transportCache = eventsCache.get(config.resolveFetch);
1637
+ transportCache || (transportCache = /* @__PURE__ */ new Map(), eventsCache.set(config.resolveFetch, transportCache));
1638
+ let cacheKey = JSON.stringify([
1639
+ url.href,
1640
+ typeof config.proxy == "string" ? config.proxy : null,
1641
+ eventSourceHeaders,
1642
+ eventSourceWithCredentials
1643
+ ]), existing = transportCache.get(cacheKey);
1644
+ if (existing) return existing;
1645
+ let initEventSource = () => new EventSource(url.href, { fetch: resolveEventSourceFetch(config, {
1646
+ headers: Object.keys(eventSourceHeaders).length ? eventSourceHeaders : void 0,
1647
+ withCredentials: eventSourceWithCredentials
1648
+ }) }), events = connectEventSource(initEventSource, [
1649
+ "message",
1650
+ "restart",
1651
+ "welcome",
1652
+ "reconnect",
1653
+ "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(() => {
1655
+ throw err;
1656
+ }))), map$1((event) => {
1657
+ if (event.type === "message") {
1658
+ let { data, ...rest } = event;
1659
+ return {
1660
+ ...rest,
1661
+ tags: data.tags
1662
+ };
1663
+ }
1664
+ return event;
1665
+ })).pipe(finalize$1(() => {
1666
+ transportCache.delete(cacheKey), transportCache.size === 0 && eventsCache.delete(config.resolveFetch);
1667
+ }), shareReplayLatest({ predicate: (event) => event.type === "welcome" }));
1668
+ return transportCache.set(cacheKey, observable), observable;
1669
+ }
1670
+ };
1671
+ /**
1672
+ * Probes the `/check/cors` endpoint to confirm whether the current origin is
1673
+ * allowed by the project's CORS configuration. EventSource failures are opaque,
1674
+ * so we use this side-channel purely to tell "the server actively rejected our
1675
+ * origin" apart from every other class of failure.
1676
+ *
1677
+ * Errors with `CorsOriginError` when either:
1678
+ *
1679
+ * - `requireCredentials` is `true` (the EventSource was about to send
1680
+ * credentials) and `/check/cors` reports `result.withCredentials === false`.
1681
+ * The credentialed request would fail due to a missing
1682
+ * `access-control-allow-credentials` header. The resulting error carries
1683
+ * `credentials: true` so its `addOriginUrl` deep-link pre-selects the
1684
+ * "Allow credentials" toggle in the Sanity management form.
1685
+ * - `/check/cors` reports `result.allowed === false` (origin is not on the
1686
+ * project's CORS allow-list). The error carries `credentials: requireCredentials`
1687
+ * so the deep-link still pre-selects credentials when the caller needed them.
1688
+ *
1689
+ * Every other outcome is intentionally treated as "we don't know": the
1690
+ * observable emits a single `void` value and then completes, so downstream
1691
+ * `mergeMap(() => ...)` consumers can continue. No error is surfaced for any
1692
+ * of these cases:
1693
+ *
1694
+ * - `allowed: true` (with credentials satisfied if required) or an
1695
+ * unrecognised body shape: the server did not confirm a CORS rejection.
1696
+ * - Non-2xx HTTP response from `/check/cors`: same - no signal either way, and
1697
+ * a 5xx on the probe shouldn't poison the EventSource's original error.
1698
+ * - `fetch` / network / JSON parse failures: indistinguishable from ordinary
1699
+ * connectivity hiccups (offline, DNS, certs, transient outages). Reporting
1700
+ * those as CORS errors is exactly the false-positive class this helper
1701
+ * exists to prevent.
1702
+ * - The subscription was aborted: nothing to emit and nothing to complete.
1703
+ *
1704
+ * In all of those cases the caller's original underlying error from the
1705
+ * EventSource is allowed to propagate unchanged.
1706
+ */
1707
+ function checkCorsObservable(url, projectId, requireCredentials) {
1708
+ return new Observable((observer) => {
1709
+ let controller = new AbortController(), { signal } = controller;
1710
+ return fetch(url, {
1711
+ method: "GET",
1712
+ mode: "cors",
1713
+ credentials: "omit",
1714
+ signal
1715
+ }).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();
1734
+ }
1735
+ }).catch(() => {
1736
+ signal.aborted || observer.closed || (observer.next(), observer.complete());
1737
+ }), () => controller.abort();
1738
+ });
1739
+ }
1740
+ /**
1741
+ * Cached observables capture their transport (`initEventSource` closes over
1742
+ * `config.resolveFetch` and `config.proxy`), so the cache is scoped per
1743
+ * resolver — `undefined` covers the `globalThis.fetch` fallback.
1744
+ */
1745
+ const eventsCache = /* @__PURE__ */ new Map();
1746
+ /** @internal */
1747
+ var ObservableDatasetsClient = class {
1748
+ #client;
1749
+ #httpRequest;
1750
+ constructor(client, httpRequest) {
1751
+ this.#client = client, this.#httpRequest = httpRequest;
1752
+ }
1753
+ /**
1754
+ * Create a new dataset with the given name
1755
+ *
1756
+ * @param name - Name of the dataset to create
1757
+ * @param options - Options for the dataset, including optional embeddings configuration
1758
+ */
1759
+ create(name, options) {
1760
+ return _modifyObservable(this.#client, this.#httpRequest, "PUT", name, options);
1761
+ }
1762
+ /**
1763
+ * Edit a dataset with the given name
1764
+ *
1765
+ * @param name - Name of the dataset to edit
1766
+ * @param options - New options for the dataset
1767
+ */
1768
+ edit(name, options) {
1769
+ return _modifyObservable(this.#client, this.#httpRequest, "PATCH", name, options);
1770
+ }
1771
+ /**
1772
+ * Delete a dataset with the given name
1773
+ *
1774
+ * @param name - Name of the dataset to delete
1775
+ */
1776
+ delete(name) {
1777
+ return _modifyObservable(this.#client, this.#httpRequest, "DELETE", name);
1778
+ }
1779
+ /**
1780
+ * Fetch a list of datasets for the configured project
1781
+ */
1782
+ list() {
1783
+ resourceGuard("dataset", this.#client.config());
1784
+ let config = this.#client.config(), projectId = config.projectId, url = "/datasets";
1785
+ return config.useProjectHostname === !1 && (url = `/projects/${projectId}/datasets`), _requestObservable(this.#client, this.#httpRequest, {
1786
+ url,
1787
+ tag: null
1788
+ });
1789
+ }
1790
+ /**
1791
+ * Get embeddings settings for a dataset
1792
+ *
1793
+ * @param name - Name of the dataset
1794
+ */
1795
+ getEmbeddingsSettings(name) {
1796
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _requestObservable(this.#client, this.#httpRequest, {
1797
+ url: _embeddingsSettingsUri(this.#client, name),
1798
+ tag: null
1799
+ });
1800
+ }
1801
+ /**
1802
+ * Edit embeddings settings for a dataset
1803
+ *
1804
+ * @param name - Name of the dataset
1805
+ * @param settings - Embeddings settings to apply
1806
+ */
1807
+ editEmbeddingsSettings(name, settings) {
1808
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _requestObservable(this.#client, this.#httpRequest, {
1809
+ method: "PUT",
1810
+ url: _embeddingsSettingsUri(this.#client, name),
1811
+ body: settings,
1812
+ tag: null
1813
+ });
1814
+ }
1815
+ }, DatasetsClient = class {
1816
+ #client;
1817
+ #httpRequest;
1818
+ constructor(client, httpRequest) {
1819
+ this.#client = client, this.#httpRequest = httpRequest;
1820
+ }
1821
+ /**
1822
+ * Create a new dataset with the given name
1823
+ *
1824
+ * @param name - Name of the dataset to create
1825
+ * @param options - Options for the dataset, including optional embeddings configuration
1826
+ */
1827
+ create(name, options) {
1828
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "PUT", name, options);
1829
+ }
1830
+ /**
1831
+ * Edit a dataset with the given name
1832
+ *
1833
+ * @param name - Name of the dataset to edit
1834
+ * @param options - New options for the dataset
1835
+ */
1836
+ edit(name, options) {
1837
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "PATCH", name, options);
1838
+ }
1839
+ /**
1840
+ * Delete a dataset with the given name
1841
+ *
1842
+ * @param name - Name of the dataset to delete
1843
+ */
1844
+ delete(name) {
1845
+ return resourceGuard("dataset", this.#client.config()), _modify(this.#client, this.#httpRequest, "DELETE", name);
1846
+ }
1847
+ /**
1848
+ * Fetch a list of datasets for the configured project
1849
+ */
1850
+ list() {
1851
+ resourceGuard("dataset", this.#client.config());
1852
+ let config = this.#client.config(), projectId = config.projectId, url = "/datasets";
1853
+ return config.useProjectHostname === !1 && (url = `/projects/${projectId}/datasets`), _request(this.#client, this.#httpRequest, {
1854
+ url,
1855
+ tag: null
1856
+ });
1857
+ }
1858
+ /**
1859
+ * Get embeddings settings for a dataset
1860
+ *
1861
+ * @param name - Name of the dataset
1862
+ */
1863
+ getEmbeddingsSettings(name) {
1864
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _request(this.#client, this.#httpRequest, {
1865
+ url: _embeddingsSettingsUri(this.#client, name),
1866
+ tag: null
1867
+ });
1868
+ }
1869
+ /**
1870
+ * Edit embeddings settings for a dataset
1871
+ *
1872
+ * @param name - Name of the dataset
1873
+ * @param settings - Embeddings settings to apply
1874
+ */
1875
+ editEmbeddingsSettings(name, settings) {
1876
+ return resourceGuard("dataset", this.#client.config()), dataset(name), _request(this.#client, this.#httpRequest, {
1877
+ method: "PUT",
1878
+ url: _embeddingsSettingsUri(this.#client, name),
1879
+ body: settings,
1880
+ tag: null
1881
+ });
1882
+ }
1883
+ };
1884
+ function _embeddingsSettingsUri(client, name) {
1885
+ let config = client.config();
1886
+ return config.useProjectHostname === !1 ? `/projects/${config.projectId}/datasets/${name}/settings/embeddings` : `/datasets/${name}/settings/embeddings`;
1887
+ }
1888
+ function _modifyObservable(client, httpRequest, method, name, options) {
1889
+ return resourceGuard("dataset", client.config()), dataset(name), _requestObservable(client, httpRequest, {
1890
+ method,
1891
+ url: `/datasets/${name}`,
1892
+ body: options,
1893
+ tag: null
1894
+ });
1895
+ }
1896
+ function _modify(client, httpRequest, method, name, options) {
1897
+ return resourceGuard("dataset", client.config()), dataset(name), _request(client, httpRequest, {
1898
+ method,
1899
+ url: `/datasets/${name}`,
1900
+ body: options,
1901
+ tag: null
1902
+ });
1903
+ }
1904
+ /** @internal */
1905
+ var ObservableMediaLibraryVideoClient = class {
1906
+ #client;
1907
+ #httpRequest;
1908
+ constructor(client, httpRequest) {
1909
+ this.#client = client, this.#httpRequest = httpRequest;
1910
+ }
1911
+ /**
1912
+ * Get video playback information for a media library asset
1913
+ *
1914
+ * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
1915
+ * @param options - Options for transformations and expiration
1916
+ */
1917
+ getPlaybackInfo(assetIdentifier, options = {}) {
1918
+ let config = this.#client.config(), configMediaLibraryId = (config.resource || config["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
1919
+ if (!effectiveLibraryId) throw Error("Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR");
1920
+ let url = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId), queryParams = buildQueryParams(options);
1921
+ return _requestObservable(this.#client, this.#httpRequest, {
1922
+ method: "GET",
1923
+ url,
1924
+ query: queryParams
1925
+ });
1926
+ }
1927
+ }, MediaLibraryVideoClient = class {
1928
+ #client;
1929
+ #httpRequest;
1930
+ constructor(client, httpRequest) {
1931
+ this.#client = client, this.#httpRequest = httpRequest;
1932
+ }
1933
+ /**
1934
+ * Get video playback information for a media library asset
1935
+ *
1936
+ * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
1937
+ * @param options - Options for transformations and expiration
1938
+ */
1939
+ getPlaybackInfo(assetIdentifier, options = {}) {
1940
+ let config = this.#client.config(), configMediaLibraryId = (config.resource || config["~experimental_resource"])?.id, { instanceId, libraryId } = parseAssetInstanceId(assetIdentifier), effectiveLibraryId = libraryId || configMediaLibraryId;
1941
+ if (!effectiveLibraryId) throw Error("Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR");
1942
+ let url = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId), queryParams = buildQueryParams(options);
1943
+ return _request(this.#client, this.#httpRequest, {
1944
+ method: "GET",
1945
+ url,
1946
+ query: queryParams
1947
+ });
1948
+ }
1949
+ };
1950
+ const ML_GDR_PATTERN = /^media-library:(ml[^:]+):([^:]+)$/;
1951
+ /** @internal */
1952
+ function isSanityReference(assetIdentifier) {
1953
+ return typeof assetIdentifier == "object" && "_ref" in assetIdentifier;
1954
+ }
1955
+ /**
1956
+ * Parse the asset instance id and library id from the asset identifier
1957
+ *
1958
+ * @param assetIdentifier - The asset identifier - either a asset instance id or a Media Library GDR
1959
+ * @returns The asset instance id and library id
1960
+ */
1961
+ function parseAssetInstanceId(assetIdentifier) {
1962
+ let ref = isSanityReference(assetIdentifier) ? assetIdentifier._ref : assetIdentifier, match = ML_GDR_PATTERN.exec(ref);
1963
+ if (match) {
1964
+ let [, libraryId, instanceId] = match;
1965
+ return {
1966
+ libraryId,
1967
+ instanceId
1968
+ };
1969
+ }
1970
+ if (typeof assetIdentifier == "string" && assetIdentifier.startsWith("video-")) return { instanceId: assetIdentifier };
1971
+ throw Error(`Invalid video asset instance identifier "${ref}": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`);
1972
+ }
1973
+ function buildVideoPlaybackInfoUrl(instanceId, libraryId) {
1974
+ return `/media-libraries/${libraryId}/video/${instanceId}/playback-info`;
1975
+ }
1976
+ function buildQueryParams(options) {
1977
+ let params = {};
1978
+ if (options.transformations) {
1979
+ let { thumbnail, animated, storyboard } = options.transformations;
1980
+ thumbnail && (thumbnail.width && (params.thumbnailWidth = thumbnail.width), thumbnail.height && (params.thumbnailHeight = thumbnail.height), thumbnail.time !== void 0 && (params.thumbnailTime = thumbnail.time), thumbnail.fit && (params.thumbnailFit = thumbnail.fit), thumbnail.format && (params.thumbnailFormat = thumbnail.format)), animated && (animated.width && (params.animatedWidth = animated.width), animated.height && (params.animatedHeight = animated.height), animated.start !== void 0 && (params.animatedStart = animated.start), animated.end !== void 0 && (params.animatedEnd = animated.end), animated.fps && (params.animatedFps = animated.fps), animated.format && (params.animatedFormat = animated.format)), storyboard && storyboard.format && (params.storyboardFormat = storyboard.format);
1981
+ }
1982
+ return options.expiration && (params.expiration = options.expiration), params;
1983
+ }
1984
+ /** @internal */
1985
+ var ObservableProjectsClient = class {
1986
+ #client;
1987
+ #httpRequest;
1988
+ constructor(client, httpRequest) {
1989
+ this.#client = client, this.#httpRequest = httpRequest;
1990
+ }
1991
+ /**
1992
+ * Fetch a list of projects the authenticated user has access to.
1993
+ *
1994
+ * @param options - Options for the list request
1995
+ * - `includeMembers` - Whether to include members in the response (default: true)
1996
+ * - `includeFeatures` - Whether to include features in the response (default: true)
1997
+ * - `organizationId` - ID of the organization to fetch projects for
1998
+ * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
1999
+ */
2000
+ list(options) {
2001
+ let query = {};
2002
+ return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), _requestObservable(this.#client, this.#httpRequest, {
2003
+ url: "/projects",
2004
+ query
2005
+ });
2006
+ }
2007
+ /**
2008
+ * Fetch a project by project ID
2009
+ *
2010
+ * @param projectId - ID of the project to fetch
2011
+ */
2012
+ getById(projectId) {
2013
+ return _requestObservable(this.#client, this.#httpRequest, { url: `/projects/${projectId}` });
2014
+ }
2015
+ }, ProjectsClient = class {
2016
+ #client;
2017
+ #httpRequest;
2018
+ constructor(client, httpRequest) {
2019
+ this.#client = client, this.#httpRequest = httpRequest;
2020
+ }
2021
+ /**
2022
+ * Fetch a list of projects the authenticated user has access to.
2023
+ *
2024
+ * @param options - Options for the list request
2025
+ * - `includeMembers` - Whether to include members in the response (default: true)
2026
+ * - `includeFeatures` - Whether to include features in the response (default: true)
2027
+ * - `organizationId` - ID of the organization to fetch projects for
2028
+ * - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
2029
+ */
2030
+ list(options) {
2031
+ let query = {};
2032
+ return options?.includeMembers === !1 && (query.includeMembers = "false"), options?.includeFeatures === !1 && (query.includeFeatures = "false"), options?.organizationId && (query.organizationId = options.organizationId), options?.onlyExplicitMembership && (query.onlyExplicitMembership = "true"), _request(this.#client, this.#httpRequest, {
2033
+ url: "/projects",
2034
+ query
2035
+ });
2036
+ }
2037
+ /**
2038
+ * Fetch a project by project ID
2039
+ *
2040
+ * @param projectId - ID of the project to fetch
2041
+ */
2042
+ getById(projectId) {
2043
+ return _request(this.#client, this.#httpRequest, { url: `/projects/${projectId}` });
2044
+ }
2045
+ };
2046
+ /**
2047
+ * @internal
2048
+ *
2049
+ * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.
2050
+ */
2051
+ const generateReleaseId = customAlphabet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 8), getDocumentVersionId = (publishedId, releaseId) => releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId);
2052
+ /** @internal */
2053
+ function deriveDocumentVersionId(op, { releaseId, publishedId, document }) {
2054
+ if (publishedId && document._id) {
2055
+ let versionId = getDocumentVersionId(publishedId, releaseId);
2056
+ return validateVersionIdMatch(versionId, document), versionId;
2057
+ }
2058
+ if (document._id) {
2059
+ let isDraft = isDraftId(document._id), isVersion = isVersionId(document._id);
2060
+ if (!isDraft && !isVersion) throw Error(`\`${op}()\` requires a document with an \`_id\` that is a version or draft ID`);
2061
+ if (releaseId) {
2062
+ if (isDraft) throw Error(`\`${op}()\` was called with a document ID (\`${document._id}\`) that is a draft ID, but a release ID (\`${releaseId}\`) was also provided.`);
2063
+ let builtVersionId = getVersionFromId(document._id);
2064
+ if (builtVersionId !== releaseId) throw Error(`\`${op}()\` was called with a document ID (\`${document._id}\`) that is a version ID, but the release ID (\`${releaseId}\`) does not match the document's version ID (\`${builtVersionId}\`).`);
2065
+ }
2066
+ return document._id;
2067
+ }
2068
+ if (publishedId) return getDocumentVersionId(publishedId, releaseId);
2069
+ throw Error(`\`${op}()\` requires either a publishedId or a document with an \`_id\``);
2070
+ }
2071
+ const getArgs = (releaseOrOptions, maybeOptions) => {
2072
+ if (typeof releaseOrOptions == "object" && releaseOrOptions && ("releaseId" in releaseOrOptions || "metadata" in releaseOrOptions)) {
2073
+ let { releaseId = generateReleaseId(), metadata = {} } = releaseOrOptions;
2074
+ return [
2075
+ releaseId,
2076
+ metadata,
2077
+ maybeOptions
2078
+ ];
2079
+ }
2080
+ return [
2081
+ generateReleaseId(),
2082
+ {},
2083
+ releaseOrOptions
2084
+ ];
2085
+ }, createRelease = (releaseOrOptions, maybeOptions) => {
2086
+ let [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions);
2087
+ return {
2088
+ action: {
2089
+ actionType: "sanity.action.release.create",
2090
+ releaseId,
2091
+ metadata: {
2092
+ ...metadata,
2093
+ releaseType: metadata.releaseType || "undecided"
2094
+ }
2095
+ },
2096
+ options
2097
+ };
2098
+ };
2099
+ /** @public */
2100
+ var ObservableReleasesClient = class {
2101
+ #client;
2102
+ #httpRequest;
2103
+ constructor(client, httpRequest) {
2104
+ this.#client = client, this.#httpRequest = httpRequest;
2105
+ }
2106
+ /**
2107
+ * @public
2108
+ *
2109
+ * Retrieve a release by id.
2110
+ *
2111
+ * @category Releases
2112
+ *
2113
+ * @param params - Release action parameters:
2114
+ * - `releaseId` - The id of the release to retrieve.
2115
+ * @param options - Additional query options including abort signal and query tag.
2116
+ * @returns An observable that resolves to the release document {@link ReleaseDocument}.
2117
+ *
2118
+ * @example Retrieving a release by id
2119
+ * ```ts
2120
+ * client.observable.releases.get({releaseId: 'my-release'}).pipe(
2121
+ * tap((release) => console.log(release)),
2122
+ * // {
2123
+ * // _id: '_.releases.my-release',
2124
+ * // name: 'my-release'
2125
+ * // _type: 'system.release',
2126
+ * // metadata: {releaseType: 'asap'},
2127
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
2128
+ * // ...
2129
+ * // }
2130
+ * ).subscribe()
2131
+ * ```
2132
+ */
2133
+ get({ releaseId }, options) {
2134
+ return _getDocumentObservable(this.#client, this.#httpRequest, `_.releases.${releaseId}`, options);
2135
+ }
2136
+ create(releaseOrOptions, maybeOptions) {
2137
+ let { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
2138
+ return _actionObservable(this.#client, this.#httpRequest, action, options).pipe(map((actionResult) => ({
2139
+ ...actionResult,
2140
+ releaseId,
2141
+ metadata
2142
+ })));
2143
+ }
2144
+ /**
2145
+ * @public
2146
+ *
2147
+ * Edits an existing release, updating the metadata.
2148
+ *
2149
+ * @category Releases
2150
+ *
2151
+ * @param params - Release action parameters:
2152
+ * - `releaseId` - The id of the release to edit.
2153
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
2154
+ * @param options - Additional action options.
2155
+ * @returns An observable that resolves to the `transactionId`.
2156
+ */
2157
+ edit({ releaseId, patch }, options) {
2158
+ let editAction = {
2159
+ actionType: "sanity.action.release.edit",
2160
+ releaseId,
2161
+ patch
2162
+ };
2163
+ return _actionObservable(this.#client, this.#httpRequest, editAction, options);
2164
+ }
2165
+ /**
2166
+ * @public
2167
+ *
2168
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
2169
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
2170
+ * documents and creation of the corresponding published documents with the new content may
2171
+ * take some time.
2172
+ *
2173
+ * During this period both the source and target documents are locked and cannot be
2174
+ * modified through any other means.
2175
+ *
2176
+ * @category Releases
2177
+ *
2178
+ * @param params - Release action parameters:
2179
+ * - `releaseId` - The id of the release to publish.
2180
+ * @param options - Additional action options.
2181
+ * @returns An observable that resolves to the `transactionId`.
2182
+ */
2183
+ publish({ releaseId }, options) {
2184
+ let publishAction = {
2185
+ actionType: "sanity.action.release.publish",
2186
+ releaseId
2187
+ };
2188
+ return _actionObservable(this.#client, this.#httpRequest, publishAction, options);
2189
+ }
2190
+ /**
2191
+ * @public
2192
+ *
2193
+ * An archive action removes an active release. The documents that comprise the release
2194
+ * are deleted and therefore no longer queryable.
2195
+ *
2196
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
2197
+ *
2198
+ * @category Releases
2199
+ *
2200
+ * @param params - Release action parameters:
2201
+ * - `releaseId` - The id of the release to archive.
2202
+ * @param options - Additional action options.
2203
+ * @returns An observable that resolves to the `transactionId`.
2204
+ */
2205
+ archive({ releaseId }, options) {
2206
+ let archiveAction = {
2207
+ actionType: "sanity.action.release.archive",
2208
+ releaseId
2209
+ };
2210
+ return _actionObservable(this.#client, this.#httpRequest, archiveAction, options);
2211
+ }
2212
+ /**
2213
+ * @public
2214
+ *
2215
+ * An unarchive action restores an archived release and all documents
2216
+ * with the content they had just prior to archiving.
2217
+ *
2218
+ * @category Releases
2219
+ *
2220
+ * @param params - Release action parameters:
2221
+ * - `releaseId` - The id of the release to unarchive.
2222
+ * @param options - Additional action options.
2223
+ * @returns An observable that resolves to the `transactionId`.
2224
+ */
2225
+ unarchive({ releaseId }, options) {
2226
+ let unarchiveAction = {
2227
+ actionType: "sanity.action.release.unarchive",
2228
+ releaseId
2229
+ };
2230
+ return _actionObservable(this.#client, this.#httpRequest, unarchiveAction, options);
2231
+ }
2232
+ /**
2233
+ * @public
2234
+ *
2235
+ * A schedule action queues a release for publishing at the given future time.
2236
+ * The release is locked such that no documents in the release can be modified and
2237
+ * no documents that it references can be deleted as this would make the publish fail.
2238
+ * At the given time, the same logic as for the publish action is triggered.
2239
+ *
2240
+ * @category Releases
2241
+ *
2242
+ * @param params - Release action parameters:
2243
+ * - `releaseId` - The id of the release to schedule.
2244
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
2245
+ * @param options - Additional action options.
2246
+ * @returns An observable that resolves to the `transactionId`.
2247
+ */
2248
+ schedule({ releaseId, publishAt }, options) {
2249
+ let scheduleAction = {
2250
+ actionType: "sanity.action.release.schedule",
2251
+ releaseId,
2252
+ publishAt
2253
+ };
2254
+ return _actionObservable(this.#client, this.#httpRequest, scheduleAction, options);
2255
+ }
2256
+ /**
2257
+ * @public
2258
+ *
2259
+ * An unschedule action stops a release from being published.
2260
+ * The documents in the release are considered unlocked and can be edited again.
2261
+ * This may fail if another release is scheduled to be published after this one and
2262
+ * has a reference to a document created by this one.
2263
+ *
2264
+ * @category Releases
2265
+ *
2266
+ * @param params - Release action parameters:
2267
+ * - `releaseId` - The id of the release to unschedule.
2268
+ * @param options - Additional action options.
2269
+ * @returns An observable that resolves to the `transactionId`.
2270
+ */
2271
+ unschedule({ releaseId }, options) {
2272
+ let unscheduleAction = {
2273
+ actionType: "sanity.action.release.unschedule",
2274
+ releaseId
2275
+ };
2276
+ return _actionObservable(this.#client, this.#httpRequest, unscheduleAction, options);
2277
+ }
2278
+ /**
2279
+ * @public
2280
+ *
2281
+ * A delete action removes a published or archived release.
2282
+ * The backing system document will be removed from the dataset.
2283
+ *
2284
+ * @category Releases
2285
+ *
2286
+ * @param params - Release action parameters:
2287
+ * - `releaseId` - The id of the release to delete.
2288
+ * @param options - Additional action options.
2289
+ * @returns An observable that resolves to the `transactionId`.
2290
+ */
2291
+ delete({ releaseId }, options) {
2292
+ let deleteAction = {
2293
+ actionType: "sanity.action.release.delete",
2294
+ releaseId
2295
+ };
2296
+ return _actionObservable(this.#client, this.#httpRequest, deleteAction, options);
2297
+ }
2298
+ /**
2299
+ * @public
2300
+ *
2301
+ * Fetch the documents in a release by release id.
2302
+ *
2303
+ * @category Releases
2304
+ *
2305
+ * @param params - Release action parameters:
2306
+ * - `releaseId` - The id of the release to fetch documents for.
2307
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
2308
+ * @returns An observable that resolves to the documents in the release.
2309
+ */
2310
+ fetchDocuments({ releaseId }, options) {
2311
+ return _getReleaseDocumentsObservable(this.#client, this.#httpRequest, releaseId, options);
2312
+ }
2313
+ }, ReleasesClient = class {
2314
+ #client;
2315
+ #httpRequest;
2316
+ constructor(client, httpRequest) {
2317
+ this.#client = client, this.#httpRequest = httpRequest;
2318
+ }
2319
+ /**
2320
+ * @public
2321
+ *
2322
+ * Retrieve a release by id.
2323
+ *
2324
+ * @category Releases
2325
+ *
2326
+ * @param params - Release action parameters:
2327
+ * - `releaseId` - The id of the release to retrieve.
2328
+ * @param options - Additional query options including abort signal and query tag.
2329
+ * @returns A promise that resolves to the release document {@link ReleaseDocument}.
2330
+ *
2331
+ * @example Retrieving a release by id
2332
+ * ```ts
2333
+ * const release = await client.releases.get({releaseId: 'my-release'})
2334
+ * console.log(release)
2335
+ * // {
2336
+ * // _id: '_.releases.my-release',
2337
+ * // name: 'my-release'
2338
+ * // _type: 'system.release',
2339
+ * // metadata: {releaseType: 'asap'},
2340
+ * // _createdAt: '2021-01-01T00:00:00.000Z',
2341
+ * // ...
2342
+ * // }
2343
+ * ```
2344
+ */
2345
+ get({ releaseId }, options) {
2346
+ return _getDocument(this.#client, this.#httpRequest, `_.releases.${releaseId}`, options);
2347
+ }
2348
+ async create(releaseOrOptions, maybeOptions) {
2349
+ let { action, options } = createRelease(releaseOrOptions, maybeOptions), { releaseId, metadata } = action;
2350
+ return {
2351
+ ...await _action(this.#client, this.#httpRequest, action, options),
2352
+ releaseId,
2353
+ metadata
2354
+ };
2355
+ }
2356
+ /**
2357
+ * @public
2358
+ *
2359
+ * Edits an existing release, updating the metadata.
2360
+ *
2361
+ * @category Releases
2362
+ *
2363
+ * @param params - Release action parameters:
2364
+ * - `releaseId` - The id of the release to edit.
2365
+ * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
2366
+ * @param options - Additional action options.
2367
+ * @returns A promise that resolves to the `transactionId`.
2368
+ */
2369
+ edit({ releaseId, patch }, options) {
2370
+ let editAction = {
2371
+ actionType: "sanity.action.release.edit",
2372
+ releaseId,
2373
+ patch
2374
+ };
2375
+ return _action(this.#client, this.#httpRequest, editAction, options);
2376
+ }
2377
+ /**
2378
+ * @public
2379
+ *
2380
+ * Publishes all documents in a release at once. For larger releases the effect of the publish
2381
+ * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
2382
+ * documents and creation of the corresponding published documents with the new content may
2383
+ * take some time.
2384
+ *
2385
+ * During this period both the source and target documents are locked and cannot be
2386
+ * modified through any other means.
2387
+ *
2388
+ * @category Releases
2389
+ *
2390
+ * @param params - Release action parameters:
2391
+ * - `releaseId` - The id of the release to publish.
2392
+ * @param options - Additional action options.
2393
+ * @returns A promise that resolves to the `transactionId`.
2394
+ */
2395
+ publish({ releaseId }, options) {
2396
+ let publishAction = {
2397
+ actionType: "sanity.action.release.publish",
2398
+ releaseId
2399
+ };
2400
+ return _action(this.#client, this.#httpRequest, publishAction, options);
2401
+ }
2402
+ /**
2403
+ * @public
2404
+ *
2405
+ * An archive action removes an active release. The documents that comprise the release
2406
+ * are deleted and therefore no longer queryable.
2407
+ *
2408
+ * While the documents remain in retention the last version can still be accessed using document history endpoint.
2409
+ *
2410
+ * @category Releases
2411
+ *
2412
+ * @param params - Release action parameters:
2413
+ * - `releaseId` - The id of the release to archive.
2414
+ * @param options - Additional action options.
2415
+ * @returns A promise that resolves to the `transactionId`.
2416
+ */
2417
+ archive({ releaseId }, options) {
2418
+ let archiveAction = {
2419
+ actionType: "sanity.action.release.archive",
2420
+ releaseId
2421
+ };
2422
+ return _action(this.#client, this.#httpRequest, archiveAction, options);
2423
+ }
2424
+ /**
2425
+ * @public
2426
+ *
2427
+ * An unarchive action restores an archived release and all documents
2428
+ * with the content they had just prior to archiving.
2429
+ *
2430
+ * @category Releases
2431
+ *
2432
+ * @param params - Release action parameters:
2433
+ * - `releaseId` - The id of the release to unarchive.
2434
+ * @param options - Additional action options.
2435
+ * @returns A promise that resolves to the `transactionId`.
2436
+ */
2437
+ unarchive({ releaseId }, options) {
2438
+ let unarchiveAction = {
2439
+ actionType: "sanity.action.release.unarchive",
2440
+ releaseId
2441
+ };
2442
+ return _action(this.#client, this.#httpRequest, unarchiveAction, options);
2443
+ }
2444
+ /**
2445
+ * @public
2446
+ *
2447
+ * A schedule action queues a release for publishing at the given future time.
2448
+ * The release is locked such that no documents in the release can be modified and
2449
+ * no documents that it references can be deleted as this would make the publish fail.
2450
+ * At the given time, the same logic as for the publish action is triggered.
2451
+ *
2452
+ * @category Releases
2453
+ *
2454
+ * @param params - Release action parameters:
2455
+ * - `releaseId` - The id of the release to schedule.
2456
+ * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
2457
+ * @param options - Additional action options.
2458
+ * @returns A promise that resolves to the `transactionId`.
2459
+ */
2460
+ schedule({ releaseId, publishAt }, options) {
2461
+ let scheduleAction = {
2462
+ actionType: "sanity.action.release.schedule",
2463
+ releaseId,
2464
+ publishAt
2465
+ };
2466
+ return _action(this.#client, this.#httpRequest, scheduleAction, options);
2467
+ }
2468
+ /**
2469
+ * @public
2470
+ *
2471
+ * An unschedule action stops a release from being published.
2472
+ * The documents in the release are considered unlocked and can be edited again.
2473
+ * This may fail if another release is scheduled to be published after this one and
2474
+ * has a reference to a document created by this one.
2475
+ *
2476
+ * @category Releases
2477
+ *
2478
+ * @param params - Release action parameters:
2479
+ * - `releaseId` - The id of the release to unschedule.
2480
+ * @param options - Additional action options.
2481
+ * @returns A promise that resolves to the `transactionId`.
2482
+ */
2483
+ unschedule({ releaseId }, options) {
2484
+ let unscheduleAction = {
2485
+ actionType: "sanity.action.release.unschedule",
2486
+ releaseId
2487
+ };
2488
+ return _action(this.#client, this.#httpRequest, unscheduleAction, options);
2489
+ }
2490
+ /**
2491
+ * @public
2492
+ *
2493
+ * A delete action removes a published or archived release.
2494
+ * The backing system document will be removed from the dataset.
2495
+ *
2496
+ * @category Releases
2497
+ *
2498
+ * @param params - Release action parameters:
2499
+ * - `releaseId` - The id of the release to delete.
2500
+ * @param options - Additional action options.
2501
+ * @returns A promise that resolves to the `transactionId`.
2502
+ */
2503
+ delete({ releaseId }, options) {
2504
+ let deleteAction = {
2505
+ actionType: "sanity.action.release.delete",
2506
+ releaseId
2507
+ };
2508
+ return _action(this.#client, this.#httpRequest, deleteAction, options);
2509
+ }
2510
+ /**
2511
+ * @public
2512
+ *
2513
+ * Fetch the documents in a release by release id.
2514
+ *
2515
+ * @category Releases
2516
+ *
2517
+ * @param params - Release action parameters:
2518
+ * - `releaseId` - The id of the release to fetch documents for.
2519
+ * @param options - Additional mutation options {@link BaseMutationOptions}.
2520
+ * @returns A promise that resolves to the documents in the release.
2521
+ */
2522
+ fetchDocuments({ releaseId }, options) {
2523
+ return _getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options);
2524
+ }
2525
+ }, ObservableUsersClient = class {
2526
+ #client;
2527
+ #httpRequest;
2528
+ constructor(client, httpRequest) {
2529
+ this.#client = client, this.#httpRequest = httpRequest;
2530
+ }
2531
+ /**
2532
+ * Fetch a user by user ID
2533
+ *
2534
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2535
+ */
2536
+ getById(id) {
2537
+ return _requestObservable(this.#client, this.#httpRequest, { url: `/users/${id}` });
2538
+ }
2539
+ }, UsersClient = class {
2540
+ #client;
2541
+ #httpRequest;
2542
+ constructor(client, httpRequest) {
2543
+ this.#client = client, this.#httpRequest = httpRequest;
2544
+ }
2545
+ /**
2546
+ * Fetch a user by user ID
2547
+ *
2548
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2549
+ */
2550
+ getById(id) {
2551
+ return _request(this.#client, this.#httpRequest, { url: `/users/${id}` });
2552
+ }
2553
+ }, ObservableSanityClient = class ObservableSanityClient {
2554
+ assets;
2555
+ datasets;
2556
+ live;
2557
+ mediaLibrary;
2558
+ projects;
2559
+ users;
2560
+ agent;
2561
+ releases;
2562
+ /**
2563
+ * Private properties
2564
+ */
2565
+ #clientConfig;
2566
+ #httpRequest;
2567
+ /**
2568
+ * Instance properties
2569
+ */
2570
+ listen = _listen;
2571
+ 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);
2573
+ }
2574
+ /**
2575
+ * Clone the client - returns a new instance
2576
+ */
2577
+ clone() {
2578
+ return new ObservableSanityClient(this.#httpRequest, this.config());
2579
+ }
2580
+ config(newConfig) {
2581
+ if (newConfig === void 0) return { ...this.#clientConfig };
2582
+ if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1) throw Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
2583
+ return this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;
2584
+ }
2585
+ /**
2586
+ * Clone the client with a new (partial) configuration.
2587
+ *
2588
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2589
+ */
2590
+ withConfig(newConfig) {
2591
+ let thisConfig = this.config();
2592
+ return new ObservableSanityClient(this.#httpRequest, {
2593
+ ...thisConfig,
2594
+ ...newConfig,
2595
+ stega: {
2596
+ ...thisConfig.stega,
2597
+ ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2598
+ }
2599
+ });
2600
+ }
2601
+ fetch(query, params, options) {
2602
+ return _fetchObservable(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
2603
+ }
2604
+ getDocument(id, options) {
2605
+ if (options?.includeAllVersions === !0) return _getDocumentObservable(this, this.#httpRequest, id, {
2606
+ ...options,
2607
+ includeAllVersions: !0
2608
+ });
2609
+ let opts = {
2610
+ signal: options?.signal,
2611
+ tag: options?.tag,
2612
+ releaseId: options?.releaseId,
2613
+ ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2614
+ };
2615
+ return _getDocumentObservable(this, this.#httpRequest, id, opts);
2616
+ }
2617
+ /**
2618
+ * Fetch multiple documents in one request.
2619
+ * Should be used sparingly - performing a query is usually a better option.
2620
+ * The order/position of documents is preserved based on the original array of IDs.
2621
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2622
+ *
2623
+ * @param ids - Document IDs to fetch
2624
+ * @param options - Request options
2625
+ */
2626
+ getDocuments(ids, options) {
2627
+ return _getDocumentsObservable(this, this.#httpRequest, ids, options);
2628
+ }
2629
+ /**
2630
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2631
+ * Returns a set of the IDs that exist.
2632
+ *
2633
+ * @param ids - Document IDs to check
2634
+ * @param options - Request options
2635
+ */
2636
+ documentsExists(ids, options) {
2637
+ return _documentsExistsObservable(this, this.#httpRequest, ids, options);
2638
+ }
2639
+ create(document, options) {
2640
+ return _createObservable(this, this.#httpRequest, document, "create", options);
2641
+ }
2642
+ createIfNotExists(document, options) {
2643
+ return _createIfNotExistsObservable(this, this.#httpRequest, document, options);
2644
+ }
2645
+ createOrReplace(document, options) {
2646
+ return _createOrReplaceObservable(this, this.#httpRequest, document, options);
2647
+ }
2648
+ createVersion({ document, publishedId, releaseId, baseId, ifBaseRevisionId }, options) {
2649
+ if (!document) return _createVersionFromBaseObservable(this, this.#httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options);
2650
+ let documentVersionId = deriveDocumentVersionId("createVersion", {
2651
+ document,
2652
+ publishedId,
2653
+ releaseId
2654
+ }), documentVersion = {
2655
+ ...document,
2656
+ _id: documentVersionId
2657
+ }, versionPublishedId = publishedId || getPublishedId(document._id);
2658
+ return _createVersionObservable(this, this.#httpRequest, documentVersion, versionPublishedId, options);
2659
+ }
2660
+ delete(selection, options) {
2661
+ return _deleteObservable(this, this.#httpRequest, selection, options);
2662
+ }
2663
+ /**
2664
+ * @public
2665
+ *
2666
+ * Deletes the draft or release version of a document.
2667
+ *
2668
+ * @remarks
2669
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
2670
+ * * If the draft or release version does not exist, any error will throw.
2671
+ *
2672
+ * @param params - Version action parameters:
2673
+ * - `releaseId` - The ID of the release to discard the document from.
2674
+ * - `publishedId` - The published ID of the document to discard.
2675
+ * @param purge - if `true` the document history is also discarded.
2676
+ * @param options - Additional action options.
2677
+ * @returns an observable that resolves to the `transactionId`.
2678
+ *
2679
+ * @example Discarding a release version of a document
2680
+ * ```ts
2681
+ * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2682
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
2683
+ * ```
2684
+ *
2685
+ * @example Discarding a draft version of a document
2686
+ * ```ts
2687
+ * client.observable.discardVersion({publishedId: 'myDocument'})
2688
+ * // The document with the ID `drafts.myDocument` will be discarded.
2689
+ * ```
2690
+ */
2691
+ discardVersion({ releaseId, publishedId }, purge, options) {
2692
+ let documentVersionId = getDocumentVersionId(publishedId, releaseId);
2693
+ return _discardVersionObservable(this, this.#httpRequest, documentVersionId, purge, options);
2694
+ }
2695
+ replaceVersion({ document, publishedId, releaseId }, options) {
2696
+ let documentVersionId = deriveDocumentVersionId("replaceVersion", {
2697
+ document,
2698
+ publishedId,
2699
+ releaseId
2700
+ }), documentVersion = {
2701
+ ...document,
2702
+ _id: documentVersionId
2703
+ };
2704
+ return _replaceVersionObservable(this, this.#httpRequest, documentVersion, options);
2705
+ }
2706
+ /**
2707
+ * @public
2708
+ *
2709
+ * Used to indicate when a document within a release should be unpublished when
2710
+ * the release is run.
2711
+ *
2712
+ * @remarks
2713
+ * * If the published document does not exist, an error will be thrown.
2714
+ *
2715
+ * @param params - Version action parameters:
2716
+ * - `releaseId` - The ID of the release to unpublish the document from.
2717
+ * - `publishedId` - The published ID of the document to unpublish.
2718
+ * @param options - Additional action options.
2719
+ * @returns an observable that resolves to the `transactionId`.
2720
+ *
2721
+ * @example Unpublishing a release version of a published document
2722
+ * ```ts
2723
+ * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2724
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
2725
+ * ```
2726
+ */
2727
+ unpublishVersion({ releaseId, publishedId }, options) {
2728
+ let versionId = getVersionId(publishedId, releaseId);
2729
+ return _unpublishVersionObservable(this, this.#httpRequest, versionId, publishedId, options);
2730
+ }
2731
+ mutate(operations, options) {
2732
+ return _mutateObservable(this, this.#httpRequest, operations, options);
2733
+ }
2734
+ /**
2735
+ * Create a new buildable patch of operations to perform
2736
+ *
2737
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2738
+ * @param operations - Optional object of patch operations to initialize the patch instance with
2739
+ * @returns Patch instance - call `.commit()` to perform the operations defined
2740
+ */
2741
+ patch(selection, operations) {
2742
+ return new ObservablePatch(selection, operations, this);
2743
+ }
2744
+ /**
2745
+ * Create a new transaction of mutations
2746
+ *
2747
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
2748
+ */
2749
+ transaction(operations) {
2750
+ return new ObservableTransaction(operations, this);
2751
+ }
2752
+ /**
2753
+ * Perform action operations against the configured dataset
2754
+ *
2755
+ * @param operations - Action operation(s) to execute
2756
+ * @param options - Action options
2757
+ */
2758
+ action(operations, options) {
2759
+ return _actionObservable(this, this.#httpRequest, operations, options);
2760
+ }
2761
+ /**
2762
+ * Perform an HTTP request against the Sanity API
2763
+ *
2764
+ * @param options - Request options
2765
+ */
2766
+ request(options) {
2767
+ return _requestObservable(this, this.#httpRequest, options);
2768
+ }
2769
+ /**
2770
+ * Get a Sanity API URL for the URI provided
2771
+ *
2772
+ * @param uri - URI/path to build URL for
2773
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
2774
+ */
2775
+ getUrl(uri, canUseCdn) {
2776
+ return _getUrl(this, uri, canUseCdn);
2777
+ }
2778
+ /**
2779
+ * Get a Sanity API URL for the data operation and path provided
2780
+ *
2781
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2782
+ * @param path - Path to append after the operation
2783
+ */
2784
+ getDataUrl(operation, path) {
2785
+ return _getDataUrl(this, operation, path);
2786
+ }
2787
+ }, SanityClient = class SanityClient {
2788
+ assets;
2789
+ datasets;
2790
+ live;
2791
+ mediaLibrary;
2792
+ projects;
2793
+ users;
2794
+ agent;
2795
+ releases;
2796
+ /**
2797
+ * Observable version of the Sanity client, with the same configuration as the promise-based one
2798
+ */
2799
+ observable;
2800
+ /**
2801
+ * Private properties
2802
+ */
2803
+ #clientConfig;
2804
+ #httpRequest;
2805
+ /**
2806
+ * Instance properties
2807
+ */
2808
+ listen = _listen;
2809
+ 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);
2811
+ }
2812
+ /**
2813
+ * Clone the client - returns a new instance
2814
+ */
2815
+ clone() {
2816
+ return new SanityClient(this.#httpRequest, this.config());
2817
+ }
2818
+ config(newConfig) {
2819
+ if (newConfig === void 0) return { ...this.#clientConfig };
2820
+ if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1) throw Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
2821
+ return this.observable && this.observable.config(newConfig), this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;
2822
+ }
2823
+ /**
2824
+ * Clone the client with a new (partial) configuration.
2825
+ *
2826
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2827
+ */
2828
+ withConfig(newConfig) {
2829
+ let thisConfig = this.config();
2830
+ return new SanityClient(this.#httpRequest, {
2831
+ ...thisConfig,
2832
+ ...newConfig,
2833
+ stega: {
2834
+ ...thisConfig.stega,
2835
+ ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2836
+ }
2837
+ });
2838
+ }
2839
+ fetch(query, params, options) {
2840
+ return _fetch(this, this.#httpRequest, this.#clientConfig.stega, query, params, options);
2841
+ }
2842
+ getDocument(id, options) {
2843
+ if (options?.includeAllVersions === !0) return _getDocument(this, this.#httpRequest, id, {
2844
+ ...options,
2845
+ includeAllVersions: !0
2846
+ });
2847
+ let opts = {
2848
+ signal: options?.signal,
2849
+ tag: options?.tag,
2850
+ releaseId: options?.releaseId,
2851
+ ...options && "includeAllVersions" in options ? { includeAllVersions: !1 } : {}
2852
+ };
2853
+ return _getDocument(this, this.#httpRequest, id, opts);
2854
+ }
2855
+ /**
2856
+ * Fetch multiple documents in one request.
2857
+ * Should be used sparingly - performing a query is usually a better option.
2858
+ * The order/position of documents is preserved based on the original array of IDs.
2859
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2860
+ *
2861
+ * @param ids - Document IDs to fetch
2862
+ * @param options - Request options
2863
+ */
2864
+ getDocuments(ids, options) {
2865
+ return _getDocuments(this, this.#httpRequest, ids, options);
2866
+ }
2867
+ /**
2868
+ * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
2869
+ * Returns a set of the IDs that exist.
2870
+ *
2871
+ * @param ids - Document IDs to check
2872
+ * @param options - Request options
2873
+ */
2874
+ documentsExists(ids, options) {
2875
+ return _documentsExists(this, this.#httpRequest, ids, options);
2876
+ }
2877
+ create(document, options) {
2878
+ return _create(this, this.#httpRequest, document, "create", options);
2879
+ }
2880
+ createIfNotExists(document, options) {
2881
+ return _createIfNotExists(this, this.#httpRequest, document, options);
2882
+ }
2883
+ createOrReplace(document, options) {
2884
+ return _createOrReplace(this, this.#httpRequest, document, options);
2885
+ }
2886
+ createVersion({ document, publishedId, releaseId, baseId, ifBaseRevisionId }, options) {
2887
+ if (!document) return _createVersionFromBase(this, this.#httpRequest, publishedId, baseId, releaseId, ifBaseRevisionId, options);
2888
+ let documentVersionId = deriveDocumentVersionId("createVersion", {
2889
+ document,
2890
+ publishedId,
2891
+ releaseId
2892
+ }), documentVersion = {
2893
+ ...document,
2894
+ _id: documentVersionId
2895
+ }, versionPublishedId = publishedId || getPublishedId(document._id);
2896
+ return _createVersion(this, this.#httpRequest, documentVersion, versionPublishedId, options);
2897
+ }
2898
+ delete(selection, options) {
2899
+ return _delete(this, this.#httpRequest, selection, options);
2900
+ }
2901
+ /**
2902
+ * @public
2903
+ *
2904
+ * Deletes the draft or release version of a document.
2905
+ *
2906
+ * @remarks
2907
+ * * Discarding a version with no `releaseId` will discard the draft version of the published document.
2908
+ * * If the draft or release version does not exist, any error will throw.
2909
+ *
2910
+ * @param params - Version action parameters:
2911
+ * - `releaseId` - The ID of the release to discard the document from.
2912
+ * - `publishedId` - The published ID of the document to discard.
2913
+ * @param purge - if `true` the document history is also discarded.
2914
+ * @param options - Additional action options.
2915
+ * @returns a promise that resolves to the `transactionId`.
2916
+ *
2917
+ * @example Discarding a release version of a document
2918
+ * ```ts
2919
+ * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2920
+ * // The document with the ID `versions.myRelease.myDocument` will be discarded.
2921
+ * ```
2922
+ *
2923
+ * @example Discarding a draft version of a document
2924
+ * ```ts
2925
+ * client.discardVersion({publishedId: 'myDocument'})
2926
+ * // The document with the ID `drafts.myDocument` will be discarded.
2927
+ * ```
2928
+ */
2929
+ discardVersion({ releaseId, publishedId }, purge, options) {
2930
+ let documentVersionId = getDocumentVersionId(publishedId, releaseId);
2931
+ return _discardVersion(this, this.#httpRequest, documentVersionId, purge, options);
2932
+ }
2933
+ replaceVersion({ document, publishedId, releaseId }, options) {
2934
+ let documentVersionId = deriveDocumentVersionId("replaceVersion", {
2935
+ document,
2936
+ publishedId,
2937
+ releaseId
2938
+ }), documentVersion = {
2939
+ ...document,
2940
+ _id: documentVersionId
2941
+ };
2942
+ return _replaceVersion(this, this.#httpRequest, documentVersion, options);
2943
+ }
2944
+ /**
2945
+ * @public
2946
+ *
2947
+ * Used to indicate when a document within a release should be unpublished when
2948
+ * the release is run.
2949
+ *
2950
+ * @remarks
2951
+ * * If the published document does not exist, an error will be thrown.
2952
+ *
2953
+ * @param params - Version action parameters:
2954
+ * - `releaseId` - The ID of the release to unpublish the document from.
2955
+ * - `publishedId` - The published ID of the document to unpublish.
2956
+ * @param options - Additional action options.
2957
+ * @returns a promise that resolves to the `transactionId`.
2958
+ *
2959
+ * @example Unpublishing a release version of a published document
2960
+ * ```ts
2961
+ * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
2962
+ * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
2963
+ * ```
2964
+ */
2965
+ unpublishVersion({ releaseId, publishedId }, options) {
2966
+ let versionId = getVersionId(publishedId, releaseId);
2967
+ return _unpublishVersion(this, this.#httpRequest, versionId, publishedId, options);
2968
+ }
2969
+ mutate(operations, options) {
2970
+ return _mutate(this, this.#httpRequest, operations, options);
2971
+ }
2972
+ /**
2973
+ * Create a new buildable patch of operations to perform
2974
+ *
2975
+ * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2976
+ * @param operations - Optional object of patch operations to initialize the patch instance with
2977
+ * @returns Patch instance - call `.commit()` to perform the operations defined
2978
+ */
2979
+ patch(documentId, operations) {
2980
+ return new Patch(documentId, operations, this);
2981
+ }
2982
+ /**
2983
+ * Create a new transaction of mutations
2984
+ *
2985
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
2986
+ */
2987
+ transaction(operations) {
2988
+ return new Transaction(operations, this);
2989
+ }
2990
+ /**
2991
+ * Perform action operations against the configured dataset
2992
+ * Returns a promise that resolves to the transaction result
2993
+ *
2994
+ * @param operations - Action operation(s) to execute
2995
+ * @param options - Action options
2996
+ */
2997
+ action(operations, options) {
2998
+ return _action(this, this.#httpRequest, operations, options);
2999
+ }
3000
+ /**
3001
+ * Perform a request against the Sanity API
3002
+ * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
3003
+ *
3004
+ * @param options - Request options
3005
+ * @returns Promise resolving to the response body
3006
+ */
3007
+ request(options) {
3008
+ return _request(this, this.#httpRequest, options);
3009
+ }
3010
+ /**
3011
+ * Perform an HTTP request a `/data` sub-endpoint
3012
+ * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
3013
+ *
3014
+ * @deprecated - Use `request()` or your own HTTP library instead
3015
+ * @param endpoint - Endpoint to hit (mutate, query etc)
3016
+ * @param body - Request body
3017
+ * @param options - Request options
3018
+ * @internal
3019
+ */
3020
+ dataRequest(endpoint, body, options) {
3021
+ return _dataRequest(this, this.#httpRequest, endpoint, body, options);
3022
+ }
3023
+ /**
3024
+ * Get a Sanity API URL for the URI provided
3025
+ *
3026
+ * @param uri - URI/path to build URL for
3027
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
3028
+ */
3029
+ getUrl(uri, canUseCdn) {
3030
+ return _getUrl(this, uri, canUseCdn);
3031
+ }
3032
+ /**
3033
+ * Get a Sanity API URL for the data operation and path provided
3034
+ *
3035
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
3036
+ * @param path - Path to append after the operation
3037
+ */
3038
+ getDataUrl(operation, path) {
3039
+ return _getDataUrl(this, operation, path);
3040
+ }
3041
+ };
3042
+ /**
3043
+ * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers
3044
+ * @internal
3045
+ */
3046
+ function defineCreateClientExports(envOptions, ClassConstructor) {
3047
+ let defaultRequester = defineRequester(envOptions).observable, createClient = (config) => {
3048
+ let { observable: clientRequester, promise: clientRequesterPromise } = defineRequester(envOptions, {
3049
+ ignoreWarnings: config.ignoreWarnings,
3050
+ maxRetries: config.maxRetries,
3051
+ retryDelay: config.retryDelay
3052
+ }), httpRequest = async (options) => (await clientRequesterPromise({
3053
+ redirect: "manual",
3054
+ ...options
3055
+ })).body;
3056
+ return new ClassConstructor(httpRequest, {
3057
+ ...config,
3058
+ requester: clientRequester,
3059
+ resolveFetch: config.resolveFetch ?? envOptions.resolveFetch
3060
+ });
3061
+ };
3062
+ return {
3063
+ requester: defaultRequester,
3064
+ createClient
3065
+ };
3066
+ }
3067
+ function defineDeprecatedCreateClient(createClient) {
3068
+ return function deprecatedCreateClient(config) {
3069
+ return printNoDefaultExport(), createClient(config);
3070
+ };
3071
+ }
3072
+ var name = "@sanity/client", version = "8.0.0";
3073
+ const log = createDebug("sanity:client");
3074
+ function isNodeReadableStream(value) {
3075
+ return typeof value != "object" || !value || !("pipe" in value) ? !1 : typeof value.pipe == "function";
3076
+ }
3077
+ const proxyFetchCache = /* @__PURE__ */ new Map();
3078
+ function getProxyFetch(proxyUrl) {
3079
+ let cached = proxyFetchCache.get(proxyUrl);
3080
+ if (cached) return cached;
3081
+ let fetch = createNodeFetch({
3082
+ proxy: proxyUrl,
3083
+ connections: 30
3084
+ });
3085
+ return proxyFetchCache.set(proxyUrl, fetch), fetch;
3086
+ }
3087
+ let envDefaultFetch;
3088
+ /**
3089
+ * Exposed via `EnvironmentOptions.resolveFetch` so EventSource connections
3090
+ * use the same transport as regular requests instead of falling back to
3091
+ * `globalThis.fetch`. Everything get-it's Node fetch provides then applies
3092
+ * to SSE too: the undici dispatcher configuration, an explicit `proxy`
3093
+ * config (pass the URL), and env-proxy support
3094
+ * (`HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY`, which Node's own global fetch does
3095
+ * not read — that is opt-in via `NODE_USE_ENV_PROXY`, and not on our 22.12
3096
+ * floor). Reached via the env rather than a direct import so `get-it/node`
3097
+ * (and with it `undici`) stays out of the browser bundle.
3098
+ *
3099
+ * @internal
3100
+ */
3101
+ function resolveFetch(proxyUrl) {
3102
+ return typeof proxyUrl == "string" ? getProxyFetch(proxyUrl) : (envDefaultFetch ??= createNodeFetch(), envDefaultFetch);
3103
+ }
3104
+ const middleware = [
3105
+ debug({
3106
+ log: (message, ...args) => log(message, ...args),
3107
+ verbose: !0
3108
+ }),
3109
+ { beforeRequest(opts) {
3110
+ let configLineage = typeof opts.meta?.lineage == "string" ? opts.meta.lineage : void 0, lineage = typeof process < "u" && process.env.X_SANITY_LINEAGE || configLineage;
3111
+ if (!lineage) return opts;
3112
+ let headers = new Headers(opts.headers);
3113
+ return headers.set("x-sanity-lineage", lineage), {
3114
+ ...opts,
3115
+ headers
3116
+ };
3117
+ } },
3118
+ { beforeRequest(opts) {
3119
+ return isNodeReadableStream(opts.body) ? {
3120
+ ...opts,
3121
+ body: Readable.toWeb(opts.body)
3122
+ } : opts;
3123
+ } }
3124
+ ], exp = defineCreateClientExports({
3125
+ headers: { "User-Agent": `${name} ${version}` },
3126
+ middleware,
3127
+ resolveFetch
3128
+ }, 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 };
3130
+
3131
+ //# sourceMappingURL=index.node.js.map