@sanity/client 6.7.1-pink-lizard.4 → 6.7.1

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