@sanity/client 0.0.0-dev.0

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