@sanity/client 6.4.3 → 6.4.5-canary.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.
@@ -0,0 +1,1891 @@
1
+ import { getIt } from 'get-it';
2
+ import { retry, jsonRequest, jsonResponse, progress, observable } from 'get-it/middleware';
3
+ import { Observable, lastValueFrom } from 'rxjs';
4
+ import { map, filter } from 'rxjs/operators';
5
+ var __defProp$3 = Object.defineProperty;
6
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
7
+ enumerable: true,
8
+ configurable: true,
9
+ writable: true,
10
+ value
11
+ }) : obj[key] = value;
12
+ var __publicField$3 = (obj, key, value) => {
13
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
14
+ return value;
15
+ };
16
+ const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
17
+ class ClientError extends Error {
18
+ constructor(res) {
19
+ const props = extractErrorProps(res);
20
+ super(props.message);
21
+ __publicField$3(this, "response");
22
+ __publicField$3(this, "statusCode", 400);
23
+ __publicField$3(this, "responseBody");
24
+ __publicField$3(this, "details");
25
+ Object.assign(this, props);
26
+ }
27
+ }
28
+ class ServerError extends Error {
29
+ constructor(res) {
30
+ const props = extractErrorProps(res);
31
+ super(props.message);
32
+ __publicField$3(this, "response");
33
+ __publicField$3(this, "statusCode", 500);
34
+ __publicField$3(this, "responseBody");
35
+ __publicField$3(this, "details");
36
+ Object.assign(this, props);
37
+ }
38
+ }
39
+ function extractErrorProps(res) {
40
+ const body = res.body;
41
+ const props = {
42
+ response: res,
43
+ statusCode: res.statusCode,
44
+ responseBody: stringifyBody(body, res),
45
+ message: "",
46
+ details: void 0
47
+ };
48
+ if (body.error && body.message) {
49
+ props.message = "".concat(body.error, " - ").concat(body.message);
50
+ return props;
51
+ }
52
+ if (isMutationError(body)) {
53
+ const allItems = body.error.items || [];
54
+ const items = allItems.slice(0, MAX_ITEMS_IN_ERROR_MESSAGE).map(item => {
55
+ var _a;
56
+ return (_a = item.error) == null ? void 0 : _a.description;
57
+ }).filter(Boolean);
58
+ let itemsStr = items.length ? ":\n- ".concat(items.join("\n- ")) : "";
59
+ if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {
60
+ itemsStr += "\n...and ".concat(allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE, " more");
61
+ }
62
+ props.message = "".concat(body.error.description).concat(itemsStr);
63
+ props.details = body.error;
64
+ return props;
65
+ }
66
+ if (body.error && body.error.description) {
67
+ props.message = body.error.description;
68
+ props.details = body.error;
69
+ return props;
70
+ }
71
+ props.message = body.error || body.message || httpErrorMessage(res);
72
+ return props;
73
+ }
74
+ function isMutationError(body) {
75
+ return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description === "string";
76
+ }
77
+ function isPlainObject(obj) {
78
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
79
+ }
80
+ function httpErrorMessage(res) {
81
+ const statusMessage = res.statusMessage ? " ".concat(res.statusMessage) : "";
82
+ return "".concat(res.method, "-request to ").concat(res.url, " resulted in HTTP ").concat(res.statusCode).concat(statusMessage);
83
+ }
84
+ function stringifyBody(body, res) {
85
+ const contentType = (res.headers["content-type"] || "").toLowerCase();
86
+ const isJson = contentType.indexOf("application/json") !== -1;
87
+ return isJson ? JSON.stringify(body, null, 2) : body;
88
+ }
89
+ const httpError = {
90
+ onResponse: res => {
91
+ if (res.statusCode >= 500) {
92
+ throw new ServerError(res);
93
+ } else if (res.statusCode >= 400) {
94
+ throw new ClientError(res);
95
+ }
96
+ return res;
97
+ }
98
+ };
99
+ const printWarnings = {
100
+ onResponse: res => {
101
+ const warn = res.headers["x-sanity-warning"];
102
+ const warnings = Array.isArray(warn) ? warn : [warn];
103
+ warnings.filter(Boolean).forEach(msg => console.warn(msg));
104
+ return res;
105
+ }
106
+ };
107
+ function defineHttpRequest(envMiddleware, _ref) {
108
+ let {
109
+ maxRetries = 5,
110
+ retryDelay
111
+ } = _ref;
112
+ const request = getIt([maxRetries > 0 ? retry({
113
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
114
+ retryDelay,
115
+ // This option is typed incorrectly in get-it.
116
+ maxRetries,
117
+ shouldRetry
118
+ }) : {}, ...envMiddleware, printWarnings, jsonRequest(), jsonResponse(), progress(), httpError, observable({
119
+ implementation: Observable
120
+ })]);
121
+ function httpRequest(options) {
122
+ let requester = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : request;
123
+ return requester({
124
+ maxRedirects: 0,
125
+ ...options
126
+ });
127
+ }
128
+ httpRequest.defaultRequester = request;
129
+ return httpRequest;
130
+ }
131
+ function shouldRetry(err, attempt, options) {
132
+ const isSafe = options.method === "GET" || options.method === "HEAD";
133
+ const uri = options.uri || options.url;
134
+ const isQuery = uri.startsWith("/data/query");
135
+ const isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
136
+ if ((isSafe || isQuery) && isRetriableResponse) return true;
137
+ return retry.shouldRetry(err, attempt, options);
138
+ }
139
+ const projectHeader = "X-Sanity-Project-ID";
140
+ function requestOptions(config) {
141
+ let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
142
+ const headers = {};
143
+ const token = overrides.token || config.token;
144
+ if (token) {
145
+ headers.Authorization = "Bearer ".concat(token);
146
+ }
147
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
148
+ headers[projectHeader] = config.projectId;
149
+ }
150
+ const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
151
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
152
+ return Object.assign({}, overrides, {
153
+ headers: Object.assign({}, headers, overrides.headers || {}),
154
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
155
+ proxy: overrides.proxy || config.proxy,
156
+ json: true,
157
+ withCredentials,
158
+ fetch: typeof overrides.fetch === "object" && typeof config.fetch === "object" ? {
159
+ ...config.fetch,
160
+ ...overrides.fetch
161
+ } : overrides.fetch || config.fetch
162
+ });
163
+ }
164
+ function getSelection(sel) {
165
+ if (typeof sel === "string" || Array.isArray(sel)) {
166
+ return {
167
+ id: sel
168
+ };
169
+ }
170
+ if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
171
+ return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
172
+ query: sel.query,
173
+ params: sel.params
174
+ } : {
175
+ query: sel.query
176
+ };
177
+ }
178
+ const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
179
+ throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
180
+ }
181
+ const VALID_ASSET_TYPES = ["image", "file"];
182
+ const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
183
+ const dataset = name => {
184
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
185
+ throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
186
+ }
187
+ };
188
+ const projectId = id => {
189
+ if (!/^[-a-z0-9]+$/i.test(id)) {
190
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
191
+ }
192
+ };
193
+ const validateAssetType = type => {
194
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) {
195
+ throw new Error("Invalid asset type: ".concat(type, ". Must be one of ").concat(VALID_ASSET_TYPES.join(", ")));
196
+ }
197
+ };
198
+ const validateObject = (op, val) => {
199
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
200
+ throw new Error("".concat(op, "() takes an object of properties"));
201
+ }
202
+ };
203
+ const validateDocumentId = (op, id) => {
204
+ if (typeof id !== "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes("..")) {
205
+ throw new Error("".concat(op, '(): "').concat(id, '" is not a valid document ID'));
206
+ }
207
+ };
208
+ const requireDocumentId = (op, doc) => {
209
+ if (!doc._id) {
210
+ throw new Error("".concat(op, '() requires that the document contains an ID ("_id" property)'));
211
+ }
212
+ validateDocumentId(op, doc._id);
213
+ };
214
+ const validateInsert = (at, selector, items) => {
215
+ const signature = "insert(at, selector, items)";
216
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
217
+ const valid = VALID_INSERT_LOCATIONS.map(loc => '"'.concat(loc, '"')).join(", ");
218
+ throw new Error("".concat(signature, ' takes an "at"-argument which is one of: ').concat(valid));
219
+ }
220
+ if (typeof selector !== "string") {
221
+ throw new Error("".concat(signature, ' takes a "selector"-argument which must be a string'));
222
+ }
223
+ if (!Array.isArray(items)) {
224
+ throw new Error("".concat(signature, ' takes an "items"-argument which must be an array'));
225
+ }
226
+ };
227
+ const hasDataset = config => {
228
+ if (!config.dataset) {
229
+ throw new Error("`dataset` must be provided to perform queries");
230
+ }
231
+ return config.dataset || "";
232
+ };
233
+ const requestTag = tag => {
234
+ if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
235
+ throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");
236
+ }
237
+ return tag;
238
+ };
239
+ const encodeQueryString = _ref2 => {
240
+ let {
241
+ query,
242
+ params = {},
243
+ options = {}
244
+ } = _ref2;
245
+ const searchParams = new URLSearchParams();
246
+ const {
247
+ tag,
248
+ ...opts
249
+ } = options;
250
+ if (tag) searchParams.set("tag", tag);
251
+ searchParams.set("query", query);
252
+ for (const [key, value] of Object.entries(params)) {
253
+ searchParams.set("$".concat(key), JSON.stringify(value));
254
+ }
255
+ for (const [key, value] of Object.entries(opts)) {
256
+ if (value) searchParams.set(key, "".concat(value));
257
+ }
258
+ return "?".concat(searchParams);
259
+ };
260
+ var __defProp$2 = Object.defineProperty;
261
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
262
+ enumerable: true,
263
+ configurable: true,
264
+ writable: true,
265
+ value
266
+ }) : obj[key] = value;
267
+ var __publicField$2 = (obj, key, value) => {
268
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
269
+ return value;
270
+ };
271
+ var __accessCheck$6 = (obj, member, msg) => {
272
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
273
+ };
274
+ var __privateGet$6 = (obj, member, getter) => {
275
+ __accessCheck$6(obj, member, "read from private field");
276
+ return getter ? getter.call(obj) : member.get(obj);
277
+ };
278
+ var __privateAdd$6 = (obj, member, value) => {
279
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
280
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
281
+ };
282
+ var __privateSet$6 = (obj, member, value, setter) => {
283
+ __accessCheck$6(obj, member, "write to private field");
284
+ setter ? setter.call(obj, value) : member.set(obj, value);
285
+ return value;
286
+ };
287
+ var _client$5, _client2$5;
288
+ class BasePatch {
289
+ constructor(selection) {
290
+ let operations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
291
+ __publicField$2(this, "selection");
292
+ __publicField$2(this, "operations");
293
+ this.selection = selection;
294
+ this.operations = operations;
295
+ }
296
+ /**
297
+ * Sets the given attributes to the document. Does NOT merge objects.
298
+ * The operation is added to the current patch, ready to be commited by `commit()`
299
+ *
300
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
301
+ */
302
+ set(attrs) {
303
+ return this._assign("set", attrs);
304
+ }
305
+ /**
306
+ * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
307
+ * The operation is added to the current patch, ready to be commited by `commit()`
308
+ *
309
+ * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
310
+ */
311
+ setIfMissing(attrs) {
312
+ return this._assign("setIfMissing", attrs);
313
+ }
314
+ /**
315
+ * Performs a "diff-match-patch" operation on the string attributes provided.
316
+ * The operation is added to the current patch, ready to be commited by `commit()`
317
+ *
318
+ * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
319
+ */
320
+ diffMatchPatch(attrs) {
321
+ validateObject("diffMatchPatch", attrs);
322
+ return this._assign("diffMatchPatch", attrs);
323
+ }
324
+ /**
325
+ * Unsets the attribute paths provided.
326
+ * The operation is added to the current patch, ready to be commited by `commit()`
327
+ *
328
+ * @param attrs - Attribute paths to unset.
329
+ */
330
+ unset(attrs) {
331
+ if (!Array.isArray(attrs)) {
332
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
333
+ }
334
+ this.operations = Object.assign({}, this.operations, {
335
+ unset: attrs
336
+ });
337
+ return this;
338
+ }
339
+ /**
340
+ * 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.
341
+ *
342
+ * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
343
+ */
344
+ inc(attrs) {
345
+ return this._assign("inc", attrs);
346
+ }
347
+ /**
348
+ * 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.
349
+ *
350
+ * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
351
+ */
352
+ dec(attrs) {
353
+ return this._assign("dec", attrs);
354
+ }
355
+ /**
356
+ * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
357
+ *
358
+ * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
359
+ * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
360
+ * @param items - Array of items to insert/replace
361
+ */
362
+ insert(at, selector, items) {
363
+ validateInsert(at, selector, items);
364
+ return this._assign("insert", {
365
+ [at]: selector,
366
+ items
367
+ });
368
+ }
369
+ /**
370
+ * Append the given items to the array at the given JSONPath
371
+ *
372
+ * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
373
+ * @param items - Array of items to append to the array
374
+ */
375
+ append(selector, items) {
376
+ return this.insert("after", "".concat(selector, "[-1]"), items);
377
+ }
378
+ /**
379
+ * Prepend the given items to the array at the given JSONPath
380
+ *
381
+ * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
382
+ * @param items - Array of items to prepend to the array
383
+ */
384
+ prepend(selector, items) {
385
+ return this.insert("before", "".concat(selector, "[0]"), items);
386
+ }
387
+ /**
388
+ * Change the contents of an array by removing existing elements and/or adding new elements.
389
+ *
390
+ * @param selector - Attribute or JSONPath expression for array
391
+ * @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
392
+ * @param deleteCount - An integer indicating the number of old array elements to remove.
393
+ * @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.
394
+ */
395
+ splice(selector, start, deleteCount, items) {
396
+ const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
397
+ const startIndex = start < 0 ? start - 1 : start;
398
+ const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
399
+ const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
400
+ const rangeSelector = "".concat(selector, "[").concat(startIndex, ":").concat(delRange, "]");
401
+ return this.insert("replace", rangeSelector, items || []);
402
+ }
403
+ /**
404
+ * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
405
+ *
406
+ * @param rev - Revision to lock the patch to
407
+ */
408
+ ifRevisionId(rev) {
409
+ this.operations.ifRevisionID = rev;
410
+ return this;
411
+ }
412
+ /**
413
+ * Return a plain JSON representation of the patch
414
+ */
415
+ serialize() {
416
+ return {
417
+ ...getSelection(this.selection),
418
+ ...this.operations
419
+ };
420
+ }
421
+ /**
422
+ * Return a plain JSON representation of the patch
423
+ */
424
+ toJSON() {
425
+ return this.serialize();
426
+ }
427
+ /**
428
+ * Clears the patch of all operations
429
+ */
430
+ reset() {
431
+ this.operations = {};
432
+ return this;
433
+ }
434
+ _assign(op, props) {
435
+ let merge = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
436
+ validateObject(op, props);
437
+ this.operations = Object.assign({}, this.operations, {
438
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
439
+ });
440
+ return this;
441
+ }
442
+ _set(op, props) {
443
+ return this._assign(op, props, false);
444
+ }
445
+ }
446
+ const _ObservablePatch = class _ObservablePatch extends BasePatch {
447
+ constructor(selection, operations, client) {
448
+ super(selection, operations);
449
+ __privateAdd$6(this, _client$5, void 0);
450
+ __privateSet$6(this, _client$5, client);
451
+ }
452
+ /**
453
+ * Clones the patch
454
+ */
455
+ clone() {
456
+ return new _ObservablePatch(this.selection, {
457
+ ...this.operations
458
+ }, __privateGet$6(this, _client$5));
459
+ }
460
+ commit(options) {
461
+ if (!__privateGet$6(this, _client$5)) {
462
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
463
+ }
464
+ const returnFirst = typeof this.selection === "string";
465
+ const opts = Object.assign({
466
+ returnFirst,
467
+ returnDocuments: true
468
+ }, options);
469
+ return __privateGet$6(this, _client$5).mutate({
470
+ patch: this.serialize()
471
+ }, opts);
472
+ }
473
+ };
474
+ _client$5 = new WeakMap();
475
+ let ObservablePatch = _ObservablePatch;
476
+ const _Patch = class _Patch extends BasePatch {
477
+ constructor(selection, operations, client) {
478
+ super(selection, operations);
479
+ __privateAdd$6(this, _client2$5, void 0);
480
+ __privateSet$6(this, _client2$5, client);
481
+ }
482
+ /**
483
+ * Clones the patch
484
+ */
485
+ clone() {
486
+ return new _Patch(this.selection, {
487
+ ...this.operations
488
+ }, __privateGet$6(this, _client2$5));
489
+ }
490
+ commit(options) {
491
+ if (!__privateGet$6(this, _client2$5)) {
492
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
493
+ }
494
+ const returnFirst = typeof this.selection === "string";
495
+ const opts = Object.assign({
496
+ returnFirst,
497
+ returnDocuments: true
498
+ }, options);
499
+ return __privateGet$6(this, _client2$5).mutate({
500
+ patch: this.serialize()
501
+ }, opts);
502
+ }
503
+ };
504
+ _client2$5 = new WeakMap();
505
+ let Patch = _Patch;
506
+ var __defProp$1 = Object.defineProperty;
507
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
508
+ enumerable: true,
509
+ configurable: true,
510
+ writable: true,
511
+ value
512
+ }) : obj[key] = value;
513
+ var __publicField$1 = (obj, key, value) => {
514
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
515
+ return value;
516
+ };
517
+ var __accessCheck$5 = (obj, member, msg) => {
518
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
519
+ };
520
+ var __privateGet$5 = (obj, member, getter) => {
521
+ __accessCheck$5(obj, member, "read from private field");
522
+ return getter ? getter.call(obj) : member.get(obj);
523
+ };
524
+ var __privateAdd$5 = (obj, member, value) => {
525
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
526
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
527
+ };
528
+ var __privateSet$5 = (obj, member, value, setter) => {
529
+ __accessCheck$5(obj, member, "write to private field");
530
+ setter ? setter.call(obj, value) : member.set(obj, value);
531
+ return value;
532
+ };
533
+ var _client$4, _client2$4;
534
+ const defaultMutateOptions = {
535
+ returnDocuments: false
536
+ };
537
+ class BaseTransaction {
538
+ constructor() {
539
+ let operations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
540
+ let transactionId = arguments.length > 1 ? arguments[1] : undefined;
541
+ __publicField$1(this, "operations");
542
+ __publicField$1(this, "trxId");
543
+ this.operations = operations;
544
+ this.trxId = transactionId;
545
+ }
546
+ /**
547
+ * 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.
548
+ * The operation is added to the current transaction, ready to be commited by `commit()`
549
+ *
550
+ * @param doc - Document to create. Requires a `_type` property.
551
+ */
552
+ create(doc) {
553
+ validateObject("create", doc);
554
+ return this._add({
555
+ create: doc
556
+ });
557
+ }
558
+ /**
559
+ * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
560
+ * The operation is added to the current transaction, ready to be commited by `commit()`
561
+ *
562
+ * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
563
+ */
564
+ createIfNotExists(doc) {
565
+ const op = "createIfNotExists";
566
+ validateObject(op, doc);
567
+ requireDocumentId(op, doc);
568
+ return this._add({
569
+ [op]: doc
570
+ });
571
+ }
572
+ /**
573
+ * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
574
+ * The operation is added to the current transaction, ready to be commited by `commit()`
575
+ *
576
+ * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
577
+ */
578
+ createOrReplace(doc) {
579
+ const op = "createOrReplace";
580
+ validateObject(op, doc);
581
+ requireDocumentId(op, doc);
582
+ return this._add({
583
+ [op]: doc
584
+ });
585
+ }
586
+ /**
587
+ * Deletes the document with the given document ID
588
+ * The operation is added to the current transaction, ready to be commited by `commit()`
589
+ *
590
+ * @param documentId - Document ID to delete
591
+ */
592
+ delete(documentId) {
593
+ validateDocumentId("delete", documentId);
594
+ return this._add({
595
+ delete: {
596
+ id: documentId
597
+ }
598
+ });
599
+ }
600
+ transactionId(id) {
601
+ if (!id) {
602
+ return this.trxId;
603
+ }
604
+ this.trxId = id;
605
+ return this;
606
+ }
607
+ /**
608
+ * Return a plain JSON representation of the transaction
609
+ */
610
+ serialize() {
611
+ return [...this.operations];
612
+ }
613
+ /**
614
+ * Return a plain JSON representation of the transaction
615
+ */
616
+ toJSON() {
617
+ return this.serialize();
618
+ }
619
+ /**
620
+ * Clears the transaction of all operations
621
+ */
622
+ reset() {
623
+ this.operations = [];
624
+ return this;
625
+ }
626
+ _add(mut) {
627
+ this.operations.push(mut);
628
+ return this;
629
+ }
630
+ }
631
+ const _Transaction = class _Transaction extends BaseTransaction {
632
+ constructor(operations, client, transactionId) {
633
+ super(operations, transactionId);
634
+ __privateAdd$5(this, _client$4, void 0);
635
+ __privateSet$5(this, _client$4, client);
636
+ }
637
+ /**
638
+ * Clones the transaction
639
+ */
640
+ clone() {
641
+ return new _Transaction([...this.operations], __privateGet$5(this, _client$4), this.trxId);
642
+ }
643
+ commit(options) {
644
+ if (!__privateGet$5(this, _client$4)) {
645
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
646
+ }
647
+ return __privateGet$5(this, _client$4).mutate(this.serialize(), Object.assign({
648
+ transactionId: this.trxId
649
+ }, defaultMutateOptions, options || {}));
650
+ }
651
+ patch(patchOrDocumentId, patchOps) {
652
+ const isBuilder = typeof patchOps === "function";
653
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof Patch;
654
+ if (isPatch) {
655
+ return this._add({
656
+ patch: patchOrDocumentId.serialize()
657
+ });
658
+ }
659
+ if (isBuilder) {
660
+ const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
661
+ if (!(patch instanceof Patch)) {
662
+ throw new Error("function passed to `patch()` must return the patch");
663
+ }
664
+ return this._add({
665
+ patch: patch.serialize()
666
+ });
667
+ }
668
+ return this._add({
669
+ patch: {
670
+ id: patchOrDocumentId,
671
+ ...patchOps
672
+ }
673
+ });
674
+ }
675
+ };
676
+ _client$4 = new WeakMap();
677
+ let Transaction = _Transaction;
678
+ const _ObservableTransaction = class _ObservableTransaction extends BaseTransaction {
679
+ constructor(operations, client, transactionId) {
680
+ super(operations, transactionId);
681
+ __privateAdd$5(this, _client2$4, void 0);
682
+ __privateSet$5(this, _client2$4, client);
683
+ }
684
+ /**
685
+ * Clones the transaction
686
+ */
687
+ clone() {
688
+ return new _ObservableTransaction([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
689
+ }
690
+ commit(options) {
691
+ if (!__privateGet$5(this, _client2$4)) {
692
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
693
+ }
694
+ return __privateGet$5(this, _client2$4).mutate(this.serialize(), Object.assign({
695
+ transactionId: this.trxId
696
+ }, defaultMutateOptions, options || {}));
697
+ }
698
+ patch(patchOrDocumentId, patchOps) {
699
+ const isBuilder = typeof patchOps === "function";
700
+ const isPatch = typeof patchOrDocumentId !== "string" && patchOrDocumentId instanceof ObservablePatch;
701
+ if (isPatch) {
702
+ return this._add({
703
+ patch: patchOrDocumentId.serialize()
704
+ });
705
+ }
706
+ if (isBuilder) {
707
+ const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
708
+ if (!(patch instanceof ObservablePatch)) {
709
+ throw new Error("function passed to `patch()` must return the patch");
710
+ }
711
+ return this._add({
712
+ patch: patch.serialize()
713
+ });
714
+ }
715
+ return this._add({
716
+ patch: {
717
+ id: patchOrDocumentId,
718
+ ...patchOps
719
+ }
720
+ });
721
+ }
722
+ };
723
+ _client2$4 = new WeakMap();
724
+ let ObservableTransaction = _ObservableTransaction;
725
+ const excludeFalsey = (param, defValue) => {
726
+ const value = typeof param === "undefined" ? defValue : param;
727
+ return param === false ? void 0 : value;
728
+ };
729
+ const getMutationQuery = function () {
730
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
731
+ return {
732
+ dryRun: options.dryRun,
733
+ returnIds: true,
734
+ returnDocuments: excludeFalsey(options.returnDocuments, true),
735
+ visibility: options.visibility || "sync",
736
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
737
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
738
+ };
739
+ };
740
+ const isResponse = event => event.type === "response";
741
+ const getBody = event => event.body;
742
+ const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
743
+ indexed[attr(doc)] = doc;
744
+ return indexed;
745
+ }, /* @__PURE__ */Object.create(null));
746
+ const getQuerySizeLimit = 11264;
747
+ function _fetch(client, httpRequest, query, params) {
748
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
749
+ const mapResponse = options.filterResponse === false ? res => res : res => res.result;
750
+ const {
751
+ cache,
752
+ next,
753
+ ...opts
754
+ } = options;
755
+ const reqOpts = typeof cache !== "undefined" || typeof next !== "undefined" ? {
756
+ ...opts,
757
+ fetch: {
758
+ cache,
759
+ next
760
+ }
761
+ } : opts;
762
+ return _dataRequest(client, httpRequest, "query", {
763
+ query,
764
+ params
765
+ }, reqOpts).pipe(map(mapResponse));
766
+ }
767
+ function _getDocument(client, httpRequest, id) {
768
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
769
+ const options = {
770
+ uri: _getDataUrl(client, "doc", id),
771
+ json: true,
772
+ tag: opts.tag
773
+ };
774
+ return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => event.body.documents && event.body.documents[0]));
775
+ }
776
+ function _getDocuments(client, httpRequest, ids) {
777
+ let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
778
+ const options = {
779
+ uri: _getDataUrl(client, "doc", ids.join(",")),
780
+ json: true,
781
+ tag: opts.tag
782
+ };
783
+ return _requestObservable(client, httpRequest, options).pipe(filter(isResponse), map(event => {
784
+ const indexed = indexBy(event.body.documents || [], doc => doc._id);
785
+ return ids.map(id => indexed[id] || null);
786
+ }));
787
+ }
788
+ function _createIfNotExists(client, httpRequest, doc, options) {
789
+ requireDocumentId("createIfNotExists", doc);
790
+ return _create(client, httpRequest, doc, "createIfNotExists", options);
791
+ }
792
+ function _createOrReplace(client, httpRequest, doc, options) {
793
+ requireDocumentId("createOrReplace", doc);
794
+ return _create(client, httpRequest, doc, "createOrReplace", options);
795
+ }
796
+ function _delete(client, httpRequest, selection, options) {
797
+ return _dataRequest(client, httpRequest, "mutate", {
798
+ mutations: [{
799
+ delete: getSelection(selection)
800
+ }]
801
+ }, options);
802
+ }
803
+ function _mutate(client, httpRequest, mutations, options) {
804
+ let mut;
805
+ if (mutations instanceof Patch || mutations instanceof ObservablePatch) {
806
+ mut = {
807
+ patch: mutations.serialize()
808
+ };
809
+ } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {
810
+ mut = mutations.serialize();
811
+ } else {
812
+ mut = mutations;
813
+ }
814
+ const muts = Array.isArray(mut) ? mut : [mut];
815
+ const transactionId = options && options.transactionId || void 0;
816
+ return _dataRequest(client, httpRequest, "mutate", {
817
+ mutations: muts,
818
+ transactionId
819
+ }, options);
820
+ }
821
+ function _dataRequest(client, httpRequest, endpoint, body) {
822
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
823
+ const isMutation = endpoint === "mutate";
824
+ const isQuery = endpoint === "query";
825
+ const strQuery = isMutation ? "" : encodeQueryString(body);
826
+ const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
827
+ const stringQuery = useGet ? strQuery : "";
828
+ const returnFirst = options.returnFirst;
829
+ const {
830
+ timeout,
831
+ token,
832
+ tag,
833
+ headers
834
+ } = options;
835
+ const uri = _getDataUrl(client, endpoint, stringQuery);
836
+ const reqOptions = {
837
+ method: useGet ? "GET" : "POST",
838
+ uri,
839
+ json: true,
840
+ body: useGet ? void 0 : body,
841
+ query: isMutation && getMutationQuery(options),
842
+ timeout,
843
+ headers,
844
+ token,
845
+ tag,
846
+ canUseCdn: isQuery,
847
+ signal: options.signal,
848
+ fetch: options.fetch
849
+ };
850
+ return _requestObservable(client, httpRequest, reqOptions).pipe(filter(isResponse), map(getBody), map(res => {
851
+ if (!isMutation) {
852
+ return res;
853
+ }
854
+ const results = res.results || [];
855
+ if (options.returnDocuments) {
856
+ return returnFirst ? results[0] && results[0].document : results.map(mut => mut.document);
857
+ }
858
+ const key = returnFirst ? "documentId" : "documentIds";
859
+ const ids = returnFirst ? results[0] && results[0].id : results.map(mut => mut.id);
860
+ return {
861
+ transactionId: res.transactionId,
862
+ results,
863
+ [key]: ids
864
+ };
865
+ }));
866
+ }
867
+ function _create(client, httpRequest, doc, op) {
868
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
869
+ const mutation = {
870
+ [op]: doc
871
+ };
872
+ const opts = Object.assign({
873
+ returnFirst: true,
874
+ returnDocuments: true
875
+ }, options);
876
+ return _dataRequest(client, httpRequest, "mutate", {
877
+ mutations: [mutation]
878
+ }, opts);
879
+ }
880
+ function _requestObservable(client, httpRequest, options) {
881
+ const uri = options.url || options.uri;
882
+ const config = client.config();
883
+ const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
884
+ const useCdn = config.useCdn && canUseCdn;
885
+ const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(".") : options.tag || config.requestTagPrefix;
886
+ if (tag) {
887
+ options.query = {
888
+ tag: requestTag(tag),
889
+ ...options.query
890
+ };
891
+ }
892
+ if (["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
893
+ if (config.resultSourceMap) {
894
+ options.query = {
895
+ resultSourceMap: true,
896
+ ...options.query
897
+ };
898
+ }
899
+ if (typeof config.perspective === "string" && config.perspective !== "raw") {
900
+ options.query = {
901
+ perspective: config.perspective,
902
+ ...options.query
903
+ };
904
+ }
905
+ }
906
+ const reqOptions = requestOptions(config, Object.assign({}, options, {
907
+ url: _getUrl(client, uri, useCdn)
908
+ }));
909
+ const request = new Observable(subscriber => httpRequest(reqOptions, config.requester).subscribe(subscriber));
910
+ return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
911
+ }
912
+ function _request(client, httpRequest, options) {
913
+ const observable = _requestObservable(client, httpRequest, options).pipe(filter(event => event.type === "response"), map(event => event.body));
914
+ return observable;
915
+ }
916
+ function _getDataUrl(client, operation, path) {
917
+ const config = client.config();
918
+ const catalog = hasDataset(config);
919
+ const baseUri = "/".concat(operation, "/").concat(catalog);
920
+ const uri = path ? "".concat(baseUri, "/").concat(path) : baseUri;
921
+ return "/data".concat(uri).replace(/\/($|\?)/, "$1");
922
+ }
923
+ function _getUrl(client, uri) {
924
+ let canUseCdn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
925
+ const {
926
+ url,
927
+ cdnUrl
928
+ } = client.config();
929
+ const base = canUseCdn ? cdnUrl : url;
930
+ return "".concat(base, "/").concat(uri.replace(/^\//, ""));
931
+ }
932
+ function _withAbortSignal(signal) {
933
+ return input => {
934
+ return new Observable(observer => {
935
+ const abort = () => observer.error(_createAbortError(signal));
936
+ if (signal && signal.aborted) {
937
+ abort();
938
+ return;
939
+ }
940
+ const subscription = input.subscribe(observer);
941
+ signal.addEventListener("abort", abort);
942
+ return () => {
943
+ signal.removeEventListener("abort", abort);
944
+ subscription.unsubscribe();
945
+ };
946
+ });
947
+ };
948
+ }
949
+ const isDomExceptionSupported = Boolean(globalThis.DOMException);
950
+ function _createAbortError(signal) {
951
+ var _a, _b;
952
+ if (isDomExceptionSupported) {
953
+ return new DOMException((_a = signal == null ? void 0 : signal.reason) != null ? _a : "The operation was aborted.", "AbortError");
954
+ }
955
+ const error = new Error((_b = signal == null ? void 0 : signal.reason) != null ? _b : "The operation was aborted.");
956
+ error.name = "AbortError";
957
+ return error;
958
+ }
959
+ var __accessCheck$4 = (obj, member, msg) => {
960
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
961
+ };
962
+ var __privateGet$4 = (obj, member, getter) => {
963
+ __accessCheck$4(obj, member, "read from private field");
964
+ return getter ? getter.call(obj) : member.get(obj);
965
+ };
966
+ var __privateAdd$4 = (obj, member, value) => {
967
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
968
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
969
+ };
970
+ var __privateSet$4 = (obj, member, value, setter) => {
971
+ __accessCheck$4(obj, member, "write to private field");
972
+ setter ? setter.call(obj, value) : member.set(obj, value);
973
+ return value;
974
+ };
975
+ var _client$3, _httpRequest$4, _client2$3, _httpRequest2$4;
976
+ class ObservableAssetsClient {
977
+ constructor(client, httpRequest) {
978
+ __privateAdd$4(this, _client$3, void 0);
979
+ __privateAdd$4(this, _httpRequest$4, void 0);
980
+ __privateSet$4(this, _client$3, client);
981
+ __privateSet$4(this, _httpRequest$4, httpRequest);
982
+ }
983
+ upload(assetType, body, options) {
984
+ return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
985
+ }
986
+ }
987
+ _client$3 = new WeakMap();
988
+ _httpRequest$4 = new WeakMap();
989
+ class AssetsClient {
990
+ constructor(client, httpRequest) {
991
+ __privateAdd$4(this, _client2$3, void 0);
992
+ __privateAdd$4(this, _httpRequest2$4, void 0);
993
+ __privateSet$4(this, _client2$3, client);
994
+ __privateSet$4(this, _httpRequest2$4, httpRequest);
995
+ }
996
+ upload(assetType, body, options) {
997
+ const observable = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
998
+ return lastValueFrom(observable.pipe(filter(event => event.type === "response"), map(event => event.body.document)));
999
+ }
1000
+ }
1001
+ _client2$3 = new WeakMap();
1002
+ _httpRequest2$4 = new WeakMap();
1003
+ function _upload(client, httpRequest, assetType, body) {
1004
+ let opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1005
+ validateAssetType(assetType);
1006
+ let meta = opts.extract || void 0;
1007
+ if (meta && !meta.length) {
1008
+ meta = ["none"];
1009
+ }
1010
+ const dataset = hasDataset(client.config());
1011
+ const assetEndpoint = assetType === "image" ? "images" : "files";
1012
+ const options = optionsFromFile(opts, body);
1013
+ const {
1014
+ tag,
1015
+ label,
1016
+ title,
1017
+ description,
1018
+ creditLine,
1019
+ filename,
1020
+ source
1021
+ } = options;
1022
+ const query = {
1023
+ label,
1024
+ title,
1025
+ description,
1026
+ filename,
1027
+ meta,
1028
+ creditLine
1029
+ };
1030
+ if (source) {
1031
+ query.sourceId = source.id;
1032
+ query.sourceName = source.name;
1033
+ query.sourceUrl = source.url;
1034
+ }
1035
+ return _requestObservable(client, httpRequest, {
1036
+ tag,
1037
+ method: "POST",
1038
+ timeout: options.timeout || 0,
1039
+ uri: "/assets/".concat(assetEndpoint, "/").concat(dataset),
1040
+ headers: options.contentType ? {
1041
+ "Content-Type": options.contentType
1042
+ } : {},
1043
+ query,
1044
+ body
1045
+ });
1046
+ }
1047
+ function optionsFromFile(opts, file) {
1048
+ if (typeof File === "undefined" || !(file instanceof File)) {
1049
+ return opts;
1050
+ }
1051
+ return Object.assign({
1052
+ filename: opts.preserveFilename === false ? void 0 : file.name,
1053
+ contentType: file.type
1054
+ }, opts);
1055
+ }
1056
+ const BASE_URL = "https://www.sanity.io/help/";
1057
+ function generateHelpUrl(slug) {
1058
+ return BASE_URL + slug;
1059
+ }
1060
+ function once(fn) {
1061
+ let didCall = false;
1062
+ let returnValue;
1063
+ return function () {
1064
+ if (didCall) {
1065
+ return returnValue;
1066
+ }
1067
+ returnValue = fn(...arguments);
1068
+ didCall = true;
1069
+ return returnValue;
1070
+ };
1071
+ }
1072
+ const createWarningPrinter = message =>
1073
+ // eslint-disable-next-line no-console
1074
+ once(function () {
1075
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1076
+ args[_key] = arguments[_key];
1077
+ }
1078
+ return console.warn(message.join(" "), ...args);
1079
+ });
1080
+ const printCdnWarning = createWarningPrinter(["Since you haven't set a value for `useCdn`, we will deliver content using our", "global, edge-cached API-CDN. If you wish to have content delivered faster, set", "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]);
1081
+ const printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", "See ".concat(generateHelpUrl("js-client-browser-token"), " for more information and how to hide this warning.")]);
1082
+ const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
1083
+ const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]);
1084
+ const defaultCdnHost = "apicdn.sanity.io";
1085
+ const defaultConfig = {
1086
+ apiHost: "https://api.sanity.io",
1087
+ apiVersion: "1",
1088
+ useProjectHostname: true
1089
+ };
1090
+ const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
1091
+ const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
1092
+ const validateApiVersion = function validateApiVersion2(apiVersion) {
1093
+ if (apiVersion === "1" || apiVersion === "X") {
1094
+ return;
1095
+ }
1096
+ const apiDate = new Date(apiVersion);
1097
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
1098
+ if (!apiVersionValid) {
1099
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
1100
+ }
1101
+ };
1102
+ const validateApiPerspective = function validateApiPerspective2(perspective) {
1103
+ switch (perspective) {
1104
+ case "previewDrafts":
1105
+ case "published":
1106
+ case "raw":
1107
+ return;
1108
+ default:
1109
+ throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`");
1110
+ }
1111
+ };
1112
+ const initConfig = (config, prevConfig) => {
1113
+ const specifiedConfig = Object.assign({}, prevConfig, config);
1114
+ if (!specifiedConfig.apiVersion) {
1115
+ printNoApiVersionSpecifiedWarning();
1116
+ }
1117
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
1118
+ const projectBased = newConfig.useProjectHostname;
1119
+ if (typeof Promise === "undefined") {
1120
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
1121
+ throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
1122
+ }
1123
+ if (projectBased && !newConfig.projectId) {
1124
+ throw new Error("Configuration must contain `projectId`");
1125
+ }
1126
+ if (typeof newConfig.perspective === "string") {
1127
+ validateApiPerspective(newConfig.perspective);
1128
+ }
1129
+ if ("encodeSourceMapAtPath" in newConfig || "encodeSourceMap" in newConfig || "studioUrl" in newConfig || "logger" in newConfig) {
1130
+ throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client', such as 'encodeSourceMapAtPath', 'encodeSourceMap', 'studioUrl' and 'logger'. Make sure you're using the right import.");
1131
+ }
1132
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
1133
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
1134
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
1135
+ printBrowserTokenWarning();
1136
+ } else if (typeof newConfig.useCdn === "undefined") {
1137
+ printCdnWarning();
1138
+ }
1139
+ if (projectBased) {
1140
+ projectId(newConfig.projectId);
1141
+ }
1142
+ if (newConfig.dataset) {
1143
+ dataset(newConfig.dataset);
1144
+ }
1145
+ if ("requestTagPrefix" in newConfig) {
1146
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
1147
+ }
1148
+ newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
1149
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
1150
+ newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials;
1151
+ validateApiVersion(newConfig.apiVersion);
1152
+ const hostParts = newConfig.apiHost.split("://", 2);
1153
+ const protocol = hostParts[0];
1154
+ const host = hostParts[1];
1155
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
1156
+ if (newConfig.useProjectHostname) {
1157
+ newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
1158
+ newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
1159
+ } else {
1160
+ newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
1161
+ newConfig.cdnUrl = newConfig.url;
1162
+ }
1163
+ return newConfig;
1164
+ };
1165
+ var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
1166
+ target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
1167
+ return target;
1168
+ }, {});
1169
+ const pick = (obj, props) => props.reduce((selection, prop) => {
1170
+ if (typeof obj[prop] === "undefined") {
1171
+ return selection;
1172
+ }
1173
+ selection[prop] = obj[prop];
1174
+ return selection;
1175
+ }, {});
1176
+ const MAX_URL_LENGTH = 16e3 - 1200;
1177
+ const possibleOptions = ["includePreviousRevision", "includeResult", "visibility", "effectFormat", "tag"];
1178
+ const defaultOptions = {
1179
+ includeResult: true
1180
+ };
1181
+ function _listen(query, params) {
1182
+ let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1183
+ const {
1184
+ url,
1185
+ token,
1186
+ withCredentials,
1187
+ requestTagPrefix
1188
+ } = this.config();
1189
+ const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
1190
+ const options = {
1191
+ ...defaults(opts, defaultOptions),
1192
+ tag
1193
+ };
1194
+ const listenOpts = pick(options, possibleOptions);
1195
+ const qs = encodeQueryString({
1196
+ query,
1197
+ params,
1198
+ options: {
1199
+ tag,
1200
+ ...listenOpts
1201
+ }
1202
+ });
1203
+ const uri = "".concat(url).concat(_getDataUrl(this, "listen", qs));
1204
+ if (uri.length > MAX_URL_LENGTH) {
1205
+ return new Observable(observer => observer.error(new Error("Query too large for listener")));
1206
+ }
1207
+ const listenFor = options.events ? options.events : ["mutation"];
1208
+ const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
1209
+ const esOptions = {};
1210
+ if (token || withCredentials) {
1211
+ esOptions.withCredentials = true;
1212
+ }
1213
+ if (token) {
1214
+ esOptions.headers = {
1215
+ Authorization: "Bearer ".concat(token)
1216
+ };
1217
+ }
1218
+ return new Observable(observer => {
1219
+ let es;
1220
+ getEventSource().then(eventSource => {
1221
+ es = eventSource;
1222
+ }).catch(reason => {
1223
+ observer.error(reason);
1224
+ stop();
1225
+ });
1226
+ let reconnectTimer;
1227
+ let stopped = false;
1228
+ function onError() {
1229
+ if (stopped) {
1230
+ return;
1231
+ }
1232
+ emitReconnect();
1233
+ if (stopped) {
1234
+ return;
1235
+ }
1236
+ if (es.readyState === es.CLOSED) {
1237
+ unsubscribe();
1238
+ clearTimeout(reconnectTimer);
1239
+ reconnectTimer = setTimeout(open, 100);
1240
+ }
1241
+ }
1242
+ function onChannelError(err) {
1243
+ observer.error(cooerceError(err));
1244
+ }
1245
+ function onMessage(evt) {
1246
+ const event = parseEvent(evt);
1247
+ return event instanceof Error ? observer.error(event) : observer.next(event);
1248
+ }
1249
+ function onDisconnect() {
1250
+ stopped = true;
1251
+ unsubscribe();
1252
+ observer.complete();
1253
+ }
1254
+ function unsubscribe() {
1255
+ if (!es) return;
1256
+ es.removeEventListener("error", onError);
1257
+ es.removeEventListener("channelError", onChannelError);
1258
+ es.removeEventListener("disconnect", onDisconnect);
1259
+ listenFor.forEach(type => es.removeEventListener(type, onMessage));
1260
+ es.close();
1261
+ }
1262
+ function emitReconnect() {
1263
+ if (shouldEmitReconnect) {
1264
+ observer.next({
1265
+ type: "reconnect"
1266
+ });
1267
+ }
1268
+ }
1269
+ async function getEventSource() {
1270
+ const {
1271
+ default: EventSource
1272
+ } = await import('@sanity/eventsource');
1273
+ const evs = new EventSource(uri, esOptions);
1274
+ evs.addEventListener("error", onError);
1275
+ evs.addEventListener("channelError", onChannelError);
1276
+ evs.addEventListener("disconnect", onDisconnect);
1277
+ listenFor.forEach(type => evs.addEventListener(type, onMessage));
1278
+ return evs;
1279
+ }
1280
+ function open() {
1281
+ getEventSource().then(eventSource => {
1282
+ es = eventSource;
1283
+ }).catch(reason => {
1284
+ observer.error(reason);
1285
+ stop();
1286
+ });
1287
+ }
1288
+ function stop() {
1289
+ stopped = true;
1290
+ unsubscribe();
1291
+ }
1292
+ return stop;
1293
+ });
1294
+ }
1295
+ function parseEvent(event) {
1296
+ try {
1297
+ const data = event.data && JSON.parse(event.data) || {};
1298
+ return Object.assign({
1299
+ type: event.type
1300
+ }, data);
1301
+ } catch (err) {
1302
+ return err;
1303
+ }
1304
+ }
1305
+ function cooerceError(err) {
1306
+ if (err instanceof Error) {
1307
+ return err;
1308
+ }
1309
+ const evt = parseEvent(err);
1310
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
1311
+ }
1312
+ function extractErrorMessage(err) {
1313
+ if (!err.error) {
1314
+ return err.message || "Unknown listener error";
1315
+ }
1316
+ if (err.error.description) {
1317
+ return err.error.description;
1318
+ }
1319
+ return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
1320
+ }
1321
+ var __accessCheck$3 = (obj, member, msg) => {
1322
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1323
+ };
1324
+ var __privateGet$3 = (obj, member, getter) => {
1325
+ __accessCheck$3(obj, member, "read from private field");
1326
+ return getter ? getter.call(obj) : member.get(obj);
1327
+ };
1328
+ var __privateAdd$3 = (obj, member, value) => {
1329
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1330
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1331
+ };
1332
+ var __privateSet$3 = (obj, member, value, setter) => {
1333
+ __accessCheck$3(obj, member, "write to private field");
1334
+ setter ? setter.call(obj, value) : member.set(obj, value);
1335
+ return value;
1336
+ };
1337
+ var _client$2, _httpRequest$3, _client2$2, _httpRequest2$3;
1338
+ class ObservableDatasetsClient {
1339
+ constructor(client, httpRequest) {
1340
+ __privateAdd$3(this, _client$2, void 0);
1341
+ __privateAdd$3(this, _httpRequest$3, void 0);
1342
+ __privateSet$3(this, _client$2, client);
1343
+ __privateSet$3(this, _httpRequest$3, httpRequest);
1344
+ }
1345
+ /**
1346
+ * Create a new dataset with the given name
1347
+ *
1348
+ * @param name - Name of the dataset to create
1349
+ * @param options - Options for the dataset
1350
+ */
1351
+ create(name, options) {
1352
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name, options);
1353
+ }
1354
+ /**
1355
+ * Edit a dataset with the given name
1356
+ *
1357
+ * @param name - Name of the dataset to edit
1358
+ * @param options - New options for the dataset
1359
+ */
1360
+ edit(name, options) {
1361
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name, options);
1362
+ }
1363
+ /**
1364
+ * Delete a dataset with the given name
1365
+ *
1366
+ * @param name - Name of the dataset to delete
1367
+ */
1368
+ delete(name) {
1369
+ return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name);
1370
+ }
1371
+ /**
1372
+ * Fetch a list of datasets for the configured project
1373
+ */
1374
+ list() {
1375
+ return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
1376
+ uri: "/datasets"
1377
+ });
1378
+ }
1379
+ }
1380
+ _client$2 = new WeakMap();
1381
+ _httpRequest$3 = new WeakMap();
1382
+ class DatasetsClient {
1383
+ constructor(client, httpRequest) {
1384
+ __privateAdd$3(this, _client2$2, void 0);
1385
+ __privateAdd$3(this, _httpRequest2$3, void 0);
1386
+ __privateSet$3(this, _client2$2, client);
1387
+ __privateSet$3(this, _httpRequest2$3, httpRequest);
1388
+ }
1389
+ /**
1390
+ * Create a new dataset with the given name
1391
+ *
1392
+ * @param name - Name of the dataset to create
1393
+ * @param options - Options for the dataset
1394
+ */
1395
+ create(name, options) {
1396
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name, options));
1397
+ }
1398
+ /**
1399
+ * Edit a dataset with the given name
1400
+ *
1401
+ * @param name - Name of the dataset to edit
1402
+ * @param options - New options for the dataset
1403
+ */
1404
+ edit(name, options) {
1405
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name, options));
1406
+ }
1407
+ /**
1408
+ * Delete a dataset with the given name
1409
+ *
1410
+ * @param name - Name of the dataset to delete
1411
+ */
1412
+ delete(name) {
1413
+ return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name));
1414
+ }
1415
+ /**
1416
+ * Fetch a list of datasets for the configured project
1417
+ */
1418
+ list() {
1419
+ return lastValueFrom(_request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), {
1420
+ uri: "/datasets"
1421
+ }));
1422
+ }
1423
+ }
1424
+ _client2$2 = new WeakMap();
1425
+ _httpRequest2$3 = new WeakMap();
1426
+ function _modify(client, httpRequest, method, name, options) {
1427
+ dataset(name);
1428
+ return _request(client, httpRequest, {
1429
+ method,
1430
+ uri: "/datasets/".concat(name),
1431
+ body: options
1432
+ });
1433
+ }
1434
+ var __accessCheck$2 = (obj, member, msg) => {
1435
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1436
+ };
1437
+ var __privateGet$2 = (obj, member, getter) => {
1438
+ __accessCheck$2(obj, member, "read from private field");
1439
+ return getter ? getter.call(obj) : member.get(obj);
1440
+ };
1441
+ var __privateAdd$2 = (obj, member, value) => {
1442
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1443
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1444
+ };
1445
+ var __privateSet$2 = (obj, member, value, setter) => {
1446
+ __accessCheck$2(obj, member, "write to private field");
1447
+ setter ? setter.call(obj, value) : member.set(obj, value);
1448
+ return value;
1449
+ };
1450
+ var _client$1, _httpRequest$2, _client2$1, _httpRequest2$2;
1451
+ class ObservableProjectsClient {
1452
+ constructor(client, httpRequest) {
1453
+ __privateAdd$2(this, _client$1, void 0);
1454
+ __privateAdd$2(this, _httpRequest$2, void 0);
1455
+ __privateSet$2(this, _client$1, client);
1456
+ __privateSet$2(this, _httpRequest$2, httpRequest);
1457
+ }
1458
+ list(options) {
1459
+ const uri = (options == null ? void 0 : options.includeMembers) === false ? "/projects?includeMembers=false" : "/projects";
1460
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
1461
+ uri
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Fetch a project by project ID
1466
+ *
1467
+ * @param projectId - ID of the project to fetch
1468
+ */
1469
+ getById(projectId) {
1470
+ return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), {
1471
+ uri: "/projects/".concat(projectId)
1472
+ });
1473
+ }
1474
+ }
1475
+ _client$1 = new WeakMap();
1476
+ _httpRequest$2 = new WeakMap();
1477
+ class ProjectsClient {
1478
+ constructor(client, httpRequest) {
1479
+ __privateAdd$2(this, _client2$1, void 0);
1480
+ __privateAdd$2(this, _httpRequest2$2, void 0);
1481
+ __privateSet$2(this, _client2$1, client);
1482
+ __privateSet$2(this, _httpRequest2$2, httpRequest);
1483
+ }
1484
+ list(options) {
1485
+ const uri = (options == null ? void 0 : options.includeMembers) === false ? "/projects?includeMembers=false" : "/projects";
1486
+ return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
1487
+ uri
1488
+ }));
1489
+ }
1490
+ /**
1491
+ * Fetch a project by project ID
1492
+ *
1493
+ * @param projectId - ID of the project to fetch
1494
+ */
1495
+ getById(projectId) {
1496
+ return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), {
1497
+ uri: "/projects/".concat(projectId)
1498
+ }));
1499
+ }
1500
+ }
1501
+ _client2$1 = new WeakMap();
1502
+ _httpRequest2$2 = new WeakMap();
1503
+ var __accessCheck$1 = (obj, member, msg) => {
1504
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1505
+ };
1506
+ var __privateGet$1 = (obj, member, getter) => {
1507
+ __accessCheck$1(obj, member, "read from private field");
1508
+ return getter ? getter.call(obj) : member.get(obj);
1509
+ };
1510
+ var __privateAdd$1 = (obj, member, value) => {
1511
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1512
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1513
+ };
1514
+ var __privateSet$1 = (obj, member, value, setter) => {
1515
+ __accessCheck$1(obj, member, "write to private field");
1516
+ setter ? setter.call(obj, value) : member.set(obj, value);
1517
+ return value;
1518
+ };
1519
+ var _client, _httpRequest$1, _client2, _httpRequest2$1;
1520
+ class ObservableUsersClient {
1521
+ constructor(client, httpRequest) {
1522
+ __privateAdd$1(this, _client, void 0);
1523
+ __privateAdd$1(this, _httpRequest$1, void 0);
1524
+ __privateSet$1(this, _client, client);
1525
+ __privateSet$1(this, _httpRequest$1, httpRequest);
1526
+ }
1527
+ /**
1528
+ * Fetch a user by user ID
1529
+ *
1530
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1531
+ */
1532
+ getById(id) {
1533
+ return _request(__privateGet$1(this, _client), __privateGet$1(this, _httpRequest$1), {
1534
+ uri: "/users/".concat(id)
1535
+ });
1536
+ }
1537
+ }
1538
+ _client = new WeakMap();
1539
+ _httpRequest$1 = new WeakMap();
1540
+ class UsersClient {
1541
+ constructor(client, httpRequest) {
1542
+ __privateAdd$1(this, _client2, void 0);
1543
+ __privateAdd$1(this, _httpRequest2$1, void 0);
1544
+ __privateSet$1(this, _client2, client);
1545
+ __privateSet$1(this, _httpRequest2$1, httpRequest);
1546
+ }
1547
+ /**
1548
+ * Fetch a user by user ID
1549
+ *
1550
+ * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1551
+ */
1552
+ getById(id) {
1553
+ return lastValueFrom(_request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
1554
+ uri: "/users/".concat(id)
1555
+ }));
1556
+ }
1557
+ }
1558
+ _client2 = new WeakMap();
1559
+ _httpRequest2$1 = new WeakMap();
1560
+ var __defProp = Object.defineProperty;
1561
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
1562
+ enumerable: true,
1563
+ configurable: true,
1564
+ writable: true,
1565
+ value
1566
+ }) : obj[key] = value;
1567
+ var __publicField = (obj, key, value) => {
1568
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1569
+ return value;
1570
+ };
1571
+ var __accessCheck = (obj, member, msg) => {
1572
+ if (!member.has(obj)) throw TypeError("Cannot " + msg);
1573
+ };
1574
+ var __privateGet = (obj, member, getter) => {
1575
+ __accessCheck(obj, member, "read from private field");
1576
+ return getter ? getter.call(obj) : member.get(obj);
1577
+ };
1578
+ var __privateAdd = (obj, member, value) => {
1579
+ if (member.has(obj)) throw TypeError("Cannot add the same private member more than once");
1580
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1581
+ };
1582
+ var __privateSet = (obj, member, value, setter) => {
1583
+ __accessCheck(obj, member, "write to private field");
1584
+ setter ? setter.call(obj, value) : member.set(obj, value);
1585
+ return value;
1586
+ };
1587
+ var _clientConfig, _httpRequest, _clientConfig2, _httpRequest2;
1588
+ const _ObservableSanityClient = class _ObservableSanityClient {
1589
+ constructor(httpRequest) {
1590
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
1591
+ __publicField(this, "assets");
1592
+ __publicField(this, "datasets");
1593
+ __publicField(this, "projects");
1594
+ __publicField(this, "users");
1595
+ /**
1596
+ * Private properties
1597
+ */
1598
+ __privateAdd(this, _clientConfig, void 0);
1599
+ __privateAdd(this, _httpRequest, void 0);
1600
+ /**
1601
+ * Instance properties
1602
+ */
1603
+ __publicField(this, "listen", _listen);
1604
+ this.config(config);
1605
+ __privateSet(this, _httpRequest, httpRequest);
1606
+ this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest));
1607
+ this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest));
1608
+ this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest));
1609
+ this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
1610
+ }
1611
+ /**
1612
+ * Clone the client - returns a new instance
1613
+ */
1614
+ clone() {
1615
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), this.config());
1616
+ }
1617
+ config(newConfig) {
1618
+ if (newConfig === void 0) {
1619
+ return {
1620
+ ...__privateGet(this, _clientConfig)
1621
+ };
1622
+ }
1623
+ if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === false) {
1624
+ throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
1625
+ }
1626
+ __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {}));
1627
+ return this;
1628
+ }
1629
+ /**
1630
+ * Clone the client with a new (partial) configuration.
1631
+ *
1632
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1633
+ */
1634
+ withConfig(newConfig) {
1635
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
1636
+ ...this.config(),
1637
+ ...newConfig
1638
+ });
1639
+ }
1640
+ fetch(query, params) {
1641
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1642
+ return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
1643
+ }
1644
+ /**
1645
+ * Fetch a single document with the given ID.
1646
+ *
1647
+ * @param id - Document ID to fetch
1648
+ * @param options - Request options
1649
+ */
1650
+ getDocument(id, options) {
1651
+ return _getDocument(this, __privateGet(this, _httpRequest), id, options);
1652
+ }
1653
+ /**
1654
+ * Fetch multiple documents in one request.
1655
+ * Should be used sparingly - performing a query is usually a better option.
1656
+ * The order/position of documents is preserved based on the original array of IDs.
1657
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1658
+ *
1659
+ * @param ids - Document IDs to fetch
1660
+ * @param options - Request options
1661
+ */
1662
+ getDocuments(ids, options) {
1663
+ return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
1664
+ }
1665
+ create(document, options) {
1666
+ return _create(this, __privateGet(this, _httpRequest), document, "create", options);
1667
+ }
1668
+ createIfNotExists(document, options) {
1669
+ return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
1670
+ }
1671
+ createOrReplace(document, options) {
1672
+ return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
1673
+ }
1674
+ delete(selection, options) {
1675
+ return _delete(this, __privateGet(this, _httpRequest), selection, options);
1676
+ }
1677
+ mutate(operations, options) {
1678
+ return _mutate(this, __privateGet(this, _httpRequest), operations, options);
1679
+ }
1680
+ /**
1681
+ * Create a new buildable patch of operations to perform
1682
+ *
1683
+ * @param documentId - Document ID(s) to patch
1684
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1685
+ */
1686
+ patch(documentId, operations) {
1687
+ return new ObservablePatch(documentId, operations, this);
1688
+ }
1689
+ /**
1690
+ * Create a new transaction of mutations
1691
+ *
1692
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1693
+ */
1694
+ transaction(operations) {
1695
+ return new ObservableTransaction(operations, this);
1696
+ }
1697
+ /**
1698
+ * DEPRECATED: Perform an HTTP request against the Sanity API
1699
+ *
1700
+ * @deprecated Use your own request library!
1701
+ * @param options - Request options
1702
+ */
1703
+ request(options) {
1704
+ return _request(this, __privateGet(this, _httpRequest), options);
1705
+ }
1706
+ /**
1707
+ * Get a Sanity API URL for the URI provided
1708
+ *
1709
+ * @param uri - URI/path to build URL for
1710
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1711
+ */
1712
+ getUrl(uri, canUseCdn) {
1713
+ return _getUrl(this, uri, canUseCdn);
1714
+ }
1715
+ /**
1716
+ * Get a Sanity API URL for the data operation and path provided
1717
+ *
1718
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1719
+ * @param path - Path to append after the operation
1720
+ */
1721
+ getDataUrl(operation, path) {
1722
+ return _getDataUrl(this, operation, path);
1723
+ }
1724
+ };
1725
+ _clientConfig = new WeakMap();
1726
+ _httpRequest = new WeakMap();
1727
+ let ObservableSanityClient = _ObservableSanityClient;
1728
+ const _SanityClient = class _SanityClient {
1729
+ constructor(httpRequest) {
1730
+ let config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig;
1731
+ __publicField(this, "assets");
1732
+ __publicField(this, "datasets");
1733
+ __publicField(this, "projects");
1734
+ __publicField(this, "users");
1735
+ /**
1736
+ * Observable version of the Sanity client, with the same configuration as the promise-based one
1737
+ */
1738
+ __publicField(this, "observable");
1739
+ /**
1740
+ * Private properties
1741
+ */
1742
+ __privateAdd(this, _clientConfig2, void 0);
1743
+ __privateAdd(this, _httpRequest2, void 0);
1744
+ /**
1745
+ * Instance properties
1746
+ */
1747
+ __publicField(this, "listen", _listen);
1748
+ this.config(config);
1749
+ __privateSet(this, _httpRequest2, httpRequest);
1750
+ this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2));
1751
+ this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2));
1752
+ this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2));
1753
+ this.users = new UsersClient(this, __privateGet(this, _httpRequest2));
1754
+ this.observable = new ObservableSanityClient(httpRequest, config);
1755
+ }
1756
+ /**
1757
+ * Clone the client - returns a new instance
1758
+ */
1759
+ clone() {
1760
+ return new _SanityClient(__privateGet(this, _httpRequest2), this.config());
1761
+ }
1762
+ config(newConfig) {
1763
+ if (newConfig === void 0) {
1764
+ return {
1765
+ ...__privateGet(this, _clientConfig2)
1766
+ };
1767
+ }
1768
+ if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === false) {
1769
+ throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");
1770
+ }
1771
+ if (this.observable) {
1772
+ this.observable.config(newConfig);
1773
+ }
1774
+ __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {}));
1775
+ return this;
1776
+ }
1777
+ /**
1778
+ * Clone the client with a new (partial) configuration.
1779
+ *
1780
+ * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1781
+ */
1782
+ withConfig(newConfig) {
1783
+ return new _SanityClient(__privateGet(this, _httpRequest2), {
1784
+ ...this.config(),
1785
+ ...newConfig
1786
+ });
1787
+ }
1788
+ fetch(query, params) {
1789
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1790
+ return lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
1791
+ }
1792
+ /**
1793
+ * Fetch a single document with the given ID.
1794
+ *
1795
+ * @param id - Document ID to fetch
1796
+ * @param options - Request options
1797
+ */
1798
+ getDocument(id, options) {
1799
+ return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
1800
+ }
1801
+ /**
1802
+ * Fetch multiple documents in one request.
1803
+ * Should be used sparingly - performing a query is usually a better option.
1804
+ * The order/position of documents is preserved based on the original array of IDs.
1805
+ * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1806
+ *
1807
+ * @param ids - Document IDs to fetch
1808
+ * @param options - Request options
1809
+ */
1810
+ getDocuments(ids, options) {
1811
+ return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
1812
+ }
1813
+ create(document, options) {
1814
+ return lastValueFrom(_create(this, __privateGet(this, _httpRequest2), document, "create", options));
1815
+ }
1816
+ createIfNotExists(document, options) {
1817
+ return lastValueFrom(_createIfNotExists(this, __privateGet(this, _httpRequest2), document, options));
1818
+ }
1819
+ createOrReplace(document, options) {
1820
+ return lastValueFrom(_createOrReplace(this, __privateGet(this, _httpRequest2), document, options));
1821
+ }
1822
+ delete(selection, options) {
1823
+ return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
1824
+ }
1825
+ mutate(operations, options) {
1826
+ return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
1827
+ }
1828
+ /**
1829
+ * Create a new buildable patch of operations to perform
1830
+ *
1831
+ * @param documentId - Document ID(s)to patch
1832
+ * @param operations - Optional object of patch operations to initialize the patch instance with
1833
+ */
1834
+ patch(documentId, operations) {
1835
+ return new Patch(documentId, operations, this);
1836
+ }
1837
+ /**
1838
+ * Create a new transaction of mutations
1839
+ *
1840
+ * @param operations - Optional array of mutation operations to initialize the transaction instance with
1841
+ */
1842
+ transaction(operations) {
1843
+ return new Transaction(operations, this);
1844
+ }
1845
+ /**
1846
+ * Perform a request against the Sanity API
1847
+ * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
1848
+ *
1849
+ * @param options - Request options
1850
+ * @returns Promise resolving to the response body
1851
+ */
1852
+ request(options) {
1853
+ return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
1854
+ }
1855
+ /**
1856
+ * Perform an HTTP request a `/data` sub-endpoint
1857
+ * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
1858
+ *
1859
+ * @deprecated - Use `request()` or your own HTTP library instead
1860
+ * @param endpoint - Endpoint to hit (mutate, query etc)
1861
+ * @param body - Request body
1862
+ * @param options - Request options
1863
+ * @internal
1864
+ */
1865
+ dataRequest(endpoint, body, options) {
1866
+ return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
1867
+ }
1868
+ /**
1869
+ * Get a Sanity API URL for the URI provided
1870
+ *
1871
+ * @param uri - URI/path to build URL for
1872
+ * @param canUseCdn - Whether or not to allow using the API CDN for this route
1873
+ */
1874
+ getUrl(uri, canUseCdn) {
1875
+ return _getUrl(this, uri, canUseCdn);
1876
+ }
1877
+ /**
1878
+ * Get a Sanity API URL for the data operation and path provided
1879
+ *
1880
+ * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1881
+ * @param path - Path to append after the operation
1882
+ */
1883
+ getDataUrl(operation, path) {
1884
+ return _getDataUrl(this, operation, path);
1885
+ }
1886
+ };
1887
+ _clientConfig2 = new WeakMap();
1888
+ _httpRequest2 = new WeakMap();
1889
+ let SanityClient = _SanityClient;
1890
+ export { BasePatch, BaseTransaction, ClientError, ObservablePatch, ObservableSanityClient, ObservableTransaction, Patch, SanityClient, ServerError, Transaction, defineHttpRequest, printNoDefaultExport };
1891
+ //# sourceMappingURL=SanityClient-fcc9ccd6.js.map