@sanity/client 3.3.3-esm.7 → 3.3.3-esm.8

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.
@@ -5,9 +5,6 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
5
  var __esm = (fn, res) => function __init() {
6
6
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
7
  };
8
- var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
8
  var __export = (target, all) => {
12
9
  for (var name in all)
13
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -22,26 +19,24 @@ var __copyProps = (to, from, except, desc) => {
22
19
  };
23
20
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
21
 
25
- // src/util/observable-modern.js
26
- var observable_modern_exports = {};
27
- __export(observable_modern_exports, {
28
- Observable: () => Observable,
29
- filter: () => filter,
30
- map: () => map
22
+ // src/http/browserMiddleware.js
23
+ var browserMiddleware_exports = {};
24
+ __export(browserMiddleware_exports, {
25
+ default: () => browserMiddleware_default
31
26
  });
27
+ var browserMiddleware_default;
28
+ var init_browserMiddleware = __esm({
29
+ "src/http/browserMiddleware.js"() {
30
+ browserMiddleware_default = [];
31
+ }
32
+ });
33
+
34
+ // src/util/observable-modern.js
32
35
  import { Observable } from "rxjs-v7/internal/Observable";
33
36
  import { filter } from "rxjs-v7/internal/operators/filter";
34
37
  import { map } from "rxjs-v7/internal/operators/map";
35
- var init_observable_modern = __esm({
36
- "src/util/observable-modern.js"() {
37
- }
38
- });
39
38
 
40
39
  // src/util/getSelection.js
41
- var getSelection_exports = {};
42
- __export(getSelection_exports, {
43
- default: () => getSelection
44
- });
45
40
  function getSelection(sel) {
46
41
  if (typeof sel === "string" || Array.isArray(sel)) {
47
42
  return { id: sel };
@@ -58,812 +53,694 @@ function getSelection(sel) {
58
53
 
59
54
  ${selectionOpts}`);
60
55
  }
61
- var init_getSelection = __esm({
62
- "src/util/getSelection.js"() {
63
- }
64
- });
65
56
 
66
57
  // src/validators.js
67
- var validators_exports = {};
68
- __export(validators_exports, {
69
- dataset: () => dataset,
70
- hasDataset: () => hasDataset,
71
- projectId: () => projectId,
72
- requestTag: () => requestTag,
73
- requireDocumentId: () => requireDocumentId,
74
- validateAssetType: () => validateAssetType,
75
- validateDocumentId: () => validateDocumentId,
76
- validateInsert: () => validateInsert,
77
- validateObject: () => validateObject
78
- });
79
- var VALID_ASSET_TYPES, VALID_INSERT_LOCATIONS, dataset, projectId, validateAssetType, validateObject, validateDocumentId, requireDocumentId, validateInsert, hasDataset, requestTag;
80
- var init_validators = __esm({
81
- "src/validators.js"() {
82
- VALID_ASSET_TYPES = ["image", "file"];
83
- VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
84
- dataset = (name) => {
85
- if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
86
- throw new Error(
87
- "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
88
- );
89
- }
90
- };
91
- projectId = (id) => {
92
- if (!/^[-a-z0-9]+$/i.test(id)) {
93
- throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
94
- }
95
- };
96
- validateAssetType = (type) => {
97
- if (VALID_ASSET_TYPES.indexOf(type) === -1) {
98
- throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
99
- }
100
- };
101
- validateObject = (op, val) => {
102
- if (val === null || typeof val !== "object" || Array.isArray(val)) {
103
- throw new Error(`${op}() takes an object of properties`);
104
- }
105
- };
106
- validateDocumentId = (op, id) => {
107
- if (typeof id !== "string" || !/^[a-z0-9_.-]+$/i.test(id)) {
108
- throw new Error(`${op}(): "${id}" is not a valid document ID`);
109
- }
110
- };
111
- requireDocumentId = (op, doc) => {
112
- if (!doc._id) {
113
- throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
114
- }
115
- validateDocumentId(op, doc._id);
116
- };
117
- validateInsert = (at, selector, items) => {
118
- const signature = "insert(at, selector, items)";
119
- if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
120
- const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
121
- throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
122
- }
123
- if (typeof selector !== "string") {
124
- throw new Error(`${signature} takes a "selector"-argument which must be a string`);
125
- }
126
- if (!Array.isArray(items)) {
127
- throw new Error(`${signature} takes an "items"-argument which must be an array`);
128
- }
129
- };
130
- hasDataset = (config) => {
131
- if (!config.dataset) {
132
- throw new Error("`dataset` must be provided to perform queries");
133
- }
134
- return config.dataset || "";
135
- };
136
- requestTag = (tag) => {
137
- if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
138
- throw new Error(
139
- `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`
140
- );
141
- }
142
- return tag;
143
- };
58
+ var VALID_ASSET_TYPES = ["image", "file"];
59
+ var VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
60
+ var dataset = (name) => {
61
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
62
+ throw new Error(
63
+ "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
64
+ );
144
65
  }
145
- });
66
+ };
67
+ var projectId = (id) => {
68
+ if (!/^[-a-z0-9]+$/i.test(id)) {
69
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
70
+ }
71
+ };
72
+ var validateAssetType = (type) => {
73
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) {
74
+ throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
75
+ }
76
+ };
77
+ var validateObject = (op, val) => {
78
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
79
+ throw new Error(`${op}() takes an object of properties`);
80
+ }
81
+ };
82
+ var validateDocumentId = (op, id) => {
83
+ if (typeof id !== "string" || !/^[a-z0-9_.-]+$/i.test(id)) {
84
+ throw new Error(`${op}(): "${id}" is not a valid document ID`);
85
+ }
86
+ };
87
+ var requireDocumentId = (op, doc) => {
88
+ if (!doc._id) {
89
+ throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
90
+ }
91
+ validateDocumentId(op, doc._id);
92
+ };
93
+ var validateInsert = (at, selector, items) => {
94
+ const signature = "insert(at, selector, items)";
95
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
96
+ const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
97
+ throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
98
+ }
99
+ if (typeof selector !== "string") {
100
+ throw new Error(`${signature} takes a "selector"-argument which must be a string`);
101
+ }
102
+ if (!Array.isArray(items)) {
103
+ throw new Error(`${signature} takes an "items"-argument which must be an array`);
104
+ }
105
+ };
106
+ var hasDataset = (config) => {
107
+ if (!config.dataset) {
108
+ throw new Error("`dataset` must be provided to perform queries");
109
+ }
110
+ return config.dataset || "";
111
+ };
112
+ var requestTag = (tag) => {
113
+ if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
114
+ throw new Error(
115
+ `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`
116
+ );
117
+ }
118
+ return tag;
119
+ };
146
120
 
147
121
  // src/data/patch.js
148
- var require_patch = __commonJS({
149
- "src/data/patch.js"(exports, module) {
150
- var getSelection2 = (init_getSelection(), __toCommonJS(getSelection_exports));
151
- var validate = (init_validators(), __toCommonJS(validators_exports));
152
- var validateObject2 = validate.validateObject;
153
- var validateInsert2 = validate.validateInsert;
154
- function Patch(selection, operations = {}, client = null) {
155
- this.selection = selection;
156
- this.operations = Object.assign({}, operations);
157
- this.client = client;
122
+ function Patch(selection, operations = {}, client = null) {
123
+ this.selection = selection;
124
+ this.operations = Object.assign({}, operations);
125
+ this.client = client;
126
+ }
127
+ Object.assign(Patch.prototype, {
128
+ clone() {
129
+ return new Patch(this.selection, Object.assign({}, this.operations), this.client);
130
+ },
131
+ set(props) {
132
+ return this.assign("set", props);
133
+ },
134
+ diffMatchPatch(props) {
135
+ validateObject("diffMatchPatch", props);
136
+ return this.assign("diffMatchPatch", props);
137
+ },
138
+ unset(attrs) {
139
+ if (!Array.isArray(attrs)) {
140
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
158
141
  }
159
- Object.assign(Patch.prototype, {
160
- clone() {
161
- return new Patch(this.selection, Object.assign({}, this.operations), this.client);
162
- },
163
- set(props) {
164
- return this.assign("set", props);
165
- },
166
- diffMatchPatch(props) {
167
- validateObject2("diffMatchPatch", props);
168
- return this.assign("diffMatchPatch", props);
169
- },
170
- unset(attrs) {
171
- if (!Array.isArray(attrs)) {
172
- throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
173
- }
174
- this.operations = Object.assign({}, this.operations, { unset: attrs });
175
- return this;
176
- },
177
- setIfMissing(props) {
178
- return this.assign("setIfMissing", props);
179
- },
180
- replace(props) {
181
- validateObject2("replace", props);
182
- return this._set("set", { $: props });
183
- },
184
- inc(props) {
185
- return this.assign("inc", props);
186
- },
187
- dec(props) {
188
- return this.assign("dec", props);
189
- },
190
- insert(at, selector, items) {
191
- validateInsert2(at, selector, items);
192
- return this.assign("insert", { [at]: selector, items });
193
- },
194
- append(selector, items) {
195
- return this.insert("after", `${selector}[-1]`, items);
196
- },
197
- prepend(selector, items) {
198
- return this.insert("before", `${selector}[0]`, items);
199
- },
200
- splice(selector, start, deleteCount, items) {
201
- const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
202
- const startIndex = start < 0 ? start - 1 : start;
203
- const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
204
- const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
205
- const rangeSelector = `${selector}[${startIndex}:${delRange}]`;
206
- return this.insert("replace", rangeSelector, items || []);
207
- },
208
- ifRevisionId(rev) {
209
- this.operations.ifRevisionID = rev;
210
- return this;
211
- },
212
- serialize() {
213
- return Object.assign(getSelection2(this.selection), this.operations);
214
- },
215
- toJSON() {
216
- return this.serialize();
217
- },
218
- commit(options = {}) {
219
- if (!this.client) {
220
- throw new Error(
221
- "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
222
- );
223
- }
224
- const returnFirst = typeof this.selection === "string";
225
- const opts = Object.assign({ returnFirst, returnDocuments: true }, options);
226
- return this.client.mutate({ patch: this.serialize() }, opts);
227
- },
228
- reset() {
229
- this.operations = {};
230
- return this;
231
- },
232
- _set(op, props) {
233
- return this.assign(op, props, false);
234
- },
235
- assign(op, props, merge = true) {
236
- validateObject2(op, props);
237
- this.operations = Object.assign({}, this.operations, {
238
- [op]: Object.assign({}, merge && this.operations[op] || {}, props)
239
- });
240
- return this;
241
- }
142
+ this.operations = Object.assign({}, this.operations, { unset: attrs });
143
+ return this;
144
+ },
145
+ setIfMissing(props) {
146
+ return this.assign("setIfMissing", props);
147
+ },
148
+ replace(props) {
149
+ validateObject("replace", props);
150
+ return this._set("set", { $: props });
151
+ },
152
+ inc(props) {
153
+ return this.assign("inc", props);
154
+ },
155
+ dec(props) {
156
+ return this.assign("dec", props);
157
+ },
158
+ insert(at, selector, items) {
159
+ validateInsert(at, selector, items);
160
+ return this.assign("insert", { [at]: selector, items });
161
+ },
162
+ append(selector, items) {
163
+ return this.insert("after", `${selector}[-1]`, items);
164
+ },
165
+ prepend(selector, items) {
166
+ return this.insert("before", `${selector}[0]`, items);
167
+ },
168
+ splice(selector, start, deleteCount, items) {
169
+ const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
170
+ const startIndex = start < 0 ? start - 1 : start;
171
+ const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
172
+ const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
173
+ const rangeSelector = `${selector}[${startIndex}:${delRange}]`;
174
+ return this.insert("replace", rangeSelector, items || []);
175
+ },
176
+ ifRevisionId(rev) {
177
+ this.operations.ifRevisionID = rev;
178
+ return this;
179
+ },
180
+ serialize() {
181
+ return Object.assign(getSelection(this.selection), this.operations);
182
+ },
183
+ toJSON() {
184
+ return this.serialize();
185
+ },
186
+ commit(options = {}) {
187
+ if (!this.client) {
188
+ throw new Error(
189
+ "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
190
+ );
191
+ }
192
+ const returnFirst = typeof this.selection === "string";
193
+ const opts = Object.assign({ returnFirst, returnDocuments: true }, options);
194
+ return this.client.mutate({ patch: this.serialize() }, opts);
195
+ },
196
+ reset() {
197
+ this.operations = {};
198
+ return this;
199
+ },
200
+ _set(op, props) {
201
+ return this.assign(op, props, false);
202
+ },
203
+ assign(op, props, merge = true) {
204
+ validateObject(op, props);
205
+ this.operations = Object.assign({}, this.operations, {
206
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
242
207
  });
243
- module.exports = Patch;
208
+ return this;
244
209
  }
245
210
  });
211
+ var patch_default = Patch;
246
212
 
247
213
  // src/data/transaction.js
248
- var require_transaction = __commonJS({
249
- "src/data/transaction.js"(exports, module) {
250
- var validators = (init_validators(), __toCommonJS(validators_exports));
251
- var Patch = require_patch();
252
- var defaultMutateOptions = { returnDocuments: false };
253
- function Transaction(operations = [], client, transactionId) {
254
- this.trxId = transactionId;
255
- this.operations = operations;
256
- this.client = client;
214
+ var defaultMutateOptions = { returnDocuments: false };
215
+ function Transaction(operations = [], client, transactionId) {
216
+ this.trxId = transactionId;
217
+ this.operations = operations;
218
+ this.client = client;
219
+ }
220
+ Object.assign(Transaction.prototype, {
221
+ clone() {
222
+ return new Transaction(this.operations.slice(0), this.client, this.trxId);
223
+ },
224
+ create(doc) {
225
+ validateObject("create", doc);
226
+ return this._add({ create: doc });
227
+ },
228
+ createIfNotExists(doc) {
229
+ const op = "createIfNotExists";
230
+ validateObject(op, doc);
231
+ requireDocumentId(op, doc);
232
+ return this._add({ [op]: doc });
233
+ },
234
+ createOrReplace(doc) {
235
+ const op = "createOrReplace";
236
+ validateObject(op, doc);
237
+ requireDocumentId(op, doc);
238
+ return this._add({ [op]: doc });
239
+ },
240
+ delete(documentId) {
241
+ validateDocumentId("delete", documentId);
242
+ return this._add({ delete: { id: documentId } });
243
+ },
244
+ patch(documentId, patchOps) {
245
+ const isBuilder = typeof patchOps === "function";
246
+ const isPatch = documentId instanceof patch_default;
247
+ if (isPatch) {
248
+ return this._add({ patch: documentId.serialize() });
257
249
  }
258
- Object.assign(Transaction.prototype, {
259
- clone() {
260
- return new Transaction(this.operations.slice(0), this.client, this.trxId);
261
- },
262
- create(doc) {
263
- validators.validateObject("create", doc);
264
- return this._add({ create: doc });
265
- },
266
- createIfNotExists(doc) {
267
- const op = "createIfNotExists";
268
- validators.validateObject(op, doc);
269
- validators.requireDocumentId(op, doc);
270
- return this._add({ [op]: doc });
271
- },
272
- createOrReplace(doc) {
273
- const op = "createOrReplace";
274
- validators.validateObject(op, doc);
275
- validators.requireDocumentId(op, doc);
276
- return this._add({ [op]: doc });
277
- },
278
- delete(documentId) {
279
- validators.validateDocumentId("delete", documentId);
280
- return this._add({ delete: { id: documentId } });
281
- },
282
- patch(documentId, patchOps) {
283
- const isBuilder = typeof patchOps === "function";
284
- const isPatch = documentId instanceof Patch;
285
- if (isPatch) {
286
- return this._add({ patch: documentId.serialize() });
287
- }
288
- if (isBuilder) {
289
- const patch = patchOps(new Patch(documentId, {}, this.client));
290
- if (!(patch instanceof Patch)) {
291
- throw new Error("function passed to `patch()` must return the patch");
292
- }
293
- return this._add({ patch: patch.serialize() });
294
- }
295
- return this._add({ patch: Object.assign({ id: documentId }, patchOps) });
296
- },
297
- transactionId(id) {
298
- if (!id) {
299
- return this.trxId;
300
- }
301
- this.trxId = id;
302
- return this;
303
- },
304
- serialize() {
305
- return this.operations.slice();
306
- },
307
- toJSON() {
308
- return this.serialize();
309
- },
310
- commit(options) {
311
- if (!this.client) {
312
- throw new Error(
313
- "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
314
- );
315
- }
316
- return this.client.mutate(
317
- this.serialize(),
318
- Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
319
- );
320
- },
321
- reset() {
322
- this.operations = [];
323
- return this;
324
- },
325
- _add(mut) {
326
- this.operations.push(mut);
327
- return this;
250
+ if (isBuilder) {
251
+ const patch = patchOps(new patch_default(documentId, {}, this.client));
252
+ if (!(patch instanceof patch_default)) {
253
+ throw new Error("function passed to `patch()` must return the patch");
328
254
  }
329
- });
330
- module.exports = Transaction;
255
+ return this._add({ patch: patch.serialize() });
256
+ }
257
+ return this._add({ patch: Object.assign({ id: documentId }, patchOps) });
258
+ },
259
+ transactionId(id) {
260
+ if (!id) {
261
+ return this.trxId;
262
+ }
263
+ this.trxId = id;
264
+ return this;
265
+ },
266
+ serialize() {
267
+ return this.operations.slice();
268
+ },
269
+ toJSON() {
270
+ return this.serialize();
271
+ },
272
+ commit(options) {
273
+ if (!this.client) {
274
+ throw new Error(
275
+ "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
276
+ );
277
+ }
278
+ return this.client.mutate(
279
+ this.serialize(),
280
+ Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
281
+ );
282
+ },
283
+ reset() {
284
+ this.operations = [];
285
+ return this;
286
+ },
287
+ _add(mut) {
288
+ this.operations.push(mut);
289
+ return this;
331
290
  }
332
291
  });
292
+ var transaction_default = Transaction;
333
293
 
334
294
  // src/data/encodeQueryString.js
335
- var encodeQueryString_exports = {};
336
- __export(encodeQueryString_exports, {
337
- default: () => encodeQueryString_default
338
- });
339
- var enc, encodeQueryString_default;
340
- var init_encodeQueryString = __esm({
341
- "src/data/encodeQueryString.js"() {
342
- enc = encodeURIComponent;
343
- encodeQueryString_default = ({ query, params = {}, options = {} }) => {
344
- const { tag, ...opts } = options;
345
- const q = `query=${enc(query)}`;
346
- const base = tag ? `?tag=${enc(tag)}&${q}` : `?${q}`;
347
- const qString = Object.keys(params).reduce(
348
- (qs, param) => `${qs}&${enc(`$${param}`)}=${enc(JSON.stringify(params[param]))}`,
349
- base
350
- );
351
- return Object.keys(opts).reduce((qs, option) => {
352
- return options[option] ? `${qs}&${enc(option)}=${enc(options[option])}` : qs;
353
- }, qString);
354
- };
355
- }
356
- });
295
+ var enc = encodeURIComponent;
296
+ var encodeQueryString_default = ({ query, params = {}, options = {} }) => {
297
+ const { tag, ...opts } = options;
298
+ const q = `query=${enc(query)}`;
299
+ const base = tag ? `?tag=${enc(tag)}&${q}` : `?${q}`;
300
+ const qString = Object.keys(params).reduce(
301
+ (qs, param) => `${qs}&${enc(`$${param}`)}=${enc(JSON.stringify(params[param]))}`,
302
+ base
303
+ );
304
+ return Object.keys(opts).reduce((qs, option) => {
305
+ return options[option] ? `${qs}&${enc(option)}=${enc(options[option])}` : qs;
306
+ }, qString);
307
+ };
308
+
309
+ // src/data/listen.js
310
+ import polyfilledEventSource from "@sanity/eventsource";
357
311
 
358
312
  // src/util/pick.js
359
- var pick_exports = {};
360
- __export(pick_exports, {
361
- default: () => pick_default
362
- });
363
- var pick_default;
364
- var init_pick = __esm({
365
- "src/util/pick.js"() {
366
- pick_default = (obj, props) => props.reduce((selection, prop) => {
367
- if (typeof obj[prop] === "undefined") {
368
- return selection;
369
- }
370
- selection[prop] = obj[prop];
371
- return selection;
372
- }, {});
313
+ var pick_default = (obj, props) => props.reduce((selection, prop) => {
314
+ if (typeof obj[prop] === "undefined") {
315
+ return selection;
373
316
  }
374
- });
317
+ selection[prop] = obj[prop];
318
+ return selection;
319
+ }, {});
375
320
 
376
321
  // src/util/defaults.js
377
- var defaults_exports = {};
378
- __export(defaults_exports, {
379
- default: () => defaults_default
380
- });
381
- var defaults_default;
382
- var init_defaults = __esm({
383
- "src/util/defaults.js"() {
384
- defaults_default = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
385
- target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
386
- return target;
387
- }, {});
388
- }
389
- });
322
+ var defaults_default = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
323
+ target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
324
+ return target;
325
+ }, {});
390
326
 
391
327
  // src/data/listen.js
392
- import polyfilledEventSource from "@sanity/eventsource";
393
- var require_listen = __commonJS({
394
- "src/data/listen.js"(exports, module) {
395
- var { Observable: Observable2 } = (init_observable_modern(), __toCommonJS(observable_modern_exports));
396
- var pick = (init_pick(), __toCommonJS(pick_exports));
397
- var defaults = (init_defaults(), __toCommonJS(defaults_exports));
398
- var encodeQueryString = (init_encodeQueryString(), __toCommonJS(encodeQueryString_exports));
399
- var MAX_URL_LENGTH = 16e3 - 1200;
400
- var EventSource = polyfilledEventSource;
401
- var possibleOptions = [
402
- "includePreviousRevision",
403
- "includeResult",
404
- "visibility",
405
- "effectFormat",
406
- "tag"
407
- ];
408
- var defaultOptions = {
409
- includeResult: true
328
+ var MAX_URL_LENGTH = 16e3 - 1200;
329
+ var EventSource = polyfilledEventSource;
330
+ var possibleOptions = [
331
+ "includePreviousRevision",
332
+ "includeResult",
333
+ "visibility",
334
+ "effectFormat",
335
+ "tag"
336
+ ];
337
+ var defaultOptions = {
338
+ includeResult: true
339
+ };
340
+ function listen(query, params, opts = {}) {
341
+ const { url, token, withCredentials, requestTagPrefix } = this.clientConfig;
342
+ const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
343
+ const options = { ...defaults_default(opts, defaultOptions), tag };
344
+ const listenOpts = pick_default(options, possibleOptions);
345
+ const qs = encodeQueryString_default({ query, params, options: listenOpts, tag });
346
+ const uri = `${url}${this.getDataUrl("listen", qs)}`;
347
+ if (uri.length > MAX_URL_LENGTH) {
348
+ return new Observable((observer) => observer.error(new Error("Query too large for listener")));
349
+ }
350
+ const listenFor = options.events ? options.events : ["mutation"];
351
+ const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
352
+ const esOptions = {};
353
+ if (token || withCredentials) {
354
+ esOptions.withCredentials = true;
355
+ }
356
+ if (token) {
357
+ esOptions.headers = {
358
+ Authorization: `Bearer ${token}`
410
359
  };
411
- module.exports = function listen(query, params, opts = {}) {
412
- const { url, token, withCredentials, requestTagPrefix } = this.clientConfig;
413
- const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
414
- const options = { ...defaults(opts, defaultOptions), tag };
415
- const listenOpts = pick(options, possibleOptions);
416
- const qs = encodeQueryString({ query, params, options: listenOpts, tag });
417
- const uri = `${url}${this.getDataUrl("listen", qs)}`;
418
- if (uri.length > MAX_URL_LENGTH) {
419
- return new Observable2((observer) => observer.error(new Error("Query too large for listener")));
420
- }
421
- const listenFor = options.events ? options.events : ["mutation"];
422
- const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
423
- const esOptions = {};
424
- if (token || withCredentials) {
425
- esOptions.withCredentials = true;
360
+ }
361
+ return new Observable((observer) => {
362
+ let es = getEventSource();
363
+ let reconnectTimer;
364
+ let stopped = false;
365
+ function onError() {
366
+ if (stopped) {
367
+ return;
426
368
  }
427
- if (token) {
428
- esOptions.headers = {
429
- Authorization: `Bearer ${token}`
430
- };
369
+ emitReconnect();
370
+ if (stopped) {
371
+ return;
431
372
  }
432
- return new Observable2((observer) => {
433
- let es = getEventSource();
434
- let reconnectTimer;
435
- let stopped = false;
436
- function onError() {
437
- if (stopped) {
438
- return;
439
- }
440
- emitReconnect();
441
- if (stopped) {
442
- return;
443
- }
444
- if (es.readyState === EventSource.CLOSED) {
445
- unsubscribe();
446
- clearTimeout(reconnectTimer);
447
- reconnectTimer = setTimeout(open, 100);
448
- }
449
- }
450
- function onChannelError(err) {
451
- observer.error(cooerceError(err));
452
- }
453
- function onMessage(evt) {
454
- const event = parseEvent(evt);
455
- return event instanceof Error ? observer.error(event) : observer.next(event);
456
- }
457
- function onDisconnect(evt) {
458
- stopped = true;
459
- unsubscribe();
460
- observer.complete();
461
- }
462
- function unsubscribe() {
463
- es.removeEventListener("error", onError, false);
464
- es.removeEventListener("channelError", onChannelError, false);
465
- es.removeEventListener("disconnect", onDisconnect, false);
466
- listenFor.forEach((type) => es.removeEventListener(type, onMessage, false));
467
- es.close();
468
- }
469
- function emitReconnect() {
470
- if (shouldEmitReconnect) {
471
- observer.next({ type: "reconnect" });
472
- }
473
- }
474
- function getEventSource() {
475
- const evs = new EventSource(uri, esOptions);
476
- evs.addEventListener("error", onError, false);
477
- evs.addEventListener("channelError", onChannelError, false);
478
- evs.addEventListener("disconnect", onDisconnect, false);
479
- listenFor.forEach((type) => evs.addEventListener(type, onMessage, false));
480
- return evs;
481
- }
482
- function open() {
483
- es = getEventSource();
484
- }
485
- function stop() {
486
- stopped = true;
487
- unsubscribe();
488
- }
489
- return stop;
490
- });
491
- };
492
- function parseEvent(event) {
493
- try {
494
- const data = event.data && JSON.parse(event.data) || {};
495
- return Object.assign({ type: event.type }, data);
496
- } catch (err) {
497
- return err;
373
+ if (es.readyState === EventSource.CLOSED) {
374
+ unsubscribe();
375
+ clearTimeout(reconnectTimer);
376
+ reconnectTimer = setTimeout(open, 100);
498
377
  }
499
378
  }
500
- function cooerceError(err) {
501
- if (err instanceof Error) {
502
- return err;
503
- }
504
- const evt = parseEvent(err);
505
- return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
379
+ function onChannelError(err) {
380
+ observer.error(cooerceError(err));
506
381
  }
507
- function extractErrorMessage(err) {
508
- if (!err.error) {
509
- return err.message || "Unknown listener error";
510
- }
511
- if (err.error.description) {
512
- return err.error.description;
382
+ function onMessage(evt) {
383
+ const event = parseEvent(evt);
384
+ return event instanceof Error ? observer.error(event) : observer.next(event);
385
+ }
386
+ function onDisconnect(evt) {
387
+ stopped = true;
388
+ unsubscribe();
389
+ observer.complete();
390
+ }
391
+ function unsubscribe() {
392
+ es.removeEventListener("error", onError, false);
393
+ es.removeEventListener("channelError", onChannelError, false);
394
+ es.removeEventListener("disconnect", onDisconnect, false);
395
+ listenFor.forEach((type) => es.removeEventListener(type, onMessage, false));
396
+ es.close();
397
+ }
398
+ function emitReconnect() {
399
+ if (shouldEmitReconnect) {
400
+ observer.next({ type: "reconnect" });
513
401
  }
514
- return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
515
402
  }
403
+ function getEventSource() {
404
+ const evs = new EventSource(uri, esOptions);
405
+ evs.addEventListener("error", onError, false);
406
+ evs.addEventListener("channelError", onChannelError, false);
407
+ evs.addEventListener("disconnect", onDisconnect, false);
408
+ listenFor.forEach((type) => evs.addEventListener(type, onMessage, false));
409
+ return evs;
410
+ }
411
+ function open() {
412
+ es = getEventSource();
413
+ }
414
+ function stop() {
415
+ stopped = true;
416
+ unsubscribe();
417
+ }
418
+ return stop;
419
+ });
420
+ }
421
+ function parseEvent(event) {
422
+ try {
423
+ const data = event.data && JSON.parse(event.data) || {};
424
+ return Object.assign({ type: event.type }, data);
425
+ } catch (err) {
426
+ return err;
516
427
  }
517
- });
428
+ }
429
+ function cooerceError(err) {
430
+ if (err instanceof Error) {
431
+ return err;
432
+ }
433
+ const evt = parseEvent(err);
434
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
435
+ }
436
+ function extractErrorMessage(err) {
437
+ if (!err.error) {
438
+ return err.message || "Unknown listener error";
439
+ }
440
+ if (err.error.description) {
441
+ return err.error.description;
442
+ }
443
+ return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
444
+ }
518
445
 
519
446
  // src/data/dataMethods.js
520
- var require_dataMethods = __commonJS({
521
- "src/data/dataMethods.js"(exports, module) {
522
- var { map: map2, filter: filter2 } = (init_observable_modern(), __toCommonJS(observable_modern_exports));
523
- var validators = (init_validators(), __toCommonJS(validators_exports));
524
- var getSelection2 = (init_getSelection(), __toCommonJS(getSelection_exports));
525
- var encodeQueryString = (init_encodeQueryString(), __toCommonJS(encodeQueryString_exports));
526
- var Transaction = require_transaction();
527
- var Patch = require_patch();
528
- var listen = require_listen();
529
- var excludeFalsey = (param, defValue) => {
530
- const value = typeof param === "undefined" ? defValue : param;
531
- return param === false ? void 0 : value;
532
- };
533
- var getMutationQuery = (options = {}) => {
534
- return {
535
- dryRun: options.dryRun,
536
- returnIds: true,
537
- returnDocuments: excludeFalsey(options.returnDocuments, true),
538
- visibility: options.visibility || "sync",
539
- autoGenerateArrayKeys: options.autoGenerateArrayKeys,
540
- skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
541
- };
447
+ var excludeFalsey = (param, defValue) => {
448
+ const value = typeof param === "undefined" ? defValue : param;
449
+ return param === false ? void 0 : value;
450
+ };
451
+ var getMutationQuery = (options = {}) => {
452
+ return {
453
+ dryRun: options.dryRun,
454
+ returnIds: true,
455
+ returnDocuments: excludeFalsey(options.returnDocuments, true),
456
+ visibility: options.visibility || "sync",
457
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
458
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
459
+ };
460
+ };
461
+ var isResponse = (event) => event.type === "response";
462
+ var getBody = (event) => event.body;
463
+ var indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
464
+ indexed[attr(doc)] = doc;
465
+ return indexed;
466
+ }, /* @__PURE__ */ Object.create(null));
467
+ var toPromise = (observable2) => observable2.toPromise();
468
+ var getQuerySizeLimit = 11264;
469
+ var dataMethods_default = {
470
+ listen,
471
+ getDataUrl(operation, path) {
472
+ const config = this.clientConfig;
473
+ const catalog = hasDataset(config);
474
+ const baseUri = `/${operation}/${catalog}`;
475
+ const uri = path ? `${baseUri}/${path}` : baseUri;
476
+ return `/data${uri}`.replace(/\/($|\?)/, "$1");
477
+ },
478
+ fetch(query, params, options = {}) {
479
+ const mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result;
480
+ const observable2 = this._dataRequest("query", { query, params }, options).pipe(map(mapResponse));
481
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
482
+ },
483
+ getDocument(id, opts = {}) {
484
+ const options = { uri: this.getDataUrl("doc", id), json: true, tag: opts.tag };
485
+ const observable2 = this._requestObservable(options).pipe(
486
+ filter(isResponse),
487
+ map((event) => event.body.documents && event.body.documents[0])
488
+ );
489
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
490
+ },
491
+ getDocuments(ids, opts = {}) {
492
+ const options = { uri: this.getDataUrl("doc", ids.join(",")), json: true, tag: opts.tag };
493
+ const observable2 = this._requestObservable(options).pipe(
494
+ filter(isResponse),
495
+ map((event) => {
496
+ const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
497
+ return ids.map((id) => indexed[id] || null);
498
+ })
499
+ );
500
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
501
+ },
502
+ create(doc, options) {
503
+ return this._create(doc, "create", options);
504
+ },
505
+ createIfNotExists(doc, options) {
506
+ requireDocumentId("createIfNotExists", doc);
507
+ return this._create(doc, "createIfNotExists", options);
508
+ },
509
+ createOrReplace(doc, options) {
510
+ requireDocumentId("createOrReplace", doc);
511
+ return this._create(doc, "createOrReplace", options);
512
+ },
513
+ patch(selector, operations) {
514
+ return new patch_default(selector, operations, this);
515
+ },
516
+ delete(selection, options) {
517
+ return this.dataRequest("mutate", { mutations: [{ delete: getSelection(selection) }] }, options);
518
+ },
519
+ mutate(mutations, options) {
520
+ const mut = mutations instanceof patch_default || mutations instanceof transaction_default ? mutations.serialize() : mutations;
521
+ const muts = Array.isArray(mut) ? mut : [mut];
522
+ const transactionId = options && options.transactionId;
523
+ return this.dataRequest("mutate", { mutations: muts, transactionId }, options);
524
+ },
525
+ transaction(operations) {
526
+ return new transaction_default(operations, this);
527
+ },
528
+ dataRequest(endpoint, body, options = {}) {
529
+ const request2 = this._dataRequest(endpoint, body, options);
530
+ return this.isPromiseAPI() ? toPromise(request2) : request2;
531
+ },
532
+ _dataRequest(endpoint, body, options = {}) {
533
+ const isMutation = endpoint === "mutate";
534
+ const isQuery = endpoint === "query";
535
+ const strQuery = !isMutation && encodeQueryString_default(body);
536
+ const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
537
+ const stringQuery = useGet ? strQuery : "";
538
+ const returnFirst = options.returnFirst;
539
+ const { timeout, token, tag, headers } = options;
540
+ const uri = this.getDataUrl(endpoint, stringQuery);
541
+ const reqOptions = {
542
+ method: useGet ? "GET" : "POST",
543
+ uri,
544
+ json: true,
545
+ body: useGet ? void 0 : body,
546
+ query: isMutation && getMutationQuery(options),
547
+ timeout,
548
+ headers,
549
+ token,
550
+ tag,
551
+ canUseCdn: isQuery
542
552
  };
543
- var isResponse = (event) => event.type === "response";
544
- var getBody = (event) => event.body;
545
- var indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
546
- indexed[attr(doc)] = doc;
547
- return indexed;
548
- }, /* @__PURE__ */ Object.create(null));
549
- var toPromise = (observable2) => observable2.toPromise();
550
- var getQuerySizeLimit = 11264;
551
- module.exports = {
552
- listen,
553
- getDataUrl(operation, path) {
554
- const config = this.clientConfig;
555
- const catalog = validators.hasDataset(config);
556
- const baseUri = `/${operation}/${catalog}`;
557
- const uri = path ? `${baseUri}/${path}` : baseUri;
558
- return `/data${uri}`.replace(/\/($|\?)/, "$1");
559
- },
560
- fetch(query, params, options = {}) {
561
- const mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result;
562
- const observable2 = this._dataRequest("query", { query, params }, options).pipe(map2(mapResponse));
563
- return this.isPromiseAPI() ? toPromise(observable2) : observable2;
564
- },
565
- getDocument(id, opts = {}) {
566
- const options = { uri: this.getDataUrl("doc", id), json: true, tag: opts.tag };
567
- const observable2 = this._requestObservable(options).pipe(
568
- filter2(isResponse),
569
- map2((event) => event.body.documents && event.body.documents[0])
570
- );
571
- return this.isPromiseAPI() ? toPromise(observable2) : observable2;
572
- },
573
- getDocuments(ids, opts = {}) {
574
- const options = { uri: this.getDataUrl("doc", ids.join(",")), json: true, tag: opts.tag };
575
- const observable2 = this._requestObservable(options).pipe(
576
- filter2(isResponse),
577
- map2((event) => {
578
- const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
579
- return ids.map((id) => indexed[id] || null);
580
- })
581
- );
582
- return this.isPromiseAPI() ? toPromise(observable2) : observable2;
583
- },
584
- create(doc, options) {
585
- return this._create(doc, "create", options);
586
- },
587
- createIfNotExists(doc, options) {
588
- validators.requireDocumentId("createIfNotExists", doc);
589
- return this._create(doc, "createIfNotExists", options);
590
- },
591
- createOrReplace(doc, options) {
592
- validators.requireDocumentId("createOrReplace", doc);
593
- return this._create(doc, "createOrReplace", options);
594
- },
595
- patch(selector, operations) {
596
- return new Patch(selector, operations, this);
597
- },
598
- delete(selection, options) {
599
- return this.dataRequest("mutate", { mutations: [{ delete: getSelection2(selection) }] }, options);
600
- },
601
- mutate(mutations, options) {
602
- const mut = mutations instanceof Patch || mutations instanceof Transaction ? mutations.serialize() : mutations;
603
- const muts = Array.isArray(mut) ? mut : [mut];
604
- const transactionId = options && options.transactionId;
605
- return this.dataRequest("mutate", { mutations: muts, transactionId }, options);
606
- },
607
- transaction(operations) {
608
- return new Transaction(operations, this);
609
- },
610
- dataRequest(endpoint, body, options = {}) {
611
- const request2 = this._dataRequest(endpoint, body, options);
612
- return this.isPromiseAPI() ? toPromise(request2) : request2;
613
- },
614
- _dataRequest(endpoint, body, options = {}) {
615
- const isMutation = endpoint === "mutate";
616
- const isQuery = endpoint === "query";
617
- const strQuery = !isMutation && encodeQueryString(body);
618
- const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
619
- const stringQuery = useGet ? strQuery : "";
620
- const returnFirst = options.returnFirst;
621
- const { timeout, token, tag, headers } = options;
622
- const uri = this.getDataUrl(endpoint, stringQuery);
623
- const reqOptions = {
624
- method: useGet ? "GET" : "POST",
625
- uri,
626
- json: true,
627
- body: useGet ? void 0 : body,
628
- query: isMutation && getMutationQuery(options),
629
- timeout,
630
- headers,
631
- token,
632
- tag,
633
- canUseCdn: isQuery
553
+ return this._requestObservable(reqOptions).pipe(
554
+ filter(isResponse),
555
+ map(getBody),
556
+ map((res) => {
557
+ if (!isMutation) {
558
+ return res;
559
+ }
560
+ const results = res.results || [];
561
+ if (options.returnDocuments) {
562
+ return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
563
+ }
564
+ const key = returnFirst ? "documentId" : "documentIds";
565
+ const ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
566
+ return {
567
+ transactionId: res.transactionId,
568
+ results,
569
+ [key]: ids
634
570
  };
635
- return this._requestObservable(reqOptions).pipe(
636
- filter2(isResponse),
637
- map2(getBody),
638
- map2((res) => {
639
- if (!isMutation) {
640
- return res;
641
- }
642
- const results = res.results || [];
643
- if (options.returnDocuments) {
644
- return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
645
- }
646
- const key = returnFirst ? "documentId" : "documentIds";
647
- const ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
648
- return {
649
- transactionId: res.transactionId,
650
- results,
651
- [key]: ids
652
- };
653
- })
654
- );
655
- },
656
- _create(doc, op, options = {}) {
657
- const mutation = { [op]: doc };
658
- const opts = Object.assign({ returnFirst: true, returnDocuments: true }, options);
659
- return this.dataRequest("mutate", { mutations: [mutation] }, opts);
660
- }
661
- };
571
+ })
572
+ );
573
+ },
574
+ _create(doc, op, options = {}) {
575
+ const mutation = { [op]: doc };
576
+ const opts = Object.assign({ returnFirst: true, returnDocuments: true }, options);
577
+ return this.dataRequest("mutate", { mutations: [mutation] }, opts);
662
578
  }
663
- });
579
+ };
664
580
 
665
581
  // src/datasets/datasetsClient.js
666
- var require_datasetsClient = __commonJS({
667
- "src/datasets/datasetsClient.js"(exports, module) {
668
- var validate = (init_validators(), __toCommonJS(validators_exports));
669
- function DatasetsClient(client) {
670
- this.request = client.request.bind(client);
671
- }
672
- Object.assign(DatasetsClient.prototype, {
673
- create(name, options) {
674
- return this._modify("PUT", name, options);
675
- },
676
- edit(name, options) {
677
- return this._modify("PATCH", name, options);
678
- },
679
- delete(name) {
680
- return this._modify("DELETE", name);
681
- },
682
- list() {
683
- return this.request({ uri: "/datasets" });
684
- },
685
- _modify(method, name, body) {
686
- validate.dataset(name);
687
- return this.request({ method, uri: `/datasets/${name}`, body });
688
- }
689
- });
690
- module.exports = DatasetsClient;
582
+ function DatasetsClient(client) {
583
+ this.request = client.request.bind(client);
584
+ }
585
+ Object.assign(DatasetsClient.prototype, {
586
+ create(name, options) {
587
+ return this._modify("PUT", name, options);
588
+ },
589
+ edit(name, options) {
590
+ return this._modify("PATCH", name, options);
591
+ },
592
+ delete(name) {
593
+ return this._modify("DELETE", name);
594
+ },
595
+ list() {
596
+ return this.request({ uri: "/datasets" });
597
+ },
598
+ _modify(method, name, body) {
599
+ dataset(name);
600
+ return this.request({ method, uri: `/datasets/${name}`, body });
691
601
  }
692
602
  });
603
+ var datasetsClient_default = DatasetsClient;
693
604
 
694
605
  // src/projects/projectsClient.js
695
- var projectsClient_exports = {};
696
- __export(projectsClient_exports, {
697
- default: () => projectsClient_default
698
- });
699
606
  function ProjectsClient(client) {
700
607
  this.client = client;
701
608
  }
702
- var projectsClient_default;
703
- var init_projectsClient = __esm({
704
- "src/projects/projectsClient.js"() {
705
- Object.assign(ProjectsClient.prototype, {
706
- list() {
707
- return this.client.request({ uri: "/projects" });
708
- },
709
- getById(id) {
710
- return this.client.request({ uri: `/projects/${id}` });
711
- }
712
- });
713
- projectsClient_default = ProjectsClient;
609
+ Object.assign(ProjectsClient.prototype, {
610
+ list() {
611
+ return this.client.request({ uri: "/projects" });
612
+ },
613
+ getById(id) {
614
+ return this.client.request({ uri: `/projects/${id}` });
714
615
  }
715
616
  });
617
+ var projectsClient_default = ProjectsClient;
716
618
 
717
619
  // src/http/queryString.js
718
- var queryString_exports = {};
719
- __export(queryString_exports, {
720
- default: () => queryString_default
721
- });
722
- var queryString_default;
723
- var init_queryString = __esm({
724
- "src/http/queryString.js"() {
725
- queryString_default = (params) => {
726
- const qs = [];
727
- for (const key in params) {
728
- if (params.hasOwnProperty(key)) {
729
- qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
730
- }
731
- }
732
- return qs.length > 0 ? `?${qs.join("&")}` : "";
733
- };
620
+ var queryString_default = (params) => {
621
+ const qs = [];
622
+ for (const key in params) {
623
+ if (params.hasOwnProperty(key)) {
624
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
625
+ }
734
626
  }
735
- });
627
+ return qs.length > 0 ? `?${qs.join("&")}` : "";
628
+ };
736
629
 
737
630
  // src/assets/assetsClient.js
738
- var require_assetsClient = __commonJS({
739
- "src/assets/assetsClient.js"(exports, module) {
740
- var { map: map2, filter: filter2 } = (init_observable_modern(), __toCommonJS(observable_modern_exports));
741
- var queryString = (init_queryString(), __toCommonJS(queryString_exports));
742
- var validators = (init_validators(), __toCommonJS(validators_exports));
743
- function AssetsClient(client) {
744
- this.client = client;
631
+ function AssetsClient(client) {
632
+ this.client = client;
633
+ }
634
+ function optionsFromFile(opts, file) {
635
+ if (typeof window === "undefined" || !(file instanceof window.File)) {
636
+ return opts;
637
+ }
638
+ return Object.assign(
639
+ {
640
+ filename: opts.preserveFilename === false ? void 0 : file.name,
641
+ contentType: file.type
642
+ },
643
+ opts
644
+ );
645
+ }
646
+ Object.assign(AssetsClient.prototype, {
647
+ upload(assetType, body, opts = {}) {
648
+ validateAssetType(assetType);
649
+ let meta = opts.extract || void 0;
650
+ if (meta && !meta.length) {
651
+ meta = ["none"];
745
652
  }
746
- function optionsFromFile(opts, file) {
747
- if (typeof window === "undefined" || !(file instanceof window.File)) {
748
- return opts;
749
- }
750
- return Object.assign(
751
- {
752
- filename: opts.preserveFilename === false ? void 0 : file.name,
753
- contentType: file.type
754
- },
755
- opts
756
- );
653
+ const dataset2 = hasDataset(this.client.clientConfig);
654
+ const assetEndpoint = assetType === "image" ? "images" : "files";
655
+ const options = optionsFromFile(opts, body);
656
+ const { tag, label, title, description, creditLine, filename, source } = options;
657
+ const query = {
658
+ label,
659
+ title,
660
+ description,
661
+ filename,
662
+ meta,
663
+ creditLine
664
+ };
665
+ if (source) {
666
+ query.sourceId = source.id;
667
+ query.sourceName = source.name;
668
+ query.sourceUrl = source.url;
757
669
  }
758
- Object.assign(AssetsClient.prototype, {
759
- upload(assetType, body, opts = {}) {
760
- validators.validateAssetType(assetType);
761
- let meta = opts.extract || void 0;
762
- if (meta && !meta.length) {
763
- meta = ["none"];
764
- }
765
- const dataset2 = validators.hasDataset(this.client.clientConfig);
766
- const assetEndpoint = assetType === "image" ? "images" : "files";
767
- const options = optionsFromFile(opts, body);
768
- const { tag, label, title, description, creditLine, filename, source } = options;
769
- const query = {
770
- label,
771
- title,
772
- description,
773
- filename,
774
- meta,
775
- creditLine
776
- };
777
- if (source) {
778
- query.sourceId = source.id;
779
- query.sourceName = source.name;
780
- query.sourceUrl = source.url;
781
- }
782
- const observable2 = this.client._requestObservable({
783
- tag,
784
- method: "POST",
785
- timeout: options.timeout || 0,
786
- uri: `/assets/${assetEndpoint}/${dataset2}`,
787
- headers: options.contentType ? { "Content-Type": options.contentType } : {},
788
- query,
789
- body
790
- });
791
- return this.client.isPromiseAPI() ? observable2.pipe(
792
- filter2((event) => event.type === "response"),
793
- map2((event) => event.body.document)
794
- ).toPromise() : observable2;
795
- },
796
- delete(type, id) {
797
- console.warn("client.assets.delete() is deprecated, please use client.delete(<document-id>)");
798
- let docId = id || "";
799
- if (!/^(image|file)-/.test(docId)) {
800
- docId = `${type}-${docId}`;
801
- } else if (type._id) {
802
- docId = type._id;
803
- }
804
- validators.hasDataset(this.client.clientConfig);
805
- return this.client.delete(docId);
806
- },
807
- getImageUrl(ref, query) {
808
- const id = ref._ref || ref;
809
- if (typeof id !== "string") {
810
- throw new Error(
811
- "getImageUrl() needs either an object with a _ref, or a string with an asset document ID"
812
- );
813
- }
814
- if (!/^image-[A-Za-z0-9_]+-\d+x\d+-[a-z]{1,5}$/.test(id)) {
815
- throw new Error(
816
- `Unsupported asset ID "${id}". URL generation only works for auto-generated IDs.`
817
- );
818
- }
819
- const [, assetId, size, format] = id.split("-");
820
- validators.hasDataset(this.client.clientConfig);
821
- const { projectId: projectId2, dataset: dataset2 } = this.client.clientConfig;
822
- const qs = query ? queryString(query) : "";
823
- return `https://cdn.sanity.io/images/${projectId2}/${dataset2}/${assetId}-${size}.${format}${qs}`;
824
- }
670
+ const observable2 = this.client._requestObservable({
671
+ tag,
672
+ method: "POST",
673
+ timeout: options.timeout || 0,
674
+ uri: `/assets/${assetEndpoint}/${dataset2}`,
675
+ headers: options.contentType ? { "Content-Type": options.contentType } : {},
676
+ query,
677
+ body
825
678
  });
826
- module.exports = AssetsClient;
679
+ return this.client.isPromiseAPI() ? observable2.pipe(
680
+ filter((event) => event.type === "response"),
681
+ map((event) => event.body.document)
682
+ ).toPromise() : observable2;
683
+ },
684
+ delete(type, id) {
685
+ console.warn("client.assets.delete() is deprecated, please use client.delete(<document-id>)");
686
+ let docId = id || "";
687
+ if (!/^(image|file)-/.test(docId)) {
688
+ docId = `${type}-${docId}`;
689
+ } else if (type._id) {
690
+ docId = type._id;
691
+ }
692
+ hasDataset(this.client.clientConfig);
693
+ return this.client.delete(docId);
694
+ },
695
+ getImageUrl(ref, query) {
696
+ const id = ref._ref || ref;
697
+ if (typeof id !== "string") {
698
+ throw new Error(
699
+ "getImageUrl() needs either an object with a _ref, or a string with an asset document ID"
700
+ );
701
+ }
702
+ if (!/^image-[A-Za-z0-9_]+-\d+x\d+-[a-z]{1,5}$/.test(id)) {
703
+ throw new Error(
704
+ `Unsupported asset ID "${id}". URL generation only works for auto-generated IDs.`
705
+ );
706
+ }
707
+ const [, assetId, size, format] = id.split("-");
708
+ hasDataset(this.client.clientConfig);
709
+ const { projectId: projectId2, dataset: dataset2 } = this.client.clientConfig;
710
+ const qs = query ? queryString_default(query) : "";
711
+ return `https://cdn.sanity.io/images/${projectId2}/${dataset2}/${assetId}-${size}.${format}${qs}`;
827
712
  }
828
713
  });
714
+ var assetsClient_default = AssetsClient;
829
715
 
830
716
  // src/users/usersClient.js
831
- var usersClient_exports = {};
832
- __export(usersClient_exports, {
833
- default: () => usersClient_default
834
- });
835
717
  function UsersClient(client) {
836
718
  this.client = client;
837
719
  }
838
- var usersClient_default;
839
- var init_usersClient = __esm({
840
- "src/users/usersClient.js"() {
841
- Object.assign(UsersClient.prototype, {
842
- getById(id) {
843
- return this.client.request({ uri: `/users/${id}` });
844
- }
845
- });
846
- usersClient_default = UsersClient;
720
+ Object.assign(UsersClient.prototype, {
721
+ getById(id) {
722
+ return this.client.request({ uri: `/users/${id}` });
847
723
  }
848
724
  });
725
+ var usersClient_default = UsersClient;
849
726
 
850
727
  // src/auth/authClient.js
851
- var require_authClient = __commonJS({
852
- "src/auth/authClient.js"(exports, module) {
853
- function AuthClient(client) {
854
- this.client = client;
855
- }
856
- Object.assign(AuthClient.prototype, {
857
- getLoginProviders() {
858
- return this.client.request({ uri: "/auth/providers" });
859
- },
860
- logout() {
861
- return this.client.request({ uri: "/auth/logout", method: "POST" });
862
- }
863
- });
864
- module.exports = AuthClient;
728
+ function AuthClient(client) {
729
+ this.client = client;
730
+ }
731
+ Object.assign(AuthClient.prototype, {
732
+ getLoginProviders() {
733
+ return this.client.request({ uri: "/auth/providers" });
734
+ },
735
+ logout() {
736
+ return this.client.request({ uri: "/auth/logout", method: "POST" });
865
737
  }
866
738
  });
739
+ var authClient_default = AuthClient;
740
+
741
+ // src/http/request.js
742
+ import getIt from "get-it";
743
+ import { observable, jsonRequest, jsonResponse, progress } from "get-it/middleware";
867
744
 
868
745
  // src/http/errors.js
869
746
  import makeError from "make-error";
@@ -905,337 +782,253 @@ function stringifyBody(body, res) {
905
782
  const isJson = contentType.indexOf("application/json") !== -1;
906
783
  return isJson ? JSON.stringify(body, null, 2) : body;
907
784
  }
908
- var init_errors = __esm({
909
- "src/http/errors.js"() {
910
- makeError(ClientError);
911
- makeError(ServerError);
912
- }
913
- });
914
-
915
- // src/http/browserMiddleware.js
916
- var browserMiddleware_exports = {};
917
- __export(browserMiddleware_exports, {
918
- default: () => browserMiddleware_default
919
- });
920
- var browserMiddleware_default;
921
- var init_browserMiddleware = __esm({
922
- "src/http/browserMiddleware.js"() {
923
- browserMiddleware_default = [];
924
- }
925
- });
785
+ makeError(ClientError);
786
+ makeError(ServerError);
926
787
 
927
788
  // src/http/request.js
928
- var request_exports = {};
929
- __export(request_exports, {
930
- default: () => request_default
931
- });
932
- import getIt from "get-it";
933
- import { observable, jsonRequest, jsonResponse, progress } from "get-it/middleware";
789
+ var httpError = {
790
+ onResponse: (res) => {
791
+ if (res.statusCode >= 500) {
792
+ throw new ServerError(res);
793
+ } else if (res.statusCode >= 400) {
794
+ throw new ClientError(res);
795
+ }
796
+ return res;
797
+ }
798
+ };
799
+ var printWarnings = {
800
+ onResponse: (res) => {
801
+ const warn = res.headers["x-sanity-warning"];
802
+ const warnings = Array.isArray(warn) ? warn : [warn];
803
+ warnings.filter(Boolean).forEach((msg) => console.warn(msg));
804
+ return res;
805
+ }
806
+ };
807
+ var envSpecific = false ? null : (init_browserMiddleware(), __toCommonJS(browserMiddleware_exports));
808
+ var middleware = envSpecific.concat([
809
+ printWarnings,
810
+ jsonRequest(),
811
+ jsonResponse(),
812
+ progress(),
813
+ httpError,
814
+ observable({ implementation: Observable })
815
+ ]);
816
+ var request = getIt(middleware);
934
817
  function httpRequest(options, requester = request) {
935
818
  return requester(Object.assign({ maxRedirects: 0 }, options));
936
819
  }
937
- var httpError, printWarnings, envSpecific, middleware, request, request_default;
938
- var init_request = __esm({
939
- "src/http/request.js"() {
940
- init_observable_modern();
941
- init_errors();
942
- httpError = {
943
- onResponse: (res) => {
944
- if (res.statusCode >= 500) {
945
- throw new ServerError(res);
946
- } else if (res.statusCode >= 400) {
947
- throw new ClientError(res);
948
- }
949
- return res;
950
- }
951
- };
952
- printWarnings = {
953
- onResponse: (res) => {
954
- const warn = res.headers["x-sanity-warning"];
955
- const warnings = Array.isArray(warn) ? warn : [warn];
956
- warnings.filter(Boolean).forEach((msg) => console.warn(msg));
957
- return res;
958
- }
959
- };
960
- envSpecific = typeof EdgeRuntime === "string" ? (init_browserMiddleware(), __toCommonJS(browserMiddleware_exports)) : (init_browserMiddleware(), __toCommonJS(browserMiddleware_exports));
961
- middleware = envSpecific.concat([
962
- printWarnings,
963
- jsonRequest(),
964
- jsonResponse(),
965
- progress(),
966
- httpError,
967
- observable({ implementation: Observable })
968
- ]);
969
- request = getIt(middleware);
970
- httpRequest.defaultRequester = request;
971
- httpRequest.ClientError = ClientError;
972
- httpRequest.ServerError = ServerError;
973
- request_default = httpRequest;
974
- }
975
- });
820
+ httpRequest.defaultRequester = request;
821
+ httpRequest.ClientError = ClientError;
822
+ httpRequest.ServerError = ServerError;
823
+ var request_default = httpRequest;
976
824
 
977
825
  // src/http/requestOptions.js
978
- var requestOptions_exports = {};
979
- __export(requestOptions_exports, {
980
- default: () => requestOptions_default
981
- });
982
- var projectHeader, requestOptions_default;
983
- var init_requestOptions = __esm({
984
- "src/http/requestOptions.js"() {
985
- projectHeader = "X-Sanity-Project-ID";
986
- requestOptions_default = (config, overrides = {}) => {
987
- const headers = {};
988
- const token = overrides.token || config.token;
989
- if (token) {
990
- headers.Authorization = `Bearer ${token}`;
991
- }
992
- if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
993
- headers[projectHeader] = config.projectId;
994
- }
995
- const withCredentials = Boolean(
996
- typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials
997
- );
998
- const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
999
- return Object.assign({}, overrides, {
1000
- headers: Object.assign({}, headers, overrides.headers || {}),
1001
- timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
1002
- proxy: overrides.proxy || config.proxy,
1003
- json: true,
1004
- withCredentials
1005
- });
1006
- };
826
+ var projectHeader = "X-Sanity-Project-ID";
827
+ var requestOptions_default = (config, overrides = {}) => {
828
+ const headers = {};
829
+ const token = overrides.token || config.token;
830
+ if (token) {
831
+ headers.Authorization = `Bearer ${token}`;
1007
832
  }
1008
- });
833
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
834
+ headers[projectHeader] = config.projectId;
835
+ }
836
+ const withCredentials = Boolean(
837
+ typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials
838
+ );
839
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
840
+ return Object.assign({}, overrides, {
841
+ headers: Object.assign({}, headers, overrides.headers || {}),
842
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
843
+ proxy: overrides.proxy || config.proxy,
844
+ json: true,
845
+ withCredentials
846
+ });
847
+ };
1009
848
 
1010
849
  // src/generateHelpUrl.js
850
+ var BASE_URL = "https://docs.sanity.io/help/";
1011
851
  function generateHelpUrl(slug) {
1012
852
  return BASE_URL + slug;
1013
853
  }
1014
- var BASE_URL;
1015
- var init_generateHelpUrl = __esm({
1016
- "src/generateHelpUrl.js"() {
1017
- BASE_URL = "https://docs.sanity.io/help/";
1018
- }
1019
- });
1020
854
 
1021
855
  // src/util/once.js
1022
- var once_default;
1023
- var init_once = __esm({
1024
- "src/util/once.js"() {
1025
- once_default = (fn) => {
1026
- let didCall = false;
1027
- let returnValue;
1028
- return (...args) => {
1029
- if (didCall) {
1030
- return returnValue;
1031
- }
1032
- returnValue = fn(...args);
1033
- didCall = true;
1034
- return returnValue;
1035
- };
1036
- };
1037
- }
1038
- });
856
+ var once_default = (fn) => {
857
+ let didCall = false;
858
+ let returnValue;
859
+ return (...args) => {
860
+ if (didCall) {
861
+ return returnValue;
862
+ }
863
+ returnValue = fn(...args);
864
+ didCall = true;
865
+ return returnValue;
866
+ };
867
+ };
1039
868
 
1040
869
  // src/warnings.js
1041
- var createWarningPrinter, printCdnWarning, printBrowserTokenWarning, printNoApiVersionSpecifiedWarning;
1042
- var init_warnings = __esm({
1043
- "src/warnings.js"() {
1044
- init_generateHelpUrl();
1045
- init_once();
1046
- createWarningPrinter = (message) => once_default((...args) => console.warn(message.join(" "), ...args));
1047
- printCdnWarning = createWarningPrinter([
1048
- "You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and",
1049
- `cheaper. Think about it! For more info, see ${generateHelpUrl("js-client-cdn-configuration")}.`,
1050
- "To hide this warning, please set the `useCdn` option to either `true` or `false` when creating",
1051
- "the client."
1052
- ]);
1053
- printBrowserTokenWarning = createWarningPrinter([
1054
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
1055
- `See ${generateHelpUrl(
1056
- "js-client-browser-token"
1057
- )} for more information and how to hide this warning.`
1058
- ]);
1059
- printNoApiVersionSpecifiedWarning = createWarningPrinter([
1060
- "Using the Sanity client without specifying an API version is deprecated.",
1061
- `See ${generateHelpUrl("js-client-api-version")}`
1062
- ]);
1063
- }
1064
- });
870
+ var createWarningPrinter = (message) => once_default((...args) => console.warn(message.join(" "), ...args));
871
+ var printCdnWarning = createWarningPrinter([
872
+ "You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and",
873
+ `cheaper. Think about it! For more info, see ${generateHelpUrl("js-client-cdn-configuration")}.`,
874
+ "To hide this warning, please set the `useCdn` option to either `true` or `false` when creating",
875
+ "the client."
876
+ ]);
877
+ var printBrowserTokenWarning = createWarningPrinter([
878
+ "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
879
+ `See ${generateHelpUrl(
880
+ "js-client-browser-token"
881
+ )} for more information and how to hide this warning.`
882
+ ]);
883
+ var printNoApiVersionSpecifiedWarning = createWarningPrinter([
884
+ "Using the Sanity client without specifying an API version is deprecated.",
885
+ `See ${generateHelpUrl("js-client-api-version")}`
886
+ ]);
1065
887
 
1066
888
  // src/config.js
1067
- var config_exports = {};
1068
- __export(config_exports, {
1069
- defaultConfig: () => defaultConfig,
1070
- initConfig: () => initConfig,
1071
- validateApiVersion: () => validateApiVersion
1072
- });
1073
- var defaultCdnHost, defaultConfig, LOCALHOSTS, isLocal, validateApiVersion, initConfig;
1074
- var init_config = __esm({
1075
- "src/config.js"() {
1076
- init_generateHelpUrl();
1077
- init_validators();
1078
- init_warnings();
1079
- defaultCdnHost = "apicdn.sanity.io";
1080
- defaultConfig = {
1081
- apiHost: "https://api.sanity.io",
1082
- apiVersion: "1",
1083
- useProjectHostname: true,
1084
- isPromiseAPI: true
1085
- };
1086
- LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
1087
- isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
1088
- validateApiVersion = function validateApiVersion2(apiVersion) {
1089
- if (apiVersion === "1" || apiVersion === "X") {
1090
- return;
1091
- }
1092
- const apiDate = new Date(apiVersion);
1093
- const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
1094
- if (!apiVersionValid) {
1095
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
1096
- }
1097
- };
1098
- initConfig = (config, prevConfig) => {
1099
- const specifiedConfig = Object.assign({}, prevConfig, config);
1100
- if (!specifiedConfig.apiVersion) {
1101
- printNoApiVersionSpecifiedWarning();
1102
- }
1103
- const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
1104
- const projectBased = newConfig.useProjectHostname;
1105
- if (typeof Promise === "undefined") {
1106
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
1107
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
1108
- }
1109
- if (projectBased && !newConfig.projectId) {
1110
- throw new Error("Configuration must contain `projectId`");
1111
- }
1112
- const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
1113
- const isLocalhost = isBrowser && isLocal(window.location.hostname);
1114
- if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
1115
- printBrowserTokenWarning();
1116
- } else if (typeof newConfig.useCdn === "undefined") {
1117
- printCdnWarning();
1118
- }
1119
- if (projectBased) {
1120
- projectId(newConfig.projectId);
1121
- }
1122
- if (newConfig.dataset) {
1123
- dataset(newConfig.dataset);
1124
- }
1125
- if ("requestTagPrefix" in newConfig) {
1126
- newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
1127
- }
1128
- newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, "");
1129
- newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
1130
- newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
1131
- validateApiVersion(newConfig.apiVersion);
1132
- const hostParts = newConfig.apiHost.split("://", 2);
1133
- const protocol = hostParts[0];
1134
- const host = hostParts[1];
1135
- const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
1136
- if (newConfig.useProjectHostname) {
1137
- newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`;
1138
- newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`;
1139
- } else {
1140
- newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`;
1141
- newConfig.cdnUrl = newConfig.url;
1142
- }
1143
- return newConfig;
1144
- };
889
+ var defaultCdnHost = "apicdn.sanity.io";
890
+ var defaultConfig = {
891
+ apiHost: "https://api.sanity.io",
892
+ apiVersion: "1",
893
+ useProjectHostname: true,
894
+ isPromiseAPI: true
895
+ };
896
+ var LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
897
+ var isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
898
+ var validateApiVersion = function validateApiVersion2(apiVersion) {
899
+ if (apiVersion === "1" || apiVersion === "X") {
900
+ return;
1145
901
  }
1146
- });
902
+ const apiDate = new Date(apiVersion);
903
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
904
+ if (!apiVersionValid) {
905
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
906
+ }
907
+ };
908
+ var initConfig = (config, prevConfig) => {
909
+ const specifiedConfig = Object.assign({}, prevConfig, config);
910
+ if (!specifiedConfig.apiVersion) {
911
+ printNoApiVersionSpecifiedWarning();
912
+ }
913
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
914
+ const projectBased = newConfig.useProjectHostname;
915
+ if (typeof Promise === "undefined") {
916
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
917
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
918
+ }
919
+ if (projectBased && !newConfig.projectId) {
920
+ throw new Error("Configuration must contain `projectId`");
921
+ }
922
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
923
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
924
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
925
+ printBrowserTokenWarning();
926
+ } else if (typeof newConfig.useCdn === "undefined") {
927
+ printCdnWarning();
928
+ }
929
+ if (projectBased) {
930
+ projectId(newConfig.projectId);
931
+ }
932
+ if (newConfig.dataset) {
933
+ dataset(newConfig.dataset);
934
+ }
935
+ if ("requestTagPrefix" in newConfig) {
936
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
937
+ }
938
+ newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, "");
939
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
940
+ newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
941
+ validateApiVersion(newConfig.apiVersion);
942
+ const hostParts = newConfig.apiHost.split("://", 2);
943
+ const protocol = hostParts[0];
944
+ const host = hostParts[1];
945
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
946
+ if (newConfig.useProjectHostname) {
947
+ newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`;
948
+ newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`;
949
+ } else {
950
+ newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`;
951
+ newConfig.cdnUrl = newConfig.url;
952
+ }
953
+ return newConfig;
954
+ };
1147
955
 
1148
956
  // src/sanityClient.js
1149
- var require_sanityClient = __commonJS({
1150
- "src/sanityClient.js"(exports, module) {
1151
- var { Observable: Observable2, map: map2, filter: filter2 } = (init_observable_modern(), __toCommonJS(observable_modern_exports));
1152
- var Patch = require_patch();
1153
- var Transaction = require_transaction();
1154
- var dataMethods = require_dataMethods();
1155
- var DatasetsClient = require_datasetsClient();
1156
- var ProjectsClient2 = (init_projectsClient(), __toCommonJS(projectsClient_exports));
1157
- var AssetsClient = require_assetsClient();
1158
- var UsersClient2 = (init_usersClient(), __toCommonJS(usersClient_exports));
1159
- var AuthClient = require_authClient();
1160
- var httpRequest2 = (init_request(), __toCommonJS(request_exports));
1161
- var getRequestOptions = (init_requestOptions(), __toCommonJS(requestOptions_exports));
1162
- var { defaultConfig: defaultConfig2, initConfig: initConfig2 } = (init_config(), __toCommonJS(config_exports));
1163
- var validate = (init_validators(), __toCommonJS(validators_exports));
1164
- var toPromise = (observable2) => observable2.toPromise();
1165
- function SanityClient(config = defaultConfig2) {
1166
- if (!(this instanceof SanityClient)) {
1167
- return new SanityClient(config);
1168
- }
1169
- this.config(config);
1170
- this.assets = new AssetsClient(this);
1171
- this.datasets = new DatasetsClient(this);
1172
- this.projects = new ProjectsClient2(this);
1173
- this.users = new UsersClient2(this);
1174
- this.auth = new AuthClient(this);
1175
- if (this.clientConfig.isPromiseAPI) {
1176
- const observableConfig = Object.assign({}, this.clientConfig, { isPromiseAPI: false });
1177
- this.observable = new SanityClient(observableConfig);
1178
- }
957
+ var toPromise2 = (observable2) => observable2.toPromise();
958
+ function SanityClient(config = defaultConfig) {
959
+ if (!(this instanceof SanityClient)) {
960
+ return new SanityClient(config);
961
+ }
962
+ this.config(config);
963
+ this.assets = new assetsClient_default(this);
964
+ this.datasets = new datasetsClient_default(this);
965
+ this.projects = new projectsClient_default(this);
966
+ this.users = new usersClient_default(this);
967
+ this.auth = new authClient_default(this);
968
+ if (this.clientConfig.isPromiseAPI) {
969
+ const observableConfig = Object.assign({}, this.clientConfig, { isPromiseAPI: false });
970
+ this.observable = new SanityClient(observableConfig);
971
+ }
972
+ }
973
+ Object.assign(SanityClient.prototype, dataMethods_default);
974
+ Object.assign(SanityClient.prototype, {
975
+ clone() {
976
+ return new SanityClient(this.config());
977
+ },
978
+ config(newConfig) {
979
+ if (typeof newConfig === "undefined") {
980
+ return Object.assign({}, this.clientConfig);
1179
981
  }
1180
- Object.assign(SanityClient.prototype, dataMethods);
1181
- Object.assign(SanityClient.prototype, {
1182
- clone() {
1183
- return new SanityClient(this.config());
1184
- },
1185
- config(newConfig) {
1186
- if (typeof newConfig === "undefined") {
1187
- return Object.assign({}, this.clientConfig);
1188
- }
1189
- if (this.observable) {
1190
- const observableConfig = Object.assign({}, newConfig, { isPromiseAPI: false });
1191
- this.observable.config(observableConfig);
1192
- }
1193
- this.clientConfig = initConfig2(newConfig, this.clientConfig || {});
1194
- return this;
1195
- },
1196
- withConfig(newConfig) {
1197
- return this.clone().config(newConfig);
1198
- },
1199
- getUrl(uri, useCdn = false) {
1200
- const base = useCdn ? this.clientConfig.cdnUrl : this.clientConfig.url;
1201
- return `${base}/${uri.replace(/^\//, "")}`;
1202
- },
1203
- isPromiseAPI() {
1204
- return this.clientConfig.isPromiseAPI;
1205
- },
1206
- _requestObservable(options) {
1207
- const uri = options.url || options.uri;
1208
- const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
1209
- const useCdn = this.clientConfig.useCdn && canUseCdn;
1210
- const tag = options.tag && this.clientConfig.requestTagPrefix ? [this.clientConfig.requestTagPrefix, options.tag].join(".") : options.tag || this.clientConfig.requestTagPrefix;
1211
- if (tag) {
1212
- options.query = { tag: validate.requestTag(tag), ...options.query };
1213
- }
1214
- const reqOptions = getRequestOptions(
1215
- this.clientConfig,
1216
- Object.assign({}, options, {
1217
- url: this.getUrl(uri, useCdn)
1218
- })
1219
- );
1220
- return new Observable2(
1221
- (subscriber) => httpRequest2(reqOptions, this.clientConfig.requester).subscribe(subscriber)
1222
- );
1223
- },
1224
- request(options) {
1225
- const observable2 = this._requestObservable(options).pipe(
1226
- filter2((event) => event.type === "response"),
1227
- map2((event) => event.body)
1228
- );
1229
- return this.isPromiseAPI() ? toPromise(observable2) : observable2;
1230
- }
1231
- });
1232
- SanityClient.Patch = Patch;
1233
- SanityClient.Transaction = Transaction;
1234
- SanityClient.ClientError = httpRequest2.ClientError;
1235
- SanityClient.ServerError = httpRequest2.ServerError;
1236
- SanityClient.requester = httpRequest2.defaultRequester;
1237
- module.exports = SanityClient;
982
+ if (this.observable) {
983
+ const observableConfig = Object.assign({}, newConfig, { isPromiseAPI: false });
984
+ this.observable.config(observableConfig);
985
+ }
986
+ this.clientConfig = initConfig(newConfig, this.clientConfig || {});
987
+ return this;
988
+ },
989
+ withConfig(newConfig) {
990
+ return this.clone().config(newConfig);
991
+ },
992
+ getUrl(uri, useCdn = false) {
993
+ const base = useCdn ? this.clientConfig.cdnUrl : this.clientConfig.url;
994
+ return `${base}/${uri.replace(/^\//, "")}`;
995
+ },
996
+ isPromiseAPI() {
997
+ return this.clientConfig.isPromiseAPI;
998
+ },
999
+ _requestObservable(options) {
1000
+ const uri = options.url || options.uri;
1001
+ const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
1002
+ const useCdn = this.clientConfig.useCdn && canUseCdn;
1003
+ const tag = options.tag && this.clientConfig.requestTagPrefix ? [this.clientConfig.requestTagPrefix, options.tag].join(".") : options.tag || this.clientConfig.requestTagPrefix;
1004
+ if (tag) {
1005
+ options.query = { tag: requestTag(tag), ...options.query };
1006
+ }
1007
+ const reqOptions = requestOptions_default(
1008
+ this.clientConfig,
1009
+ Object.assign({}, options, {
1010
+ url: this.getUrl(uri, useCdn)
1011
+ })
1012
+ );
1013
+ return new Observable(
1014
+ (subscriber) => request_default(reqOptions, this.clientConfig.requester).subscribe(subscriber)
1015
+ );
1016
+ },
1017
+ request(options) {
1018
+ const observable2 = this._requestObservable(options).pipe(
1019
+ filter((event) => event.type === "response"),
1020
+ map((event) => event.body)
1021
+ );
1022
+ return this.isPromiseAPI() ? toPromise2(observable2) : observable2;
1238
1023
  }
1239
1024
  });
1240
- export default require_sanityClient();
1025
+ SanityClient.Patch = patch_default;
1026
+ SanityClient.Transaction = transaction_default;
1027
+ SanityClient.ClientError = request_default.ClientError;
1028
+ SanityClient.ServerError = request_default.ServerError;
1029
+ SanityClient.requester = request_default.defaultRequester;
1030
+ var sanityClient_default = SanityClient;
1031
+ export {
1032
+ sanityClient_default as default
1033
+ };
1241
1034
  //# sourceMappingURL=sanityClient.browser.mjs.map