@sanity/client 3.3.0 → 4.0.0-alpha.esm.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +10 -10
  2. package/dist/browser/sanityClient.js +2243 -0
  3. package/dist/node/sanityClient.js +7075 -0
  4. package/lib/assets/assetsClient.js +132 -106
  5. package/lib/auth/authClient.js +38 -19
  6. package/lib/config.js +25 -13
  7. package/lib/data/dataMethods.js +32 -24
  8. package/lib/data/encodeQueryString.js +8 -2
  9. package/lib/data/listen.js +25 -21
  10. package/lib/data/patch.js +169 -118
  11. package/lib/data/transaction.js +134 -88
  12. package/lib/datasets/datasetsClient.js +63 -32
  13. package/lib/http/browserMiddleware.js +6 -1
  14. package/lib/http/errors.js +12 -8
  15. package/lib/http/nodeMiddleware.js +16 -9
  16. package/lib/http/queryString.js +9 -2
  17. package/lib/http/request.js +27 -24
  18. package/lib/http/requestOptions.js +10 -6
  19. package/lib/projects/projectsClient.js +37 -18
  20. package/lib/sanityClient.js +143 -105
  21. package/lib/users/usersClient.js +28 -11
  22. package/lib/util/defaults.js +12 -4
  23. package/lib/util/getSelection.js +7 -2
  24. package/lib/util/observable.js +24 -13
  25. package/lib/util/once.js +9 -2
  26. package/lib/util/pick.js +9 -2
  27. package/lib/validators.js +38 -15
  28. package/lib/warnings.js +14 -6
  29. package/package.json +22 -3
  30. package/sanityClient.d.ts +1 -13
  31. package/src/assets/assetsClient.js +132 -0
  32. package/src/auth/authClient.js +13 -0
  33. package/src/config.js +93 -0
  34. package/src/data/dataMethods.js +182 -0
  35. package/src/data/encodeQueryString.js +18 -0
  36. package/src/data/listen.js +159 -0
  37. package/src/data/patch.js +119 -0
  38. package/src/data/transaction.js +103 -0
  39. package/src/datasets/datasetsClient.js +28 -0
  40. package/src/http/browserMiddleware.js +1 -0
  41. package/src/http/errors.js +53 -0
  42. package/src/http/nodeMiddleware.js +11 -0
  43. package/src/http/queryString.js +10 -0
  44. package/src/http/request.js +50 -0
  45. package/src/http/requestOptions.js +29 -0
  46. package/src/projects/projectsClient.js +13 -0
  47. package/src/sanityClient.js +124 -0
  48. package/src/users/usersClient.js +9 -0
  49. package/src/util/defaults.js +9 -0
  50. package/src/util/getSelection.js +17 -0
  51. package/src/util/observable.js +6 -0
  52. package/src/util/once.js +12 -0
  53. package/src/util/pick.js +9 -0
  54. package/src/validators.js +76 -0
  55. package/src/warnings.js +25 -0
  56. package/test/client.test.js +37 -37
  57. package/test/encodeQueryString.test.js +3 -1
  58. package/test/helpers/sseServer.js +2 -1
  59. package/test/listen.test.js +4 -2
  60. package/test/warnings.test.disabled.js +8 -4
  61. package/umd/sanityClient.js +38 -38
  62. package/umd/sanityClient.min.js +1 -1
