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