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