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