@@ -0,0 +1,2243 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
19
+
20
+ // node_modules/nano-pubsub/index.js
21
+ var require_nano_pubsub = __commonJS({
22
+ "node_modules/nano-pubsub/index.js"(exports, module) {
23
+ module.exports = function Pubsub() {
24
+ var subscribers = [];
25
+ return {
26
+ subscribe,
27
+ publish
28
+ };
29
+ function subscribe(subscriber) {
30
+ subscribers.push(subscriber);
31
+ return function unsubscribe() {
32
+ var idx = subscribers.indexOf(subscriber);
33
+ if (idx > -1) {
34
+ subscribers.splice(idx, 1);
35
+ }
36
+ };
37
+ }
38
+ function publish() {
39
+ for (var i = 0; i < subscribers.length; i++) {
40
+ subscribers[i].apply(null, arguments);
41
+ }
42
+ }
43
+ };
44
+ }
45
+ });
46
+
47
+ // node_modules/get-it/lib/util/middlewareReducer.js
48
+ var require_middlewareReducer = __commonJS({
49
+ "node_modules/get-it/lib/util/middlewareReducer.js"(exports, module) {
50
+ "use strict";
51
+ module.exports = function(middleware3) {
52
+ var applyMiddleware = function applyMiddleware2(hook, defaultValue) {
53
+ var bailEarly = hook === "onError";
54
+ var value = defaultValue;
55
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
56
+ args[_key - 2] = arguments[_key];
57
+ }
58
+ for (var i = 0; i < middleware3[hook].length; i++) {
59
+ var handler = middleware3[hook][i];
60
+ value = handler.apply(void 0, [value].concat(args));
61
+ if (bailEarly && !value) {
62
+ break;
63
+ }
64
+ }
65
+ return value;
66
+ };
67
+ return applyMiddleware;
68
+ };
69
+ }
70
+ });
71
+
72
+ // node_modules/object-assign/index.js
73
+ var require_object_assign = __commonJS({
74
+ "node_modules/object-assign/index.js"(exports, module) {
75
+ "use strict";
76
+ var getOwnPropertySymbols = Object.getOwnPropertySymbols;
77
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
78
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
79
+ function toObject(val) {
80
+ if (val === null || val === void 0) {
81
+ throw new TypeError("Object.assign cannot be called with null or undefined");
82
+ }
83
+ return Object(val);
84
+ }
85
+ function shouldUseNative() {
86
+ try {
87
+ if (!Object.assign) {
88
+ return false;
89
+ }
90
+ var test1 = new String("abc");
91
+ test1[5] = "de";
92
+ if (Object.getOwnPropertyNames(test1)[0] === "5") {
93
+ return false;
94
+ }
95
+ var test2 = {};
96
+ for (var i = 0; i < 10; i++) {
97
+ test2["_" + String.fromCharCode(i)] = i;
98
+ }
99
+ var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
100
+ return test2[n];
101
+ });
102
+ if (order2.join("") !== "0123456789") {
103
+ return false;
104
+ }
105
+ var test3 = {};
106
+ "abcdefghijklmnopqrst".split("").forEach(function(letter) {
107
+ test3[letter] = letter;
108
+ });
109
+ if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
110
+ return false;
111
+ }
112
+ return true;
113
+ } catch (err) {
114
+ return false;
115
+ }
116
+ }
117
+ module.exports = shouldUseNative() ? Object.assign : function(target, source) {
118
+ var from;
119
+ var to = toObject(target);
120
+ var symbols;
121
+ for (var s = 1; s < arguments.length; s++) {
122
+ from = Object(arguments[s]);
123
+ for (var key in from) {
124
+ if (hasOwnProperty.call(from, key)) {
125
+ to[key] = from[key];
126
+ }
127
+ }
128
+ if (getOwnPropertySymbols) {
129
+ symbols = getOwnPropertySymbols(from);
130
+ for (var i = 0; i < symbols.length; i++) {
131
+ if (propIsEnumerable.call(from, symbols[i])) {
132
+ to[symbols[i]] = from[symbols[i]];
133
+ }
134
+ }
135
+ }
136
+ }
137
+ return to;
138
+ };
139
+ }
140
+ });
141
+
142
+ // node_modules/requires-port/index.js
143
+ var require_requires_port = __commonJS({
144
+ "node_modules/requires-port/index.js"(exports, module) {
145
+ "use strict";
146
+ module.exports = function required(port, protocol) {
147
+ protocol = protocol.split(":")[0];
148
+ port = +port;
149
+ if (!port)
150
+ return false;
151
+ switch (protocol) {
152
+ case "http":
153
+ case "ws":
154
+ return port !== 80;
155
+ case "https":
156
+ case "wss":
157
+ return port !== 443;
158
+ case "ftp":
159
+ return port !== 21;
160
+ case "gopher":
161
+ return port !== 70;
162
+ case "file":
163
+ return false;
164
+ }
165
+ return port !== 0;
166
+ };
167
+ }
168
+ });
169
+
170
+ // node_modules/querystringify/index.js
171
+ var require_querystringify = __commonJS({
172
+ "node_modules/querystringify/index.js"(exports) {
173
+ "use strict";
174
+ var has = Object.prototype.hasOwnProperty;
175
+ var undef;
176
+ function decode(input) {
177
+ try {
178
+ return decodeURIComponent(input.replace(/\+/g, " "));
179
+ } catch (e) {
180
+ return null;
181
+ }
182
+ }
183
+ function encode(input) {
184
+ try {
185
+ return encodeURIComponent(input);
186
+ } catch (e) {
187
+ return null;
188
+ }
189
+ }
190
+ function querystring(query) {
191
+ var parser = /([^=?#&]+)=?([^&]*)/g, result = {}, part;
192
+ while (part = parser.exec(query)) {
193
+ var key = decode(part[1]), value = decode(part[2]);
194
+ if (key === null || value === null || key in result)
195
+ continue;
196
+ result[key] = value;
197
+ }
198
+ return result;
199
+ }
200
+ function querystringify(obj, prefix) {
201
+ prefix = prefix || "";
202
+ var pairs = [], value, key;
203
+ if (typeof prefix !== "string")
204
+ prefix = "?";
205
+ for (key in obj) {
206
+ if (has.call(obj, key)) {
207
+ value = obj[key];
208
+ if (!value && (value === null || value === undef || isNaN(value))) {
209
+ value = "";
210
+ }
211
+ key = encode(key);
212
+ value = encode(value);
213
+ if (key === null || value === null)
214
+ continue;
215
+ pairs.push(key + "=" + value);
216
+ }
217
+ }
218
+ return pairs.length ? prefix + pairs.join("&") : "";
219
+ }
220
+ exports.stringify = querystringify;
221
+ exports.parse = querystring;
222
+ }
223
+ });
224
+
225
+ // node_modules/url-parse/index.js
226
+ var require_url_parse = __commonJS({
227
+ "node_modules/url-parse/index.js"(exports, module) {
228
+ "use strict";
229
+ var required = require_requires_port();
230
+ var qs = require_querystringify();
231
+ var controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
232
+ var CRHTLF = /[\n\r\t]/g;
233
+ var slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
234
+ var port = /:\d+$/;
235
+ var protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i;
236
+ var windowsDriveLetter = /^[a-zA-Z]:/;
237
+ function trimLeft(str) {
238
+ return (str ? str : "").toString().replace(controlOrWhitespace, "");
239
+ }
240
+ var rules = [
241
+ ["#", "hash"],
242
+ ["?", "query"],
243
+ function sanitize(address, url) {
244
+ return isSpecial(url.protocol) ? address.replace(/\\/g, "/") : address;
245
+ },
246
+ ["/", "pathname"],
247
+ ["@", "auth", 1],
248
+ [NaN, "host", void 0, 1, 1],
249
+ [/:(\d*)$/, "port", void 0, 1],
250
+ [NaN, "hostname", void 0, 1, 1]
251
+ ];
252
+ var ignore = { hash: 1, query: 1 };
253
+ function lolcation(loc) {
254
+ var globalVar;
255
+ if (typeof window !== "undefined")
256
+ globalVar = window;
257
+ else if (typeof global !== "undefined")
258
+ globalVar = global;
259
+ else if (typeof self !== "undefined")
260
+ globalVar = self;
261
+ else
262
+ globalVar = {};
263
+ var location = globalVar.location || {};
264
+ loc = loc || location;
265
+ var finaldestination = {}, type = typeof loc, key;
266
+ if (loc.protocol === "blob:") {
267
+ finaldestination = new Url(unescape(loc.pathname), {});
268
+ } else if (type === "string") {
269
+ finaldestination = new Url(loc, {});
270
+ for (key in ignore)
271
+ delete finaldestination[key];
272
+ } else if (type === "object") {
273
+ for (key in loc) {
274
+ if (key in ignore)
275
+ continue;
276
+ finaldestination[key] = loc[key];
277
+ }
278
+ if (finaldestination.slashes === void 0) {
279
+ finaldestination.slashes = slashes.test(loc.href);
280
+ }
281
+ }
282
+ return finaldestination;
283
+ }
284
+ function isSpecial(scheme) {
285
+ return scheme === "file:" || scheme === "ftp:" || scheme === "http:" || scheme === "https:" || scheme === "ws:" || scheme === "wss:";
286
+ }
287
+ function extractProtocol(address, location) {
288
+ address = trimLeft(address);
289
+ address = address.replace(CRHTLF, "");
290
+ location = location || {};
291
+ var match = protocolre.exec(address);
292
+ var protocol = match[1] ? match[1].toLowerCase() : "";
293
+ var forwardSlashes = !!match[2];
294
+ var otherSlashes = !!match[3];
295
+ var slashesCount = 0;
296
+ var rest;
297
+ if (forwardSlashes) {
298
+ if (otherSlashes) {
299
+ rest = match[2] + match[3] + match[4];
300
+ slashesCount = match[2].length + match[3].length;
301
+ } else {
302
+ rest = match[2] + match[4];
303
+ slashesCount = match[2].length;
304
+ }
305
+ } else {
306
+ if (otherSlashes) {
307
+ rest = match[3] + match[4];
308
+ slashesCount = match[3].length;
309
+ } else {
310
+ rest = match[4];
311
+ }
312
+ }
313
+ if (protocol === "file:") {
314
+ if (slashesCount >= 2) {
315
+ rest = rest.slice(2);
316
+ }
317
+ } else if (isSpecial(protocol)) {
318
+ rest = match[4];
319
+ } else if (protocol) {
320
+ if (forwardSlashes) {
321
+ rest = rest.slice(2);
322
+ }
323
+ } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
324
+ rest = match[4];
325
+ }
326
+ return {
327
+ protocol,
328
+ slashes: forwardSlashes || isSpecial(protocol),
329
+ slashesCount,
330
+ rest
331
+ };
332
+ }
333
+ function resolve(relative, base) {
334
+ if (relative === "")
335
+ return base;
336
+ var path = (base || "/").split("/").slice(0, -1).concat(relative.split("/")), i = path.length, last = path[i - 1], unshift = false, up = 0;
337
+ while (i--) {
338
+ if (path[i] === ".") {
339
+ path.splice(i, 1);
340
+ } else if (path[i] === "..") {
341
+ path.splice(i, 1);
342
+ up++;
343
+ } else if (up) {
344
+ if (i === 0)
345
+ unshift = true;
346
+ path.splice(i, 1);
347
+ up--;
348
+ }
349
+ }
350
+ if (unshift)
351
+ path.unshift("");
352
+ if (last === "." || last === "..")
353
+ path.push("");
354
+ return path.join("/");
355
+ }
356
+ function Url(address, location, parser) {
357
+ address = trimLeft(address);
358
+ address = address.replace(CRHTLF, "");
359
+ if (!(this instanceof Url)) {
360
+ return new Url(address, location, parser);
361
+ }
362
+ var relative, extracted, parse, instruction, index, key, instructions = rules.slice(), type = typeof location, url = this, i = 0;
363
+ if (type !== "object" && type !== "string") {
364
+ parser = location;
365
+ location = null;
366
+ }
367
+ if (parser && typeof parser !== "function")
368
+ parser = qs.parse;
369
+ location = lolcation(location);
370
+ extracted = extractProtocol(address || "", location);
371
+ relative = !extracted.protocol && !extracted.slashes;
372
+ url.slashes = extracted.slashes || relative && location.slashes;
373
+ url.protocol = extracted.protocol || location.protocol || "";
374
+ address = extracted.rest;
375
+ if (extracted.protocol === "file:" && (extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || !extracted.slashes && (extracted.protocol || extracted.slashesCount < 2 || !isSpecial(url.protocol))) {
376
+ instructions[3] = [/(.*)/, "pathname"];
377
+ }
378
+ for (; i < instructions.length; i++) {
379
+ instruction = instructions[i];
380
+ if (typeof instruction === "function") {
381
+ address = instruction(address, url);
382
+ continue;
383
+ }
384
+ parse = instruction[0];
385
+ key = instruction[1];
386
+ if (parse !== parse) {
387
+ url[key] = address;
388
+ } else if (typeof parse === "string") {
389
+ index = parse === "@" ? address.lastIndexOf(parse) : address.indexOf(parse);
390
+ if (~index) {
391
+ if (typeof instruction[2] === "number") {
392
+ url[key] = address.slice(0, index);
393
+ address = address.slice(index + instruction[2]);
394
+ } else {
395
+ url[key] = address.slice(index);
396
+ address = address.slice(0, index);
397
+ }
398
+ }
399
+ } else if (index = parse.exec(address)) {
400
+ url[key] = index[1];
401
+ address = address.slice(0, index.index);
402
+ }
403
+ url[key] = url[key] || (relative && instruction[3] ? location[key] || "" : "");
404
+ if (instruction[4])
405
+ url[key] = url[key].toLowerCase();
406
+ }
407
+ if (parser)
408
+ url.query = parser(url.query);
409
+ if (relative && location.slashes && url.pathname.charAt(0) !== "/" && (url.pathname !== "" || location.pathname !== "")) {
410
+ url.pathname = resolve(url.pathname, location.pathname);
411
+ }
412
+ if (url.pathname.charAt(0) !== "/" && isSpecial(url.protocol)) {
413
+ url.pathname = "/" + url.pathname;
414
+ }
415
+ if (!required(url.port, url.protocol)) {
416
+ url.host = url.hostname;
417
+ url.port = "";
418
+ }
419
+ url.username = url.password = "";
420
+ if (url.auth) {
421
+ index = url.auth.indexOf(":");
422
+ if (~index) {
423
+ url.username = url.auth.slice(0, index);
424
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
425
+ url.password = url.auth.slice(index + 1);
426
+ url.password = encodeURIComponent(decodeURIComponent(url.password));
427
+ } else {
428
+ url.username = encodeURIComponent(decodeURIComponent(url.auth));
429
+ }
430
+ url.auth = url.password ? url.username + ":" + url.password : url.username;
431
+ }
432
+ url.origin = url.protocol !== "file:" && isSpecial(url.protocol) && url.host ? url.protocol + "//" + url.host : "null";
433
+ url.href = url.toString();
434
+ }
435
+ function set(part, value, fn) {
436
+ var url = this;
437
+ switch (part) {
438
+ case "query":
439
+ if (typeof value === "string" && value.length) {
440
+ value = (fn || qs.parse)(value);
441
+ }
442
+ url[part] = value;
443
+ break;
444
+ case "port":
445
+ url[part] = value;
446
+ if (!required(value, url.protocol)) {
447
+ url.host = url.hostname;
448
+ url[part] = "";
449
+ } else if (value) {
450
+ url.host = url.hostname + ":" + value;
451
+ }
452
+ break;
453
+ case "hostname":
454
+ url[part] = value;
455
+ if (url.port)
456
+ value += ":" + url.port;
457
+ url.host = value;
458
+ break;
459
+ case "host":
460
+ url[part] = value;
461
+ if (port.test(value)) {
462
+ value = value.split(":");
463
+ url.port = value.pop();
464
+ url.hostname = value.join(":");
465
+ } else {
466
+ url.hostname = value;
467
+ url.port = "";
468
+ }
469
+ break;
470
+ case "protocol":
471
+ url.protocol = value.toLowerCase();
472
+ url.slashes = !fn;
473
+ break;
474
+ case "pathname":
475
+ case "hash":
476
+ if (value) {
477
+ var char = part === "pathname" ? "/" : "#";
478
+ url[part] = value.charAt(0) !== char ? char + value : value;
479
+ } else {
480
+ url[part] = value;
481
+ }
482
+ break;
483
+ case "username":
484
+ case "password":
485
+ url[part] = encodeURIComponent(value);
486
+ break;
487
+ case "auth":
488
+ var index = value.indexOf(":");
489
+ if (~index) {
490
+ url.username = value.slice(0, index);
491
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
492
+ url.password = value.slice(index + 1);
493
+ url.password = encodeURIComponent(decodeURIComponent(url.password));
494
+ } else {
495
+ url.username = encodeURIComponent(decodeURIComponent(value));
496
+ }
497
+ }
498
+ for (var i = 0; i < rules.length; i++) {
499
+ var ins = rules[i];
500
+ if (ins[4])
501
+ url[ins[1]] = url[ins[1]].toLowerCase();
502
+ }
503
+ url.auth = url.password ? url.username + ":" + url.password : url.username;
504
+ url.origin = url.protocol !== "file:" && isSpecial(url.protocol) && url.host ? url.protocol + "//" + url.host : "null";
505
+ url.href = url.toString();
506
+ return url;
507
+ }
508
+ function toString(stringify) {
509
+ if (!stringify || typeof stringify !== "function")
510
+ stringify = qs.stringify;
511
+ var query, url = this, host = url.host, protocol = url.protocol;
512
+ if (protocol && protocol.charAt(protocol.length - 1) !== ":")
513
+ protocol += ":";
514
+ var result = protocol + (url.protocol && url.slashes || isSpecial(url.protocol) ? "//" : "");
515
+ if (url.username) {
516
+ result += url.username;
517
+ if (url.password)
518
+ result += ":" + url.password;
519
+ result += "@";
520
+ } else if (url.password) {
521
+ result += ":" + url.password;
522
+ result += "@";
523
+ } else if (url.protocol !== "file:" && isSpecial(url.protocol) && !host && url.pathname !== "/") {
524
+ result += "@";
525
+ }
526
+ if (host[host.length - 1] === ":" || port.test(url.hostname) && !url.port) {
527
+ host += ":";
528
+ }
529
+ result += host + url.pathname;
530
+ query = typeof url.query === "object" ? stringify(url.query) : url.query;
531
+ if (query)
532
+ result += query.charAt(0) !== "?" ? "?" + query : query;
533
+ if (url.hash)
534
+ result += url.hash;
535
+ return result;
536
+ }
537
+ Url.prototype = { set, toString };
538
+ Url.extractProtocol = extractProtocol;
539
+ Url.location = lolcation;
540
+ Url.trimLeft = trimLeft;
541
+ Url.qs = qs;
542
+ module.exports = Url;
543
+ }
544
+ });
545
+
546
+ // node_modules/get-it/lib/middleware/defaultOptionsProcessor.js
547
+ var require_defaultOptionsProcessor = __commonJS({
548
+ "node_modules/get-it/lib/middleware/defaultOptionsProcessor.js"(exports, module) {
549
+ "use strict";
550
+ var objectAssign = require_object_assign();
551
+ var urlParse = require_url_parse();
552
+ var isReactNative = typeof navigator === "undefined" ? false : navigator.product === "ReactNative";
553
+ var has = Object.prototype.hasOwnProperty;
554
+ var defaultOptions2 = {
555
+ timeout: isReactNative ? 6e4 : 12e4
556
+ };
557
+ module.exports = function(opts) {
558
+ var options = typeof opts === "string" ? objectAssign({
559
+ url: opts
560
+ }, defaultOptions2) : objectAssign({}, defaultOptions2, opts);
561
+ var url = urlParse(options.url, {}, true);
562
+ options.timeout = normalizeTimeout(options.timeout);
563
+ if (options.query) {
564
+ url.query = objectAssign({}, url.query, removeUndefined(options.query));
565
+ }
566
+ options.method = options.body && !options.method ? "POST" : (options.method || "GET").toUpperCase();
567
+ options.url = url.toString(stringifyQueryString);
568
+ return options;
569
+ };
570
+ function stringifyQueryString(obj) {
571
+ var pairs = [];
572
+ for (var key in obj) {
573
+ if (has.call(obj, key)) {
574
+ push(key, obj[key]);
575
+ }
576
+ }
577
+ return pairs.length ? pairs.join("&") : "";
578
+ function push(key2, val) {
579
+ if (Array.isArray(val)) {
580
+ val.forEach(function(item) {
581
+ return push(key2, item);
582
+ });
583
+ } else {
584
+ pairs.push([key2, val].map(encodeURIComponent).join("="));
585
+ }
586
+ }
587
+ }
588
+ function normalizeTimeout(time) {
589
+ if (time === false || time === 0) {
590
+ return false;
591
+ }
592
+ if (time.connect || time.socket) {
593
+ return time;
594
+ }
595
+ var delay = Number(time);
596
+ if (isNaN(delay)) {
597
+ return normalizeTimeout(defaultOptions2.timeout);
598
+ }
599
+ return {
600
+ connect: delay,
601
+ socket: delay
602
+ };
603
+ }
604
+ function removeUndefined(obj) {
605
+ var target = {};
606
+ for (var key in obj) {
607
+ if (obj[key] !== void 0) {
608
+ target[key] = obj[key];
609
+ }
610
+ }
611
+ return target;
612
+ }
613
+ }
614
+ });
615
+
616
+ // node_modules/get-it/lib/middleware/defaultOptionsValidator.js
617
+ var require_defaultOptionsValidator = __commonJS({
618
+ "node_modules/get-it/lib/middleware/defaultOptionsValidator.js"(exports, module) {
619
+ "use strict";
620
+ var validUrl = /^https?:\/\//i;
621
+ module.exports = function(options) {
622
+ if (!validUrl.test(options.url)) {
623
+ throw new Error('"'.concat(options.url, '" is not a valid URL'));
624
+ }
625
+ };
626
+ }
627
+ });
628
+
629
+ // node_modules/same-origin/url-parser.js
630
+ var require_url_parser = __commonJS({
631
+ "node_modules/same-origin/url-parser.js"(exports, module) {
632
+ "use strict";
633
+ var regex = /^(?:(?:(?:([^:\/#\?]+:)?(?:(?:\/\/)((?:((?:[^:@\/#\?]+)(?:\:(?:[^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((?:\/?(?:[^\/\?#]+\/+)*)(?:[^\?#]*)))?(\?[^#]+)?)(#.*)?/;
634
+ module.exports = {
635
+ regex,
636
+ parse: function(url) {
637
+ var match = regex.exec(url);
638
+ if (!match) {
639
+ return {};
640
+ }
641
+ return {
642
+ protocol: (match[1] || "").toLowerCase() || void 0,
643
+ hostname: (match[5] || "").toLowerCase() || void 0,
644
+ port: match[6] || void 0
645
+ };
646
+ }
647
+ };
648
+ }
649
+ });
650
+
651
+ // node_modules/same-origin/index.js
652
+ var require_same_origin = __commonJS({
653
+ "node_modules/same-origin/index.js"(exports, module) {
654
+ "use strict";
655
+ var url = require_url_parser();
656
+ module.exports = function(uri1, uri2, ieMode) {
657
+ if (uri1 === uri2) {
658
+ return true;
659
+ }
660
+ var url1 = url.parse(uri1, false, true);
661
+ var url2 = url.parse(uri2, false, true);
662
+ var url1Port = url1.port | 0 || (url1.protocol === "https" ? 443 : 80);
663
+ var url2Port = url2.port | 0 || (url2.protocol === "https" ? 443 : 80);
664
+ var match = {
665
+ proto: url1.protocol === url2.protocol,
666
+ hostname: url1.hostname === url2.hostname,
667
+ port: url1Port === url2Port
668
+ };
669
+ return match.proto && match.hostname && (match.port || ieMode);
670
+ };
671
+ }
672
+ });
673
+
674
+ // node_modules/parse-headers/parse-headers.js
675
+ var require_parse_headers = __commonJS({
676
+ "node_modules/parse-headers/parse-headers.js"(exports, module) {
677
+ var trim = function(string) {
678
+ return string.replace(/^\s+|\s+$/g, "");
679
+ };
680
+ var isArray = function(arg) {
681
+ return Object.prototype.toString.call(arg) === "[object Array]";
682
+ };
683
+ module.exports = function(headers) {
684
+ if (!headers)
685
+ return {};
686
+ var result = {};
687
+ var headersArr = trim(headers).split("\n");
688
+ for (var i = 0; i < headersArr.length; i++) {
689
+ var row = headersArr[i];
690
+ var index = row.indexOf(":"), key = trim(row.slice(0, index)).toLowerCase(), value = trim(row.slice(index + 1));
691
+ if (typeof result[key] === "undefined") {
692
+ result[key] = value;
693
+ } else if (isArray(result[key])) {
694
+ result[key].push(value);
695
+ } else {
696
+ result[key] = [result[key], value];
697
+ }
698
+ }
699
+ return result;
700
+ };
701
+ }
702
+ });
703
+
704
+ // node_modules/get-it/lib/request/browser/fetchXhr.js
705
+ var require_fetchXhr = __commonJS({
706
+ "node_modules/get-it/lib/request/browser/fetchXhr.js"(exports, module) {
707
+ "use strict";
708
+ function FetchXhr() {
709
+ this.readyState = 0;
710
+ }
711
+ FetchXhr.prototype.open = function(method, url) {
712
+ this._method = method;
713
+ this._url = url;
714
+ this._resHeaders = "";
715
+ this.readyState = 1;
716
+ this.onreadystatechange();
717
+ };
718
+ FetchXhr.prototype.abort = function() {
719
+ if (this._controller) {
720
+ this._controller.abort();
721
+ }
722
+ };
723
+ FetchXhr.prototype.getAllResponseHeaders = function() {
724
+ return this._resHeaders;
725
+ };
726
+ FetchXhr.prototype.setRequestHeader = function(key, value) {
727
+ this._headers = this._headers || {};
728
+ this._headers[key] = value;
729
+ };
730
+ FetchXhr.prototype.send = function(body) {
731
+ var _this = this;
732
+ var ctrl = this._controller = typeof AbortController === "function" && new AbortController();
733
+ var textBody = this.responseType !== "arraybuffer";
734
+ var options = {
735
+ method: this._method,
736
+ headers: this._headers,
737
+ signal: ctrl && ctrl.signal,
738
+ body
739
+ };
740
+ if (typeof window !== "undefined") {
741
+ options.credentials = this.withCredentials ? "include" : "omit";
742
+ }
743
+ fetch(this._url, options).then(function(res) {
744
+ res.headers.forEach(function(value, key) {
745
+ _this._resHeaders += "".concat(key, ": ").concat(value, "\r\n");
746
+ });
747
+ _this.status = res.status;
748
+ _this.statusText = res.statusText;
749
+ _this.readyState = 3;
750
+ return textBody ? res.text() : res.arrayBuffer();
751
+ }).then(function(resBody) {
752
+ if (textBody) {
753
+ _this.responseText = resBody;
754
+ } else {
755
+ _this.response = resBody;
756
+ }
757
+ _this.readyState = 4;
758
+ _this.onreadystatechange();
759
+ }).catch(function(err) {
760
+ if (err.name === "AbortError") {
761
+ _this.onabort();
762
+ return;
763
+ }
764
+ _this.onerror(err);
765
+ });
766
+ };
767
+ module.exports = FetchXhr;
768
+ }
769
+ });
770
+
771
+ // node_modules/get-it/lib/request/browser-request.js
772
+ var require_browser_request = __commonJS({
773
+ "node_modules/get-it/lib/request/browser-request.js"(exports, module) {
774
+ "use strict";
775
+ var sameOrigin = require_same_origin();
776
+ var parseHeaders = require_parse_headers();
777
+ var FetchXhr = require_fetchXhr();
778
+ var noop = function noop2() {
779
+ };
780
+ var win = typeof window === "undefined" ? void 0 : window;
781
+ var adapter = win ? "xhr" : "fetch";
782
+ var XmlHttpRequest = typeof XMLHttpRequest === "function" ? XMLHttpRequest : noop;
783
+ var hasXhr2 = "withCredentials" in new XmlHttpRequest();
784
+ var XDR = typeof XDomainRequest === "undefined" ? void 0 : XDomainRequest;
785
+ var CrossDomainRequest = hasXhr2 ? XmlHttpRequest : XDR;
786
+ if (!win) {
787
+ XmlHttpRequest = FetchXhr;
788
+ CrossDomainRequest = FetchXhr;
789
+ }
790
+ module.exports = function(context, callback) {
791
+ var opts = context.options;
792
+ var options = context.applyMiddleware("finalizeOptions", opts);
793
+ var timers = {};
794
+ var cors = win && win.location && !sameOrigin(win.location.href, options.url);
795
+ var injectedResponse = context.applyMiddleware("interceptRequest", void 0, {
796
+ adapter,
797
+ context
798
+ });
799
+ if (injectedResponse) {
800
+ var cbTimer = setTimeout(callback, 0, null, injectedResponse);
801
+ var cancel = function cancel2() {
802
+ return clearTimeout(cbTimer);
803
+ };
804
+ return {
805
+ abort: cancel
806
+ };
807
+ }
808
+ var xhr = cors ? new CrossDomainRequest() : new XmlHttpRequest();
809
+ var isXdr = win && win.XDomainRequest && xhr instanceof win.XDomainRequest;
810
+ var headers = options.headers;
811
+ var delays = options.timeout;
812
+ var aborted = false;
813
+ var loaded = false;
814
+ var timedOut = false;
815
+ xhr.onerror = onError;
816
+ xhr.ontimeout = onError;
817
+ xhr.onabort = function() {
818
+ stopTimers(true);
819
+ aborted = true;
820
+ };
821
+ xhr.onprogress = function() {
822
+ };
823
+ var loadEvent = isXdr ? "onload" : "onreadystatechange";
824
+ xhr[loadEvent] = function() {
825
+ resetTimers();
826
+ if (aborted || xhr.readyState !== 4 && !isXdr) {
827
+ return;
828
+ }
829
+ if (xhr.status === 0) {
830
+ return;
831
+ }
832
+ onLoad();
833
+ };
834
+ xhr.open(options.method, options.url, true);
835
+ xhr.withCredentials = !!options.withCredentials;
836
+ if (headers && xhr.setRequestHeader) {
837
+ for (var key in headers) {
838
+ if (headers.hasOwnProperty(key)) {
839
+ xhr.setRequestHeader(key, headers[key]);
840
+ }
841
+ }
842
+ } else if (headers && isXdr) {
843
+ throw new Error("Headers cannot be set on an XDomainRequest object");
844
+ }
845
+ if (options.rawBody) {
846
+ xhr.responseType = "arraybuffer";
847
+ }
848
+ context.applyMiddleware("onRequest", {
849
+ options,
850
+ adapter,
851
+ request: xhr,
852
+ context
853
+ });
854
+ xhr.send(options.body || null);
855
+ if (delays) {
856
+ timers.connect = setTimeout(function() {
857
+ return timeoutRequest("ETIMEDOUT");
858
+ }, delays.connect);
859
+ }
860
+ return {
861
+ abort
862
+ };
863
+ function abort() {
864
+ aborted = true;
865
+ if (xhr) {
866
+ xhr.abort();
867
+ }
868
+ }
869
+ function timeoutRequest(code) {
870
+ timedOut = true;
871
+ xhr.abort();
872
+ var error = new Error(code === "ESOCKETTIMEDOUT" ? "Socket timed out on request to ".concat(options.url) : "Connection timed out on request to ".concat(options.url));
873
+ error.code = code;
874
+ context.channels.error.publish(error);
875
+ }
876
+ function resetTimers() {
877
+ if (!delays) {
878
+ return;
879
+ }
880
+ stopTimers();
881
+ timers.socket = setTimeout(function() {
882
+ return timeoutRequest("ESOCKETTIMEDOUT");
883
+ }, delays.socket);
884
+ }
885
+ function stopTimers(force) {
886
+ if (force || aborted || xhr.readyState >= 2 && timers.connect) {
887
+ clearTimeout(timers.connect);
888
+ }
889
+ if (timers.socket) {
890
+ clearTimeout(timers.socket);
891
+ }
892
+ }
893
+ function onError(error) {
894
+ if (loaded) {
895
+ return;
896
+ }
897
+ stopTimers(true);
898
+ loaded = true;
899
+ xhr = null;
900
+ var err = error || new Error("Network error while attempting to reach ".concat(options.url));
901
+ err.isNetworkError = true;
902
+ err.request = options;
903
+ callback(err);
904
+ }
905
+ function reduceResponse() {
906
+ var statusCode = xhr.status;
907
+ var statusMessage = xhr.statusText;
908
+ if (isXdr && statusCode === void 0) {
909
+ statusCode = 200;
910
+ } else if (statusCode > 12e3 && statusCode < 12156) {
911
+ return onError();
912
+ } else {
913
+ statusCode = xhr.status === 1223 ? 204 : xhr.status;
914
+ statusMessage = xhr.status === 1223 ? "No Content" : statusMessage;
915
+ }
916
+ return {
917
+ body: xhr.response || xhr.responseText,
918
+ url: options.url,
919
+ method: options.method,
920
+ headers: isXdr ? {} : parseHeaders(xhr.getAllResponseHeaders()),
921
+ statusCode,
922
+ statusMessage
923
+ };
924
+ }
925
+ function onLoad() {
926
+ if (aborted || loaded || timedOut) {
927
+ return;
928
+ }
929
+ if (xhr.status === 0) {
930
+ onError(new Error("Unknown XHR error"));
931
+ return;
932
+ }
933
+ stopTimers();
934
+ loaded = true;
935
+ callback(null, reduceResponse());
936
+ }
937
+ };
938
+ }
939
+ });
940
+
941
+ // node_modules/get-it/lib/request/index.js
942
+ var require_request = __commonJS({
943
+ "node_modules/get-it/lib/request/index.js"(exports, module) {
944
+ "use strict";
945
+ module.exports = require_browser_request();
946
+ }
947
+ });
948
+
949
+ // node_modules/get-it/lib/index.js
950
+ var require_lib = __commonJS({
951
+ "node_modules/get-it/lib/index.js"(exports, module) {
952
+ "use strict";
953
+ var pubsub = require_nano_pubsub();
954
+ var middlewareReducer = require_middlewareReducer();
955
+ var processOptions = require_defaultOptionsProcessor();
956
+ var validateOptions = require_defaultOptionsValidator();
957
+ var httpRequester = require_request();
958
+ var channelNames = ["request", "response", "progress", "error", "abort"];
959
+ var middlehooks = ["processOptions", "validateOptions", "interceptRequest", "finalizeOptions", "onRequest", "onResponse", "onError", "onReturn", "onHeaders"];
960
+ module.exports = function createRequester() {
961
+ var initMiddleware = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
962
+ var httpRequest2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : httpRequester;
963
+ var loadedMiddleware = [];
964
+ var middleware3 = middlehooks.reduce(function(ware, name) {
965
+ ware[name] = ware[name] || [];
966
+ return ware;
967
+ }, {
968
+ processOptions: [processOptions],
969
+ validateOptions: [validateOptions]
970
+ });
971
+ function request2(opts) {
972
+ var channels = channelNames.reduce(function(target, name) {
973
+ target[name] = pubsub();
974
+ return target;
975
+ }, {});
976
+ var applyMiddleware = middlewareReducer(middleware3);
977
+ var options = applyMiddleware("processOptions", opts);
978
+ applyMiddleware("validateOptions", options);
979
+ var context = {
980
+ options,
981
+ channels,
982
+ applyMiddleware
983
+ };
984
+ var ongoingRequest = null;
985
+ var unsubscribe = channels.request.subscribe(function(ctx) {
986
+ ongoingRequest = httpRequest2(ctx, function(err, res) {
987
+ return onResponse(err, res, ctx);
988
+ });
989
+ });
990
+ channels.abort.subscribe(function() {
991
+ unsubscribe();
992
+ if (ongoingRequest) {
993
+ ongoingRequest.abort();
994
+ }
995
+ });
996
+ var returnValue = applyMiddleware("onReturn", channels, context);
997
+ if (returnValue === channels) {
998
+ channels.request.publish(context);
999
+ }
1000
+ return returnValue;
1001
+ function onResponse(reqErr, res, ctx) {
1002
+ var error = reqErr;
1003
+ var response = res;
1004
+ if (!error) {
1005
+ try {
1006
+ response = applyMiddleware("onResponse", res, ctx);
1007
+ } catch (err) {
1008
+ response = null;
1009
+ error = err;
1010
+ }
1011
+ }
1012
+ error = error && applyMiddleware("onError", error, ctx);
1013
+ if (error) {
1014
+ channels.error.publish(error);
1015
+ } else if (response) {
1016
+ channels.response.publish(response);
1017
+ }
1018
+ }
1019
+ }
1020
+ request2.use = function use(newMiddleware) {
1021
+ if (!newMiddleware) {
1022
+ throw new Error("Tried to add middleware that resolved to falsey value");
1023
+ }
1024
+ if (typeof newMiddleware === "function") {
1025
+ throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");
1026
+ }
1027
+ if (newMiddleware.onReturn && middleware3.onReturn.length > 0) {
1028
+ throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");
1029
+ }
1030
+ middlehooks.forEach(function(key) {
1031
+ if (newMiddleware[key]) {
1032
+ middleware3[key].push(newMiddleware[key]);
1033
+ }
1034
+ });
1035
+ loadedMiddleware.push(newMiddleware);
1036
+ return request2;
1037
+ };
1038
+ request2.clone = function clone() {
1039
+ return createRequester(loadedMiddleware);
1040
+ };
1041
+ initMiddleware.forEach(request2.use);
1042
+ return request2;
1043
+ };
1044
+ }
1045
+ });
1046
+
1047
+ // node_modules/get-it/index.js
1048
+ var require_get_it = __commonJS({
1049
+ "node_modules/get-it/index.js"(exports, module) {
1050
+ module.exports = require_lib();
1051
+ }
1052
+ });
1053
+
1054
+ // node_modules/get-it/lib/util/global.js
1055
+ var require_global = __commonJS({
1056
+ "node_modules/get-it/lib/util/global.js"(exports, module) {
1057
+ "use strict";
1058
+ if (typeof globalThis !== "undefined") {
1059
+ module.exports = globalThis;
1060
+ } else if (typeof window !== "undefined") {
1061
+ module.exports = window;
1062
+ } else if (typeof global !== "undefined") {
1063
+ module.exports = global;
1064
+ } else if (typeof self !== "undefined") {
1065
+ module.exports = self;
1066
+ } else {
1067
+ module.exports = {};
1068
+ }
1069
+ }
1070
+ });
1071
+
1072
+ // node_modules/get-it/lib/middleware/observable.js
1073
+ var require_observable = __commonJS({
1074
+ "node_modules/get-it/lib/middleware/observable.js"(exports, module) {
1075
+ "use strict";
1076
+ var global2 = require_global();
1077
+ var objectAssign = require_object_assign();
1078
+ module.exports = function() {
1079
+ var opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1080
+ var Observable2 = opts.implementation || global2.Observable;
1081
+ if (!Observable2) {
1082
+ throw new Error("`Observable` is not available in global scope, and no implementation was passed");
1083
+ }
1084
+ return {
1085
+ onReturn: function onReturn(channels, context) {
1086
+ return new Observable2(function(observer) {
1087
+ channels.error.subscribe(function(err) {
1088
+ return observer.error(err);
1089
+ });
1090
+ channels.progress.subscribe(function(event) {
1091
+ return observer.next(objectAssign({
1092
+ type: "progress"
1093
+ }, event));
1094
+ });
1095
+ channels.response.subscribe(function(response) {
1096
+ observer.next(objectAssign({
1097
+ type: "response"
1098
+ }, response));
1099
+ observer.complete();
1100
+ });
1101
+ channels.request.publish(context);
1102
+ return function() {
1103
+ return channels.abort.publish();
1104
+ };
1105
+ });
1106
+ }
1107
+ };
1108
+ };
1109
+ }
1110
+ });
1111
+
1112
+ // node_modules/isobject/index.js
1113
+ var require_isobject = __commonJS({
1114
+ "node_modules/isobject/index.js"(exports, module) {
1115
+ "use strict";
1116
+ module.exports = function isObject(val) {
1117
+ return val != null && typeof val === "object" && Array.isArray(val) === false;
1118
+ };
1119
+ }
1120
+ });
1121
+
1122
+ // node_modules/is-plain-object/index.js
1123
+ var require_is_plain_object = __commonJS({
1124
+ "node_modules/is-plain-object/index.js"(exports, module) {
1125
+ "use strict";
1126
+ var isObject = require_isobject();
1127
+ function isObjectObject(o) {
1128
+ return isObject(o) === true && Object.prototype.toString.call(o) === "[object Object]";
1129
+ }
1130
+ module.exports = function isPlainObject(o) {
1131
+ var ctor, prot;
1132
+ if (isObjectObject(o) === false)
1133
+ return false;
1134
+ ctor = o.constructor;
1135
+ if (typeof ctor !== "function")
1136
+ return false;
1137
+ prot = ctor.prototype;
1138
+ if (isObjectObject(prot) === false)
1139
+ return false;
1140
+ if (prot.hasOwnProperty("isPrototypeOf") === false) {
1141
+ return false;
1142
+ }
1143
+ return true;
1144
+ };
1145
+ }
1146
+ });
1147
+
1148
+ // node_modules/get-it/lib/middleware/jsonRequest.js
1149
+ var require_jsonRequest = __commonJS({
1150
+ "node_modules/get-it/lib/middleware/jsonRequest.js"(exports, module) {
1151
+ "use strict";
1152
+ function _typeof(obj) {
1153
+ "@babel/helpers - typeof";
1154
+ return _typeof = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(obj2) {
1155
+ return typeof obj2;
1156
+ } : function(obj2) {
1157
+ return obj2 && typeof Symbol == "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
1158
+ }, _typeof(obj);
1159
+ }
1160
+ var objectAssign = require_object_assign();
1161
+ var isPlainObject = require_is_plain_object();
1162
+ var serializeTypes = ["boolean", "string", "number"];
1163
+ var isBuffer = function isBuffer2(obj) {
1164
+ return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
1165
+ };
1166
+ module.exports = function() {
1167
+ return {
1168
+ processOptions: function processOptions(options) {
1169
+ var body = options.body;
1170
+ if (!body) {
1171
+ return options;
1172
+ }
1173
+ var isStream = typeof body.pipe === "function";
1174
+ var shouldSerialize = !isStream && !isBuffer(body) && (serializeTypes.indexOf(_typeof(body)) !== -1 || Array.isArray(body) || isPlainObject(body));
1175
+ if (!shouldSerialize) {
1176
+ return options;
1177
+ }
1178
+ return objectAssign({}, options, {
1179
+ body: JSON.stringify(options.body),
1180
+ headers: objectAssign({}, options.headers, {
1181
+ "Content-Type": "application/json"
1182
+ })
1183
+ });
1184
+ }
1185
+ };
1186
+ };
1187
+ }
1188
+ });
1189
+
1190
+ // node_modules/get-it/lib/middleware/jsonResponse.js
1191
+ var require_jsonResponse = __commonJS({
1192
+ "node_modules/get-it/lib/middleware/jsonResponse.js"(exports, module) {
1193
+ "use strict";
1194
+ var objectAssign = require_object_assign();
1195
+ module.exports = function(opts) {
1196
+ return {
1197
+ onResponse: function onResponse(response) {
1198
+ var contentType = response.headers["content-type"] || "";
1199
+ var shouldDecode = opts && opts.force || contentType.indexOf("application/json") !== -1;
1200
+ if (!response.body || !contentType || !shouldDecode) {
1201
+ return response;
1202
+ }
1203
+ return objectAssign({}, response, {
1204
+ body: tryParse(response.body)
1205
+ });
1206
+ },
1207
+ processOptions: function processOptions(options) {
1208
+ return objectAssign({}, options, {
1209
+ headers: objectAssign({
1210
+ Accept: "application/json"
1211
+ }, options.headers)
1212
+ });
1213
+ }
1214
+ };
1215
+ };
1216
+ function tryParse(body) {
1217
+ try {
1218
+ return JSON.parse(body);
1219
+ } catch (err) {
1220
+ err.message = "Failed to parsed response body as JSON: ".concat(err.message);
1221
+ throw err;
1222
+ }
1223
+ }
1224
+ }
1225
+ });
1226
+
1227
+ // node_modules/get-it/lib/middleware/progress/browser-progress.js
1228
+ var require_browser_progress = __commonJS({
1229
+ "node_modules/get-it/lib/middleware/progress/browser-progress.js"(exports, module) {
1230
+ "use strict";
1231
+ module.exports = function() {
1232
+ return {
1233
+ onRequest: function onRequest(evt) {
1234
+ if (evt.adapter !== "xhr") {
1235
+ return;
1236
+ }
1237
+ var xhr = evt.request;
1238
+ var context = evt.context;
1239
+ if ("upload" in xhr && "onprogress" in xhr.upload) {
1240
+ xhr.upload.onprogress = handleProgress("upload");
1241
+ }
1242
+ if ("onprogress" in xhr) {
1243
+ xhr.onprogress = handleProgress("download");
1244
+ }
1245
+ function handleProgress(stage) {
1246
+ return function(event) {
1247
+ var percent = event.lengthComputable ? event.loaded / event.total * 100 : -1;
1248
+ context.channels.progress.publish({
1249
+ stage,
1250
+ percent,
1251
+ total: event.total,
1252
+ loaded: event.loaded,
1253
+ lengthComputable: event.lengthComputable
1254
+ });
1255
+ };
1256
+ }
1257
+ }
1258
+ };
1259
+ };
1260
+ }
1261
+ });
1262
+
1263
+ // node_modules/get-it/lib/middleware/progress/index.js
1264
+ var require_progress = __commonJS({
1265
+ "node_modules/get-it/lib/middleware/progress/index.js"(exports, module) {
1266
+ "use strict";
1267
+ module.exports = require_browser_progress();
1268
+ }
1269
+ });
1270
+
1271
+ // src/util/observable.js
1272
+ import { Observable } from "rxjs/internal/Observable";
1273
+ import { filter } from "rxjs/internal/operators/filter";
1274
+ import { map } from "rxjs/internal/operators/map";
1275
+
1276
+ // src/util/getSelection.js
1277
+ function getSelection(sel) {
1278
+ if (typeof sel === "string" || Array.isArray(sel)) {
1279
+ return { id: sel };
1280
+ }
1281
+ if (sel && sel.query) {
1282
+ return "params" in sel ? { query: sel.query, params: sel.params } : { query: sel.query };
1283
+ }
1284
+ const selectionOpts = [
1285
+ "* Document ID (<docId>)",
1286
+ "* Array of document IDs",
1287
+ "* Object containing `query`"
1288
+ ].join("\n");
1289
+ throw new Error(`Unknown selection - must be one of:
1290
+
1291
+ ${selectionOpts}`);
1292
+ }
1293
+
1294
+ // src/validators.js
1295
+ var VALID_ASSET_TYPES = ["image", "file"];
1296
+ var VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
1297
+ var dataset = (name) => {
1298
+ if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name)) {
1299
+ throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters");
1300
+ }
1301
+ };
1302
+ var projectId = (id) => {
1303
+ if (!/^[-a-z0-9]+$/i.test(id)) {
1304
+ throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
1305
+ }
1306
+ };
1307
+ var validateAssetType = (type) => {
1308
+ if (VALID_ASSET_TYPES.indexOf(type) === -1) {
1309
+ throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
1310
+ }
1311
+ };
1312
+ var validateObject = (op, val) => {
1313
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
1314
+ throw new Error(`${op}() takes an object of properties`);
1315
+ }
1316
+ };
1317
+ var validateDocumentId = (op, id) => {
1318
+ if (typeof id !== "string" || !/^[a-z0-9_.-]+$/i.test(id)) {
1319
+ throw new Error(`${op}(): "${id}" is not a valid document ID`);
1320
+ }
1321
+ };
1322
+ var requireDocumentId = (op, doc) => {
1323
+ if (!doc._id) {
1324
+ throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
1325
+ }
1326
+ validateDocumentId(op, doc._id);
1327
+ };
1328
+ var validateInsert = (at, selector, items) => {
1329
+ const signature = "insert(at, selector, items)";
1330
+ if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
1331
+ const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
1332
+ throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
1333
+ }
1334
+ if (typeof selector !== "string") {
1335
+ throw new Error(`${signature} takes a "selector"-argument which must be a string`);
1336
+ }
1337
+ if (!Array.isArray(items)) {
1338
+ throw new Error(`${signature} takes an "items"-argument which must be an array`);
1339
+ }
1340
+ };
1341
+ var hasDataset = (config) => {
1342
+ if (!config.dataset) {
1343
+ throw new Error("`dataset` must be provided to perform queries");
1344
+ }
1345
+ return config.dataset || "";
1346
+ };
1347
+ var requestTag = (tag) => {
1348
+ if (typeof tag !== "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {
1349
+ throw new Error(`Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`);
1350
+ }
1351
+ return tag;
1352
+ };
1353
+
1354
+ // src/data/patch.js
1355
+ var Patch = class {
1356
+ constructor(selection, operations = {}, client = null) {
1357
+ this.selection = selection;
1358
+ this.operations = Object.assign({}, operations);
1359
+ this.client = client;
1360
+ }
1361
+ clone() {
1362
+ return new Patch(this.selection, Object.assign({}, this.operations), this.client);
1363
+ }
1364
+ set(props) {
1365
+ return this._assign("set", props);
1366
+ }
1367
+ diffMatchPatch(props) {
1368
+ validateObject("diffMatchPatch", props);
1369
+ return this._assign("diffMatchPatch", props);
1370
+ }
1371
+ unset(attrs) {
1372
+ if (!Array.isArray(attrs)) {
1373
+ throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
1374
+ }
1375
+ this.operations = Object.assign({}, this.operations, { unset: attrs });
1376
+ return this;
1377
+ }
1378
+ setIfMissing(props) {
1379
+ return this._assign("setIfMissing", props);
1380
+ }
1381
+ replace(props) {
1382
+ validateObject("replace", props);
1383
+ return this._set("set", { $: props });
1384
+ }
1385
+ inc(props) {
1386
+ return this._assign("inc", props);
1387
+ }
1388
+ dec(props) {
1389
+ return this._assign("dec", props);
1390
+ }
1391
+ insert(at, selector, items) {
1392
+ validateInsert(at, selector, items);
1393
+ return this._assign("insert", { [at]: selector, items });
1394
+ }
1395
+ append(selector, items) {
1396
+ return this.insert("after", `${selector}[-1]`, items);
1397
+ }
1398
+ prepend(selector, items) {
1399
+ return this.insert("before", `${selector}[0]`, items);
1400
+ }
1401
+ splice(selector, start, deleteCount, items) {
1402
+ const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
1403
+ const startIndex = start < 0 ? start - 1 : start;
1404
+ const delCount = delAll ? -1 : Math.max(0, start + deleteCount);
1405
+ const delRange = startIndex < 0 && delCount >= 0 ? "" : delCount;
1406
+ const rangeSelector = `${selector}[${startIndex}:${delRange}]`;
1407
+ return this.insert("replace", rangeSelector, items || []);
1408
+ }
1409
+ ifRevisionId(rev) {
1410
+ this.operations.ifRevisionID = rev;
1411
+ return this;
1412
+ }
1413
+ serialize() {
1414
+ return Object.assign(getSelection(this.selection), this.operations);
1415
+ }
1416
+ toJSON() {
1417
+ return this.serialize();
1418
+ }
1419
+ commit(options = {}) {
1420
+ if (!this.client) {
1421
+ throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");
1422
+ }
1423
+ const returnFirst = typeof this.selection === "string";
1424
+ const opts = Object.assign({ returnFirst, returnDocuments: true }, options);
1425
+ return this.client.mutate({ patch: this.serialize() }, opts);
1426
+ }
1427
+ reset() {
1428
+ this.operations = {};
1429
+ return this;
1430
+ }
1431
+ _set(op, props) {
1432
+ return this._assign(op, props, false);
1433
+ }
1434
+ _assign(op, props, merge = true) {
1435
+ validateObject(op, props);
1436
+ this.operations = Object.assign({}, this.operations, {
1437
+ [op]: Object.assign({}, merge && this.operations[op] || {}, props)
1438
+ });
1439
+ return this;
1440
+ }
1441
+ };
1442
+
1443
+ // src/data/transaction.js
1444
+ var defaultMutateOptions = { returnDocuments: false };
1445
+ var Transaction = class {
1446
+ constructor(operations = [], client, transactionId) {
1447
+ this.trxId = transactionId;
1448
+ this.operations = operations;
1449
+ this.client = client;
1450
+ }
1451
+ clone() {
1452
+ return new Transaction(this.operations.slice(0), this.client, this.trxId);
1453
+ }
1454
+ create(doc) {
1455
+ validateObject("create", doc);
1456
+ return this._add({ create: doc });
1457
+ }
1458
+ createIfNotExists(doc) {
1459
+ const op = "createIfNotExists";
1460
+ validateObject(op, doc);
1461
+ requireDocumentId(op, doc);
1462
+ return this._add({ [op]: doc });
1463
+ }
1464
+ createOrReplace(doc) {
1465
+ const op = "createOrReplace";
1466
+ validateObject(op, doc);
1467
+ requireDocumentId(op, doc);
1468
+ return this._add({ [op]: doc });
1469
+ }
1470
+ delete(documentId) {
1471
+ validateDocumentId("delete", documentId);
1472
+ return this._add({ delete: { id: documentId } });
1473
+ }
1474
+ patch(documentId, patchOps) {
1475
+ const isBuilder = typeof patchOps === "function";
1476
+ const isPatch = documentId instanceof Patch;
1477
+ if (isPatch) {
1478
+ return this._add({ patch: documentId.serialize() });
1479
+ }
1480
+ if (isBuilder) {
1481
+ const patch = patchOps(new Patch(documentId, {}, this.client));
1482
+ if (!(patch instanceof Patch)) {
1483
+ throw new Error("function passed to `patch()` must return the patch");
1484
+ }
1485
+ return this._add({ patch: patch.serialize() });
1486
+ }
1487
+ return this._add({ patch: Object.assign({ id: documentId }, patchOps) });
1488
+ }
1489
+ transactionId(id) {
1490
+ if (!id) {
1491
+ return this.trxId;
1492
+ }
1493
+ this.trxId = id;
1494
+ return this;
1495
+ }
1496
+ serialize() {
1497
+ return this.operations.slice();
1498
+ }
1499
+ toJSON() {
1500
+ return this.serialize();
1501
+ }
1502
+ commit(options) {
1503
+ if (!this.client) {
1504
+ throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");
1505
+ }
1506
+ return this.client.mutate(this.serialize(), Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {}));
1507
+ }
1508
+ reset() {
1509
+ this.operations = [];
1510
+ return this;
1511
+ }
1512
+ _add(mut) {
1513
+ this.operations.push(mut);
1514
+ return this;
1515
+ }
1516
+ };
1517
+
1518
+ // src/data/encodeQueryString.js
1519
+ var enc = encodeURIComponent;
1520
+ var encodeQueryString = ({ query, params = {}, options = {} }) => {
1521
+ const { tag, ...opts } = options;
1522
+ const q = `query=${enc(query)}`;
1523
+ const base = tag ? `?tag=${enc(tag)}&${q}` : `?${q}`;
1524
+ const qString = Object.keys(params).reduce((qs, param) => `${qs}&${enc(`$${param}`)}=${enc(JSON.stringify(params[param]))}`, base);
1525
+ return Object.keys(opts).reduce((qs, option) => {
1526
+ return options[option] ? `${qs}&${enc(option)}=${enc(options[option])}` : qs;
1527
+ }, qString);
1528
+ };
1529
+
1530
+ // src/data/listen.js
1531
+ import polyfilledEventSource from "@sanity/eventsource";
1532
+
1533
+ // src/util/pick.js
1534
+ var pick = (obj, props) => props.reduce((selection, prop) => {
1535
+ if (typeof obj[prop] === "undefined") {
1536
+ return selection;
1537
+ }
1538
+ selection[prop] = obj[prop];
1539
+ return selection;
1540
+ }, {});
1541
+
1542
+ // src/util/defaults.js
1543
+ var defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => {
1544
+ target[prop] = typeof obj[prop] === "undefined" ? defaults2[prop] : obj[prop];
1545
+ return target;
1546
+ }, {});
1547
+
1548
+ // src/data/listen.js
1549
+ var MAX_URL_LENGTH = 16e3 - 1200;
1550
+ var EventSource = polyfilledEventSource;
1551
+ var possibleOptions = [
1552
+ "includePreviousRevision",
1553
+ "includeResult",
1554
+ "visibility",
1555
+ "effectFormat",
1556
+ "tag"
1557
+ ];
1558
+ var defaultOptions = {
1559
+ includeResult: true
1560
+ };
1561
+ function listen(query, params, opts = {}) {
1562
+ const { url, token, withCredentials, requestTagPrefix } = this.clientConfig;
1563
+ const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag;
1564
+ const options = { ...defaults(opts, defaultOptions), tag };
1565
+ const listenOpts = pick(options, possibleOptions);
1566
+ const qs = encodeQueryString({ query, params, options: listenOpts, tag });
1567
+ const uri = `${url}${this.getDataUrl("listen", qs)}`;
1568
+ if (uri.length > MAX_URL_LENGTH) {
1569
+ return new Observable((observer) => observer.error(new Error("Query too large for listener")));
1570
+ }
1571
+ const listenFor = options.events ? options.events : ["mutation"];
1572
+ const shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1;
1573
+ const esOptions = {};
1574
+ if (token || withCredentials) {
1575
+ esOptions.withCredentials = true;
1576
+ }
1577
+ if (token) {
1578
+ esOptions.headers = {
1579
+ Authorization: `Bearer ${token}`
1580
+ };
1581
+ }
1582
+ return new Observable((observer) => {
1583
+ let es = getEventSource();
1584
+ let reconnectTimer;
1585
+ let stopped = false;
1586
+ function onError() {
1587
+ if (stopped) {
1588
+ return;
1589
+ }
1590
+ emitReconnect();
1591
+ if (stopped) {
1592
+ return;
1593
+ }
1594
+ if (es.readyState === EventSource.CLOSED) {
1595
+ unsubscribe();
1596
+ clearTimeout(reconnectTimer);
1597
+ reconnectTimer = setTimeout(open, 100);
1598
+ }
1599
+ }
1600
+ function onChannelError(err) {
1601
+ observer.error(cooerceError(err));
1602
+ }
1603
+ function onMessage(evt) {
1604
+ const event = parseEvent(evt);
1605
+ return event instanceof Error ? observer.error(event) : observer.next(event);
1606
+ }
1607
+ function onDisconnect(evt) {
1608
+ stopped = true;
1609
+ unsubscribe();
1610
+ observer.complete();
1611
+ }
1612
+ function unsubscribe() {
1613
+ es.removeEventListener("error", onError, false);
1614
+ es.removeEventListener("channelError", onChannelError, false);
1615
+ es.removeEventListener("disconnect", onDisconnect, false);
1616
+ listenFor.forEach((type) => es.removeEventListener(type, onMessage, false));
1617
+ es.close();
1618
+ }
1619
+ function emitReconnect() {
1620
+ if (shouldEmitReconnect) {
1621
+ observer.next({ type: "reconnect" });
1622
+ }
1623
+ }
1624
+ function getEventSource() {
1625
+ const evs = new EventSource(uri, esOptions);
1626
+ evs.addEventListener("error", onError, false);
1627
+ evs.addEventListener("channelError", onChannelError, false);
1628
+ evs.addEventListener("disconnect", onDisconnect, false);
1629
+ listenFor.forEach((type) => evs.addEventListener(type, onMessage, false));
1630
+ return evs;
1631
+ }
1632
+ function open() {
1633
+ es = getEventSource();
1634
+ }
1635
+ function stop() {
1636
+ stopped = true;
1637
+ unsubscribe();
1638
+ }
1639
+ return stop;
1640
+ });
1641
+ }
1642
+ function parseEvent(event) {
1643
+ try {
1644
+ const data = event.data && JSON.parse(event.data) || {};
1645
+ return Object.assign({ type: event.type }, data);
1646
+ } catch (err) {
1647
+ return err;
1648
+ }
1649
+ }
1650
+ function cooerceError(err) {
1651
+ if (err instanceof Error) {
1652
+ return err;
1653
+ }
1654
+ const evt = parseEvent(err);
1655
+ return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
1656
+ }
1657
+ function extractErrorMessage(err) {
1658
+ if (!err.error) {
1659
+ return err.message || "Unknown listener error";
1660
+ }
1661
+ if (err.error.description) {
1662
+ return err.error.description;
1663
+ }
1664
+ return typeof err.error === "string" ? err.error : JSON.stringify(err.error, null, 2);
1665
+ }
1666
+
1667
+ // src/data/dataMethods.js
1668
+ var excludeFalsey = (param, defValue) => {
1669
+ const value = typeof param === "undefined" ? defValue : param;
1670
+ return param === false ? void 0 : value;
1671
+ };
1672
+ var getMutationQuery = (options = {}) => {
1673
+ return {
1674
+ dryRun: options.dryRun,
1675
+ returnIds: true,
1676
+ returnDocuments: excludeFalsey(options.returnDocuments, true),
1677
+ visibility: options.visibility || "sync",
1678
+ autoGenerateArrayKeys: options.autoGenerateArrayKeys,
1679
+ skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
1680
+ };
1681
+ };
1682
+ var isResponse = (event) => event.type === "response";
1683
+ var getBody = (event) => event.body;
1684
+ var indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
1685
+ indexed[attr(doc)] = doc;
1686
+ return indexed;
1687
+ }, /* @__PURE__ */ Object.create(null));
1688
+ var toPromise = (observable2) => observable2.toPromise();
1689
+ var getQuerySizeLimit = 11264;
1690
+ var dataMethods = {
1691
+ listen,
1692
+ getDataUrl(operation, path) {
1693
+ const config = this.clientConfig;
1694
+ const catalog = hasDataset(config);
1695
+ const baseUri = `/${operation}/${catalog}`;
1696
+ const uri = path ? `${baseUri}/${path}` : baseUri;
1697
+ return `/data${uri}`.replace(/\/($|\?)/, "$1");
1698
+ },
1699
+ fetch(query, params, options = {}) {
1700
+ const mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result;
1701
+ const observable2 = this._dataRequest("query", { query, params }, options).pipe(map(mapResponse));
1702
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
1703
+ },
1704
+ getDocument(id, opts = {}) {
1705
+ const options = { uri: this.getDataUrl("doc", id), json: true, tag: opts.tag };
1706
+ const observable2 = this._requestObservable(options).pipe(filter(isResponse), map((event) => event.body.documents && event.body.documents[0]));
1707
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
1708
+ },
1709
+ getDocuments(ids, opts = {}) {
1710
+ const options = { uri: this.getDataUrl("doc", ids.join(",")), json: true, tag: opts.tag };
1711
+ const observable2 = this._requestObservable(options).pipe(filter(isResponse), map((event) => {
1712
+ const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
1713
+ return ids.map((id) => indexed[id] || null);
1714
+ }));
1715
+ return this.isPromiseAPI() ? toPromise(observable2) : observable2;
1716
+ },
1717
+ create(doc, options) {
1718
+ return this._create(doc, "create", options);
1719
+ },
1720
+ createIfNotExists(doc, options) {
1721
+ requireDocumentId("createIfNotExists", doc);
1722
+ return this._create(doc, "createIfNotExists", options);
1723
+ },
1724
+ createOrReplace(doc, options) {
1725
+ requireDocumentId("createOrReplace", doc);
1726
+ return this._create(doc, "createOrReplace", options);
1727
+ },
1728
+ patch(selector, operations) {
1729
+ return new Patch(selector, operations, this);
1730
+ },
1731
+ delete(selection, options) {
1732
+ return this.dataRequest("mutate", { mutations: [{ delete: getSelection(selection) }] }, options);
1733
+ },
1734
+ mutate(mutations, options) {
1735
+ const mut = mutations instanceof Patch || mutations instanceof Transaction ? mutations.serialize() : mutations;
1736
+ const muts = Array.isArray(mut) ? mut : [mut];
1737
+ const transactionId = options && options.transactionId;
1738
+ return this.dataRequest("mutate", { mutations: muts, transactionId }, options);
1739
+ },
1740
+ transaction(operations) {
1741
+ return new Transaction(operations, this);
1742
+ },
1743
+ dataRequest(endpoint, body, options = {}) {
1744
+ const request2 = this._dataRequest(endpoint, body, options);
1745
+ return this.isPromiseAPI() ? toPromise(request2) : request2;
1746
+ },
1747
+ _dataRequest(endpoint, body, options = {}) {
1748
+ const isMutation = endpoint === "mutate";
1749
+ const isQuery = endpoint === "query";
1750
+ const strQuery = !isMutation && encodeQueryString(body);
1751
+ const useGet = !isMutation && strQuery.length < getQuerySizeLimit;
1752
+ const stringQuery = useGet ? strQuery : "";
1753
+ const returnFirst = options.returnFirst;
1754
+ const { timeout, token, tag, headers } = options;
1755
+ const uri = this.getDataUrl(endpoint, stringQuery);
1756
+ const reqOptions = {
1757
+ method: useGet ? "GET" : "POST",
1758
+ uri,
1759
+ json: true,
1760
+ body: useGet ? void 0 : body,
1761
+ query: isMutation && getMutationQuery(options),
1762
+ timeout,
1763
+ headers,
1764
+ token,
1765
+ tag,
1766
+ canUseCdn: isQuery
1767
+ };
1768
+ return this._requestObservable(reqOptions).pipe(filter(isResponse), map(getBody), map((res) => {
1769
+ if (!isMutation) {
1770
+ return res;
1771
+ }
1772
+ const results = res.results || [];
1773
+ if (options.returnDocuments) {
1774
+ return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
1775
+ }
1776
+ const key = returnFirst ? "documentId" : "documentIds";
1777
+ const ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
1778
+ return {
1779
+ transactionId: res.transactionId,
1780
+ results,
1781
+ [key]: ids
1782
+ };
1783
+ }));
1784
+ },
1785
+ _create(doc, op, options = {}) {
1786
+ const mutation = { [op]: doc };
1787
+ const opts = Object.assign({ returnFirst: true, returnDocuments: true }, options);
1788
+ return this.dataRequest("mutate", { mutations: [mutation] }, opts);
1789
+ }
1790
+ };
1791
+
1792
+ // src/datasets/datasetsClient.js
1793
+ var DatasetsClient = class {
1794
+ constructor(client) {
1795
+ this.request = client.request.bind(client);
1796
+ }
1797
+ create(name, options) {
1798
+ return this._modify("PUT", name, options);
1799
+ }
1800
+ edit(name, options) {
1801
+ return this._modify("PATCH", name, options);
1802
+ }
1803
+ delete(name) {
1804
+ return this._modify("DELETE", name);
1805
+ }
1806
+ list() {
1807
+ return this.request({ uri: "/datasets" });
1808
+ }
1809
+ _modify(method, name, body) {
1810
+ dataset(name);
1811
+ return this.request({ method, uri: `/datasets/${name}`, body });
1812
+ }
1813
+ };
1814
+
1815
+ // src/projects/projectsClient.js
1816
+ var ProjectsClient = class {
1817
+ constructor(client) {
1818
+ this.client = client;
1819
+ }
1820
+ list() {
1821
+ return this.client.request({ uri: "/projects" });
1822
+ }
1823
+ getById(id) {
1824
+ return this.client.request({ uri: `/projects/${id}` });
1825
+ }
1826
+ };
1827
+
1828
+ // src/http/queryString.js
1829
+ var queryString = (params) => {
1830
+ const qs = [];
1831
+ for (const key in params) {
1832
+ if (params.hasOwnProperty(key)) {
1833
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
1834
+ }
1835
+ }
1836
+ return qs.length > 0 ? `?${qs.join("&")}` : "";
1837
+ };
1838
+
1839
+ // src/assets/assetsClient.js
1840
+ var AssetsClient = class {
1841
+ constructor(client) {
1842
+ this.client = client;
1843
+ }
1844
+ upload(assetType, body, opts = {}) {
1845
+ validateAssetType(assetType);
1846
+ let meta = opts.extract || void 0;
1847
+ if (meta && !meta.length) {
1848
+ meta = ["none"];
1849
+ }
1850
+ const dataset2 = hasDataset(this.client.clientConfig);
1851
+ const assetEndpoint = assetType === "image" ? "images" : "files";
1852
+ const options = optionsFromFile(opts, body);
1853
+ const { tag, label, title, description, creditLine, filename, source } = options;
1854
+ const query = {
1855
+ label,
1856
+ title,
1857
+ description,
1858
+ filename,
1859
+ meta,
1860
+ creditLine
1861
+ };
1862
+ if (source) {
1863
+ query.sourceId = source.id;
1864
+ query.sourceName = source.name;
1865
+ query.sourceUrl = source.url;
1866
+ }
1867
+ const observable2 = this.client._requestObservable({
1868
+ tag,
1869
+ method: "POST",
1870
+ timeout: options.timeout || 0,
1871
+ uri: `/assets/${assetEndpoint}/${dataset2}`,
1872
+ headers: options.contentType ? { "Content-Type": options.contentType } : {},
1873
+ query,
1874
+ body
1875
+ });
1876
+ return this.client.isPromiseAPI() ? observable2.pipe(filter((event) => event.type === "response"), map((event) => event.body.document)).toPromise() : observable2;
1877
+ }
1878
+ delete(type, id) {
1879
+ console.warn("client.assets.delete() is deprecated, please use client.delete(<document-id>)");
1880
+ let docId = id || "";
1881
+ if (!/^(image|file)-/.test(docId)) {
1882
+ docId = `${type}-${docId}`;
1883
+ } else if (type._id) {
1884
+ docId = type._id;
1885
+ }
1886
+ hasDataset(this.client.clientConfig);
1887
+ return this.client.delete(docId);
1888
+ }
1889
+ getImageUrl(ref, query) {
1890
+ const id = ref._ref || ref;
1891
+ if (typeof id !== "string") {
1892
+ throw new Error("getImageUrl() needs either an object with a _ref, or a string with an asset document ID");
1893
+ }
1894
+ if (!/^image-[A-Za-z0-9_]+-\d+x\d+-[a-z]{1,5}$/.test(id)) {
1895
+ throw new Error(`Unsupported asset ID "${id}". URL generation only works for auto-generated IDs.`);
1896
+ }
1897
+ const [, assetId, size, format] = id.split("-");
1898
+ hasDataset(this.client.clientConfig);
1899
+ const { projectId: projectId2, dataset: dataset2 } = this.client.clientConfig;
1900
+ const qs = query ? queryString(query) : "";
1901
+ return `https://cdn.sanity.io/images/${projectId2}/${dataset2}/${assetId}-${size}.${format}${qs}`;
1902
+ }
1903
+ };
1904
+ function optionsFromFile(opts, file) {
1905
+ if (typeof window === "undefined" || !(file instanceof window.File)) {
1906
+ return opts;
1907
+ }
1908
+ return Object.assign({
1909
+ filename: opts.preserveFilename === false ? void 0 : file.name,
1910
+ contentType: file.type
1911
+ }, opts);
1912
+ }
1913
+
1914
+ // src/users/usersClient.js
1915
+ var UsersClient = class {
1916
+ constructor(client) {
1917
+ this.client = client;
1918
+ }
1919
+ getById(id) {
1920
+ return this.client.request({ uri: `/users/${id}` });
1921
+ }
1922
+ };
1923
+
1924
+ // src/auth/authClient.js
1925
+ var AuthClient = class {
1926
+ constructor(client) {
1927
+ this.client = client;
1928
+ }
1929
+ getLoginProviders() {
1930
+ return this.client.request({ uri: "/auth/providers" });
1931
+ }
1932
+ logout() {
1933
+ return this.client.request({ uri: "/auth/logout", method: "POST" });
1934
+ }
1935
+ };
1936
+
1937
+ // src/http/request.js
1938
+ var import_get_it = __toESM(require_get_it());
1939
+ var import_observable4 = __toESM(require_observable());
1940
+ var import_jsonRequest = __toESM(require_jsonRequest());
1941
+ var import_jsonResponse = __toESM(require_jsonResponse());
1942
+ var import_progress = __toESM(require_progress());
1943
+
1944
+ // src/http/errors.js
1945
+ import makeError from "make-error";
1946
+ function ClientError(res) {
1947
+ const props = extractErrorProps(res);
1948
+ ClientError.super.call(this, props.message);
1949
+ Object.assign(this, props);
1950
+ }
1951
+ function ServerError(res) {
1952
+ const props = extractErrorProps(res);
1953
+ ServerError.super.call(this, props.message);
1954
+ Object.assign(this, props);
1955
+ }
1956
+ function extractErrorProps(res) {
1957
+ const body = res.body;
1958
+ const props = {
1959
+ response: res,
1960
+ statusCode: res.statusCode,
1961
+ responseBody: stringifyBody(body, res)
1962
+ };
1963
+ if (body.error && body.message) {
1964
+ props.message = `${body.error} - ${body.message}`;
1965
+ return props;
1966
+ }
1967
+ if (body.error && body.error.description) {
1968
+ props.message = body.error.description;
1969
+ props.details = body.error;
1970
+ return props;
1971
+ }
1972
+ props.message = body.error || body.message || httpErrorMessage(res);
1973
+ return props;
1974
+ }
1975
+ function httpErrorMessage(res) {
1976
+ const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
1977
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
1978
+ }
1979
+ function stringifyBody(body, res) {
1980
+ const contentType = (res.headers["content-type"] || "").toLowerCase();
1981
+ const isJson = contentType.indexOf("application/json") !== -1;
1982
+ return isJson ? JSON.stringify(body, null, 2) : body;
1983
+ }
1984
+ makeError(ClientError);
1985
+ makeError(ServerError);
1986
+
1987
+ // src/http/browserMiddleware.js
1988
+ var middleware = [];
1989
+
1990
+ // src/http/request.js
1991
+ var httpError = {
1992
+ onResponse: (res) => {
1993
+ if (res.statusCode >= 500) {
1994
+ throw new ServerError(res);
1995
+ } else if (res.statusCode >= 400) {
1996
+ throw new ClientError(res);
1997
+ }
1998
+ return res;
1999
+ }
2000
+ };
2001
+ var printWarnings = {
2002
+ onResponse: (res) => {
2003
+ const warn = res.headers["x-sanity-warning"];
2004
+ const warnings = Array.isArray(warn) ? warn : [warn];
2005
+ warnings.filter(Boolean).forEach((msg) => console.warn(msg));
2006
+ return res;
2007
+ }
2008
+ };
2009
+ var middleware2 = middleware.concat([
2010
+ printWarnings,
2011
+ (0, import_jsonRequest.default)(),
2012
+ (0, import_jsonResponse.default)(),
2013
+ (0, import_progress.default)(),
2014
+ httpError,
2015
+ (0, import_observable4.default)({ implementation: Observable })
2016
+ ]);
2017
+ var request = (0, import_get_it.default)(middleware2);
2018
+ function httpRequest(options, requester = request) {
2019
+ return requester(Object.assign({ maxRedirects: 0 }, options));
2020
+ }
2021
+ httpRequest.defaultRequester = request;
2022
+ httpRequest.ClientError = ClientError;
2023
+ httpRequest.ServerError = ServerError;
2024
+
2025
+ // src/http/requestOptions.js
2026
+ var projectHeader = "X-Sanity-Project-ID";
2027
+ var requestOptions = (config, overrides = {}) => {
2028
+ const headers = {};
2029
+ const token = overrides.token || config.token;
2030
+ if (token) {
2031
+ headers.Authorization = `Bearer ${token}`;
2032
+ }
2033
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
2034
+ headers[projectHeader] = config.projectId;
2035
+ }
2036
+ const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
2037
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
2038
+ return Object.assign({}, overrides, {
2039
+ headers: Object.assign({}, headers, overrides.headers || {}),
2040
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
2041
+ proxy: overrides.proxy || config.proxy,
2042
+ json: true,
2043
+ withCredentials
2044
+ });
2045
+ };
2046
+
2047
+ // src/config.js
2048
+ import { generateHelpUrl as generateHelpUrl2 } from "@sanity/generate-help-url";
2049
+
2050
+ // src/warnings.js
2051
+ import { generateHelpUrl } from "@sanity/generate-help-url";
2052
+
2053
+ // src/util/once.js
2054
+ var once = (fn) => {
2055
+ let didCall = false;
2056
+ let returnValue;
2057
+ return (...args) => {
2058
+ if (didCall) {
2059
+ return returnValue;
2060
+ }
2061
+ returnValue = fn(...args);
2062
+ didCall = true;
2063
+ return returnValue;
2064
+ };
2065
+ };
2066
+
2067
+ // src/warnings.js
2068
+ var createWarningPrinter = (message) => once((...args) => console.warn(message.join(" "), ...args));
2069
+ var printCdnWarning = createWarningPrinter([
2070
+ "You are not using the Sanity CDN. That means your data is always fresh, but the CDN is faster and",
2071
+ `cheaper. Think about it! For more info, see ${generateHelpUrl("js-client-cdn-configuration")}.`,
2072
+ "To hide this warning, please set the `useCdn` option to either `true` or `false` when creating",
2073
+ "the client."
2074
+ ]);
2075
+ var printBrowserTokenWarning = createWarningPrinter([
2076
+ "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
2077
+ `See ${generateHelpUrl("js-client-browser-token")} for more information and how to hide this warning.`
2078
+ ]);
2079
+ var printNoApiVersionSpecifiedWarning = createWarningPrinter([
2080
+ "Using the Sanity client without specifying an API version is deprecated.",
2081
+ `See ${generateHelpUrl("js-client-api-version")}`
2082
+ ]);
2083
+
2084
+ // src/config.js
2085
+ var defaultCdnHost = "apicdn.sanity.io";
2086
+ var defaultConfig = {
2087
+ apiHost: "https://api.sanity.io",
2088
+ apiVersion: "1",
2089
+ useProjectHostname: true,
2090
+ isPromiseAPI: true
2091
+ };
2092
+ var LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
2093
+ var isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
2094
+ var initConfig = (config, prevConfig) => {
2095
+ const specifiedConfig = Object.assign({}, prevConfig, config);
2096
+ if (!specifiedConfig.apiVersion) {
2097
+ printNoApiVersionSpecifiedWarning();
2098
+ }
2099
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
2100
+ const projectBased = newConfig.useProjectHostname;
2101
+ if (typeof Promise === "undefined") {
2102
+ const helpUrl = generateHelpUrl2("js-client-promise-polyfill");
2103
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
2104
+ }
2105
+ if (projectBased && !newConfig.projectId) {
2106
+ throw new Error("Configuration must contain `projectId`");
2107
+ }
2108
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
2109
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
2110
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
2111
+ printBrowserTokenWarning();
2112
+ } else if (typeof newConfig.useCdn === "undefined") {
2113
+ printCdnWarning();
2114
+ }
2115
+ if (projectBased) {
2116
+ projectId(newConfig.projectId);
2117
+ }
2118
+ if (newConfig.dataset) {
2119
+ dataset(newConfig.dataset);
2120
+ }
2121
+ if ("requestTagPrefix" in newConfig) {
2122
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
2123
+ }
2124
+ newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, "");
2125
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
2126
+ newConfig.useCdn = Boolean(newConfig.useCdn) && !newConfig.withCredentials;
2127
+ validateApiVersion(newConfig.apiVersion);
2128
+ const hostParts = newConfig.apiHost.split("://", 2);
2129
+ const protocol = hostParts[0];
2130
+ const host = hostParts[1];
2131
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
2132
+ if (newConfig.useProjectHostname) {
2133
+ newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`;
2134
+ newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`;
2135
+ } else {
2136
+ newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`;
2137
+ newConfig.cdnUrl = newConfig.url;
2138
+ }
2139
+ return newConfig;
2140
+ };
2141
+ function validateApiVersion(apiVersion) {
2142
+ if (apiVersion === "1" || apiVersion === "X") {
2143
+ return;
2144
+ }
2145
+ const apiDate = new Date(apiVersion);
2146
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
2147
+ if (!apiVersionValid) {
2148
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
2149
+ }
2150
+ }
2151
+
2152
+ // src/sanityClient.js
2153
+ var toPromise2 = (observable2) => observable2.toPromise();
2154
+ var SanityClient = class {
2155
+ constructor(config = defaultConfig) {
2156
+ this.config(config);
2157
+ this.assets = new AssetsClient(this);
2158
+ this.datasets = new DatasetsClient(this);
2159
+ this.projects = new ProjectsClient(this);
2160
+ this.users = new UsersClient(this);
2161
+ this.auth = new AuthClient(this);
2162
+ if (this.clientConfig.isPromiseAPI) {
2163
+ const observableConfig = Object.assign({}, this.clientConfig, { isPromiseAPI: false });
2164
+ this.observable = new SanityClient(observableConfig);
2165
+ }
2166
+ }
2167
+ clone() {
2168
+ return new SanityClient(this.config());
2169
+ }
2170
+ config(newConfig) {
2171
+ if (typeof newConfig === "undefined") {
2172
+ return Object.assign({}, this.clientConfig);
2173
+ }
2174
+ if (this.observable) {
2175
+ const observableConfig = Object.assign({}, newConfig, { isPromiseAPI: false });
2176
+ this.observable.config(observableConfig);
2177
+ }
2178
+ this.clientConfig = initConfig(newConfig, this.clientConfig || {});
2179
+ return this;
2180
+ }
2181
+ withConfig(newConfig) {
2182
+ return this.clone().config(newConfig);
2183
+ }
2184
+ getUrl(uri, useCdn = false) {
2185
+ const base = useCdn ? this.clientConfig.cdnUrl : this.clientConfig.url;
2186
+ return `${base}/${uri.replace(/^\//, "")}`;
2187
+ }
2188
+ isPromiseAPI() {
2189
+ return this.clientConfig.isPromiseAPI;
2190
+ }
2191
+ _requestObservable(options) {
2192
+ const uri = options.url || options.uri;
2193
+ const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
2194
+ const useCdn = this.clientConfig.useCdn && canUseCdn;
2195
+ const tag = options.tag && this.clientConfig.requestTagPrefix ? [this.clientConfig.requestTagPrefix, options.tag].join(".") : options.tag || this.clientConfig.requestTagPrefix;
2196
+ if (tag) {
2197
+ options.query = { tag: requestTag(tag), ...options.query };
2198
+ }
2199
+ const reqOptions = requestOptions(this.clientConfig, Object.assign({}, options, {
2200
+ url: this.getUrl(uri, useCdn)
2201
+ }));
2202
+ return new Observable((subscriber) => httpRequest(reqOptions, this.clientConfig.requester).subscribe(subscriber));
2203
+ }
2204
+ request(options) {
2205
+ const observable2 = this._requestObservable(options).pipe(filter((event) => event.type === "response"), map((event) => event.body));
2206
+ return this.isPromiseAPI() ? toPromise2(observable2) : observable2;
2207
+ }
2208
+ };
2209
+ Object.assign(SanityClient.prototype, dataMethods);
2210
+ SanityClient.Patch = Patch;
2211
+ SanityClient.Transaction = Transaction;
2212
+ SanityClient.ClientError = httpRequest.ClientError;
2213
+ SanityClient.ServerError = httpRequest.ServerError;
2214
+ SanityClient.requester = httpRequest.defaultRequester;
2215
+ function createClient(config) {
2216
+ return new SanityClient(config);
2217
+ }
2218
+ createClient.Patch = Patch;
2219
+ createClient.Transaction = Transaction;
2220
+ createClient.ClientError = httpRequest.ClientError;
2221
+ createClient.ServerError = httpRequest.ServerError;
2222
+ createClient.requester = httpRequest.defaultRequester;
2223
+ export {
2224
+ SanityClient,
2225
+ createClient
2226
+ };
2227
+ /*
2228
+ object-assign
2229
+ (c) Sindre Sorhus
2230
+ @license MIT
2231
+ */
2232
+ /*!
2233
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
2234
+ *
2235
+ * Copyright (c) 2014-2017, Jon Schlinkert.
2236
+ * Released under the MIT License.
2237
+ */
2238
+ /*!
2239
+ * isobject <https://github.com/jonschlinkert/isobject>
2240
+ *
2241
+ * Copyright (c) 2014-2017, Jon Schlinkert.
2242
+ * Released under the MIT License.
2243
+ */