@sanity/client 3.4.0-beta.esm.2 → 3.4.0

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