@sanity/client 6.4.3 → 6.4.5-canary.0

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