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