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