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