-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkinto-http-client.js
2669 lines (2644 loc) · 111 KB
/
kinto-http-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*
* This file is generated from kinto-http.js - do not modify directly.
*/
const global = this;
var EXPORTED_SYMBOLS = ["KintoHttpClient"];
const { setTimeout, clearTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm");
const { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGlobalGetters(global, ["fetch"]);
/*
* Version 5.1.1 - 30c540a
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.KintoHttpClient = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
/**
* Chunks an array into n pieces.
*
* @private
* @param {Array} array
* @param {Number} n
* @return {Array}
*/
function partition(array, n) {
if (n <= 0) {
return [array];
}
return array.reduce((acc, x, i) => {
if (i === 0 || i % n === 0) {
acc.push([x]);
}
else {
acc[acc.length - 1].push(x);
}
return acc;
}, []);
}
/**
* Returns a Promise always resolving after the specified amount in milliseconds.
*
* @return Promise<void>
*/
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Always returns a resource data object from the provided argument.
*
* @private
* @param {Object|String} resource
* @return {Object}
*/
function toDataBody(resource) {
if (isObject(resource)) {
return resource;
}
if (typeof resource === "string") {
return { id: resource };
}
throw new Error("Invalid argument.");
}
/**
* Transforms an object into an URL query string, stripping out any undefined
* values.
*
* @param {Object} obj
* @return {String}
*/
function qsify(obj) {
const encode = (v) => encodeURIComponent(typeof v === "boolean" ? String(v) : v);
const stripped = cleanUndefinedProperties(obj);
return Object.keys(stripped)
.map((k) => {
const ks = encode(k) + "=";
if (Array.isArray(stripped[k])) {
return ks + stripped[k].map((v) => encode(v)).join(",");
}
else {
return ks + encode(stripped[k]);
}
})
.join("&");
}
/**
* Checks if a version is within the provided range.
*
* @param {String} version The version to check.
* @param {String} minVersion The minimum supported version (inclusive).
* @param {String} maxVersion The minimum supported version (exclusive).
* @throws {Error} If the version is outside of the provided range.
*/
function checkVersion(version, minVersion, maxVersion) {
const extract = (str) => str.split(".").map((x) => parseInt(x, 10));
const [verMajor, verMinor] = extract(version);
const [minMajor, minMinor] = extract(minVersion);
const [maxMajor, maxMinor] = extract(maxVersion);
const checks = [
verMajor < minMajor,
verMajor === minMajor && verMinor < minMinor,
verMajor > maxMajor,
verMajor === maxMajor && verMinor >= maxMinor,
];
if (checks.some((x) => x)) {
throw new Error(`Version ${version} doesn't satisfy ${minVersion} <= x < ${maxVersion}`);
}
}
/**
* Generates a decorator function ensuring a version check is performed against
* the provided requirements before executing it.
*
* @param {String} min The required min version (inclusive).
* @param {String} max The required max version (inclusive).
* @return {Function}
*/
function support(min, max) {
return function (
// @ts-ignore
target, key, descriptor) {
const fn = descriptor.value;
return {
configurable: true,
get() {
const wrappedMethod = (...args) => {
// "this" is the current instance which its method is decorated.
const client = this.client ? this.client : this;
return client
.fetchHTTPApiVersion()
.then((version) => checkVersion(version, min, max))
.then(() => fn.apply(this, args));
};
Object.defineProperty(this, key, {
value: wrappedMethod,
configurable: true,
writable: true,
});
return wrappedMethod;
},
};
};
}
/**
* Generates a decorator function ensuring that the specified capabilities are
* available on the server before executing it.
*
* @param {Array<String>} capabilities The required capabilities.
* @return {Function}
*/
function capable(capabilities) {
return function (
// @ts-ignore
target, key, descriptor) {
const fn = descriptor.value;
return {
configurable: true,
get() {
const wrappedMethod = (...args) => {
// "this" is the current instance which its method is decorated.
const client = this.client ? this.client : this;
return client
.fetchServerCapabilities()
.then((available) => {
const missing = capabilities.filter((c) => !(c in available));
if (missing.length > 0) {
const missingStr = missing.join(", ");
throw new Error(`Required capabilities ${missingStr} not present on server`);
}
})
.then(() => fn.apply(this, args));
};
Object.defineProperty(this, key, {
value: wrappedMethod,
configurable: true,
writable: true,
});
return wrappedMethod;
},
};
};
}
/**
* Generates a decorator function ensuring an operation is not performed from
* within a batch request.
*
* @param {String} message The error message to throw.
* @return {Function}
*/
function nobatch(message) {
return function (
// @ts-ignore
target, key, descriptor) {
const fn = descriptor.value;
return {
configurable: true,
get() {
const wrappedMethod = (...args) => {
// "this" is the current instance which its method is decorated.
if (this._isBatch) {
throw new Error(message);
}
return fn.apply(this, args);
};
Object.defineProperty(this, key, {
value: wrappedMethod,
configurable: true,
writable: true,
});
return wrappedMethod;
},
};
};
}
/**
* Returns true if the specified value is an object (i.e. not an array nor null).
* @param {Object} thing The value to inspect.
* @return {bool}
*/
function isObject(thing) {
return typeof thing === "object" && thing !== null && !Array.isArray(thing);
}
/**
* Parses a data url.
* @param {String} dataURL The data url.
* @return {Object}
*/
function parseDataURL(dataURL) {
const regex = /^data:(.*);base64,(.*)/;
const match = dataURL.match(regex);
if (!match) {
throw new Error(`Invalid data-url: ${String(dataURL).substr(0, 32)}...`);
}
const props = match[1];
const base64 = match[2];
const [type, ...rawParams] = props.split(";");
const params = rawParams.reduce((acc, param) => {
const [key, value] = param.split("=");
return Object.assign(Object.assign({}, acc), { [key]: value });
}, {});
return Object.assign(Object.assign({}, params), { type, base64 });
}
/**
* Extracts file information from a data url.
* @param {String} dataURL The data url.
* @return {Object}
*/
function extractFileInfo(dataURL) {
const { name, type, base64 } = parseDataURL(dataURL);
const binary = atob(base64);
const array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
const blob = new Blob([new Uint8Array(array)], { type });
return { blob, name };
}
/**
* Creates a FormData instance from a data url and an existing JSON response
* body.
* @param {String} dataURL The data url.
* @param {Object} body The response body.
* @param {Object} [options={}] The options object.
* @param {Object} [options.filename] Force attachment file name.
* @return {FormData}
*/
function createFormData(dataURL, body, options = {}) {
const { filename = "untitled" } = options;
const { blob, name } = extractFileInfo(dataURL);
const formData = new FormData();
formData.append("attachment", blob, name || filename);
for (const property in body) {
if (typeof body[property] !== "undefined") {
formData.append(property, JSON.stringify(body[property]));
}
}
return formData;
}
/**
* Clones an object with all its undefined keys removed.
* @private
*/
function cleanUndefinedProperties(obj) {
const result = {};
for (const key in obj) {
if (typeof obj[key] !== "undefined") {
result[key] = obj[key];
}
}
return result;
}
/**
* Handle common query parameters for Kinto requests.
*
* @param {String} [path] The endpoint base path.
* @param {Array} [options.fields] Fields to limit the
* request to.
* @param {Object} [options.query={}] Additional query arguments.
*/
function addEndpointOptions(path, options = {}) {
const query = Object.assign({}, options.query);
if (options.fields) {
query._fields = options.fields;
}
const queryString = qsify(query);
if (queryString) {
return path + "?" + queryString;
}
return path;
}
/**
* Replace authorization header with an obscured version
*/
function obscureAuthorizationHeader(headers) {
const h = new Headers(headers);
if (h.has("authorization")) {
h.set("authorization", "**** (suppressed)");
}
const obscuredHeaders = {};
for (const [header, value] of h.entries()) {
obscuredHeaders[header] = value;
}
return obscuredHeaders;
}
/**
* Kinto server error code descriptors.
*/
const ERROR_CODES = {
104: "Missing Authorization Token",
105: "Invalid Authorization Token",
106: "Request body was not valid JSON",
107: "Invalid request parameter",
108: "Missing request parameter",
109: "Invalid posted data",
110: "Invalid Token / id",
111: "Missing Token / id",
112: "Content-Length header was not provided",
113: "Request body too large",
114: "Resource was created, updated or deleted meanwhile",
115: "Method not allowed on this end point (hint: server may be readonly)",
116: "Requested version not available on this server",
117: "Client has sent too many requests",
121: "Resource access is forbidden for this user",
122: "Another resource violates constraint",
201: "Service Temporary unavailable due to high load",
202: "Service deprecated",
999: "Internal Server Error",
};
class NetworkTimeoutError extends Error {
constructor(url, options) {
super(`Timeout while trying to access ${url} with ${JSON.stringify(options)}`);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, NetworkTimeoutError);
}
this.url = url;
this.options = options;
}
}
class UnparseableResponseError extends Error {
constructor(response, body, error) {
const { status } = response;
super(`Response from server unparseable (HTTP ${status || 0}; ${error}): ${body}`);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnparseableResponseError);
}
this.status = status;
this.response = response;
this.stack = error.stack;
this.error = error;
}
}
/**
* "Error" subclass representing a >=400 response from the server.
*
* Whether or not this is an error depends on your application.
*
* The `json` field can be undefined if the server responded with an
* empty response body. This shouldn't generally happen. Most "bad"
* responses come with a JSON error description, or (if they're
* fronted by a CDN or nginx or something) occasionally non-JSON
* responses (which become UnparseableResponseErrors, above).
*/
class ServerResponse extends Error {
constructor(response, json) {
const { status } = response;
let { statusText } = response;
let errnoMsg;
if (json) {
// Try to fill in information from the JSON error.
statusText = json.error || statusText;
// Take errnoMsg from either ERROR_CODES or json.message.
if (json.errno && json.errno in ERROR_CODES) {
errnoMsg = ERROR_CODES[json.errno];
}
else if (json.message) {
errnoMsg = json.message;
}
// If we had both ERROR_CODES and json.message, and they differ,
// combine them.
if (errnoMsg && json.message && json.message !== errnoMsg) {
errnoMsg += ` (${json.message})`;
}
}
let message = `HTTP ${status} ${statusText}`;
if (errnoMsg) {
message += `: ${errnoMsg}`;
}
super(message.trim());
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ServerResponse);
}
this.response = response;
this.data = json;
}
}
var errors = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': ERROR_CODES,
NetworkTimeoutError: NetworkTimeoutError,
ServerResponse: ServerResponse,
UnparseableResponseError: UnparseableResponseError
});
/**
* Enhanced HTTP client for the Kinto protocol.
* @private
*/
class HTTP {
/**
* Constructor.
*
* @param {EventEmitter} events The event handler.
* @param {Object} [options={}} The options object.
* @param {Number} [options.timeout=null] The request timeout in ms, if any (default: `null`).
* @param {String} [options.requestMode="cors"] The HTTP request mode (default: `"cors"`).
*/
constructor(events, options = {}) {
// public properties
/**
* The event emitter instance.
* @type {EventEmitter}
*/
this.events = events;
/**
* The request mode.
* @see https://fetch.spec.whatwg.org/#requestmode
* @type {String}
*/
this.requestMode = options.requestMode || HTTP.defaultOptions.requestMode;
/**
* The request timeout.
* @type {Number}
*/
this.timeout = options.timeout || HTTP.defaultOptions.timeout;
}
/**
* Default HTTP request headers applied to each outgoing request.
*
* @type {Object}
*/
static get DEFAULT_REQUEST_HEADERS() {
return {
Accept: "application/json",
"Content-Type": "application/json",
};
}
/**
* Default options.
*
* @type {Object}
*/
static get defaultOptions() {
return { timeout: null, requestMode: "cors" };
}
/**
* @private
*/
timedFetch(url, options) {
let hasTimedout = false;
return new Promise((resolve, reject) => {
// Detect if a request has timed out.
let _timeoutId;
if (this.timeout) {
_timeoutId = setTimeout(() => {
hasTimedout = true;
if (options && options.headers) {
options = Object.assign(Object.assign({}, options), { headers: obscureAuthorizationHeader(options.headers) });
}
reject(new NetworkTimeoutError(url, options));
}, this.timeout);
}
function proceedWithHandler(fn) {
return (arg) => {
if (!hasTimedout) {
if (_timeoutId) {
clearTimeout(_timeoutId);
}
fn(arg);
}
};
}
fetch(url, options)
.then(proceedWithHandler(resolve))
.catch(proceedWithHandler(reject));
});
}
/**
* @private
*/
async processResponse(response) {
const { status, headers } = response;
const text = await response.text();
// Check if we have a body; if so parse it as JSON.
let json;
if (text.length !== 0) {
try {
json = JSON.parse(text);
}
catch (err) {
throw new UnparseableResponseError(response, text, err);
}
}
if (status >= 400) {
throw new ServerResponse(response, json);
}
return { status, json: json, headers };
}
/**
* @private
*/
async retry(url, retryAfter, request, options) {
await delay(retryAfter);
return this.request(url, request, Object.assign(Object.assign({}, options), { retry: options.retry - 1 }));
}
/**
* Performs an HTTP request to the Kinto server.
*
* Resolves with an objet containing the following HTTP response properties:
* - `{Number} status` The HTTP status code.
* - `{Object} json` The JSON response body.
* - `{Headers} headers` The response headers object; see the ES6 fetch() spec.
*
* @param {String} url The URL.
* @param {Object} [request={}] The request object, passed to
* fetch() as its options object.
* @param {Object} [request.headers] The request headers object (default: {})
* @param {Object} [options={}] Options for making the
* request
* @param {Number} [options.retry] Number of retries (default: 0)
* @return {Promise}
*/
async request(url, request = { headers: {} }, options = { retry: 0 }) {
// Ensure default request headers are always set
request.headers = Object.assign(Object.assign({}, HTTP.DEFAULT_REQUEST_HEADERS), request.headers);
// If a multipart body is provided, remove any custom Content-Type header as
// the fetch() implementation will add the correct one for us.
if (request.body && request.body instanceof FormData) {
if (request.headers instanceof Headers) {
request.headers.delete("Content-Type");
}
else if (!Array.isArray(request.headers)) {
delete request.headers["Content-Type"];
}
}
request.mode = this.requestMode;
const response = await this.timedFetch(url, request);
const { headers } = response;
this._checkForDeprecationHeader(headers);
this._checkForBackoffHeader(headers);
// Check if the server summons the client to retry after a while.
const retryAfter = this._checkForRetryAfterHeader(headers);
// If number of allowed of retries is not exhausted, retry the same request.
if (retryAfter && options.retry > 0) {
return this.retry(url, retryAfter, request, options);
}
else {
return this.processResponse(response);
}
}
_checkForDeprecationHeader(headers) {
const alertHeader = headers.get("Alert");
if (!alertHeader) {
return;
}
let alert;
try {
alert = JSON.parse(alertHeader);
}
catch (err) {
console.warn("Unable to parse Alert header message", alertHeader);
return;
}
console.warn(alert.message, alert.url);
if (this.events) {
this.events.emit("deprecated", alert);
}
}
_checkForBackoffHeader(headers) {
let backoffMs;
const backoffHeader = headers.get("Backoff");
const backoffSeconds = backoffHeader ? parseInt(backoffHeader, 10) : 0;
if (backoffSeconds > 0) {
backoffMs = new Date().getTime() + backoffSeconds * 1000;
}
else {
backoffMs = 0;
}
if (this.events) {
this.events.emit("backoff", backoffMs);
}
}
_checkForRetryAfterHeader(headers) {
const retryAfter = headers.get("Retry-After");
if (!retryAfter) {
return;
}
const delay = parseInt(retryAfter, 10) * 1000;
const tryAgainAfter = new Date().getTime() + delay;
if (this.events) {
this.events.emit("retry-after", tryAgainAfter);
}
return delay;
}
}
/**
* Endpoints templates.
* @type {Object}
*/
const ENDPOINTS = {
root: () => "/",
batch: () => "/batch",
permissions: () => "/permissions",
bucket: (bucket) => "/buckets" + (bucket ? `/${bucket}` : ""),
history: (bucket) => `${ENDPOINTS.bucket(bucket)}/history`,
collection: (bucket, coll) => `${ENDPOINTS.bucket(bucket)}/collections` + (coll ? `/${coll}` : ""),
group: (bucket, group) => `${ENDPOINTS.bucket(bucket)}/groups` + (group ? `/${group}` : ""),
record: (bucket, coll, id) => `${ENDPOINTS.collection(bucket, coll)}/records` + (id ? `/${id}` : ""),
attachment: (bucket, coll, id) => `${ENDPOINTS.record(bucket, coll, id)}/attachment`,
};
const requestDefaults = {
safe: false,
// check if we should set default content type here
headers: {},
patch: false,
};
/**
* @private
*/
function safeHeader(safe, last_modified) {
if (!safe) {
return {};
}
if (last_modified) {
return { "If-Match": `"${last_modified}"` };
}
return { "If-None-Match": "*" };
}
/**
* @private
*/
function createRequest(path, { data, permissions }, options = {}) {
const { headers, safe } = Object.assign(Object.assign({}, requestDefaults), options);
const method = options.method || (data && data.id) ? "PUT" : "POST";
return {
method,
path,
headers: Object.assign(Object.assign({}, headers), safeHeader(safe)),
body: { data, permissions },
};
}
/**
* @private
*/
function updateRequest(path, { data, permissions }, options = {}) {
const { headers, safe, patch } = Object.assign(Object.assign({}, requestDefaults), options);
const { last_modified } = Object.assign(Object.assign({}, data), options);
const hasNoData = data &&
Object.keys(data).filter((k) => k !== "id" && k !== "last_modified")
.length === 0;
if (hasNoData) {
data = undefined;
}
return {
method: patch ? "PATCH" : "PUT",
path,
headers: Object.assign(Object.assign({}, headers), safeHeader(safe, last_modified)),
body: { data, permissions },
};
}
/**
* @private
*/
function jsonPatchPermissionsRequest(path, permissions, opType, options = {}) {
const { headers, safe, last_modified } = Object.assign(Object.assign({}, requestDefaults), options);
const ops = [];
for (const [type, principals] of Object.entries(permissions)) {
if (principals) {
for (const principal of principals) {
ops.push({
op: opType,
path: `/permissions/${type}/${principal}`,
});
}
}
}
return {
method: "PATCH",
path,
headers: Object.assign(Object.assign(Object.assign({}, headers), safeHeader(safe, last_modified)), { "Content-Type": "application/json-patch+json" }),
body: ops,
};
}
/**
* @private
*/
function deleteRequest(path, options = {}) {
const { headers, safe, last_modified } = Object.assign(Object.assign({}, requestDefaults), options);
if (safe && !last_modified) {
throw new Error("Safe concurrency check requires a last_modified value.");
}
return {
method: "DELETE",
path,
headers: Object.assign(Object.assign({}, headers), safeHeader(safe, last_modified)),
};
}
/**
* @private
*/
function addAttachmentRequest(path, dataURI, { data, permissions } = {}, options = {}) {
const { headers, safe, gzipped } = Object.assign(Object.assign({}, requestDefaults), options);
const { last_modified } = Object.assign(Object.assign({}, data), options);
const body = { data, permissions };
const formData = createFormData(dataURI, body, options);
const customPath = `${path}${gzipped !== null ? "?gzipped=" + (gzipped ? "true" : "false") : ""}`;
return {
method: "POST",
path: customPath,
headers: Object.assign(Object.assign({}, headers), safeHeader(safe, last_modified)),
body: formData,
};
}
/**
* Exports batch responses as a result object.
*
* @private
* @param {Array} responses The batch subrequest responses.
* @param {Array} requests The initial issued requests.
* @return {Object}
*/
function aggregate(responses = [], requests = []) {
if (responses.length !== requests.length) {
throw new Error("Responses length should match requests one.");
}
const results = {
errors: [],
published: [],
conflicts: [],
skipped: [],
};
return responses.reduce((acc, response, index) => {
const { status } = response;
const request = requests[index];
if (status >= 200 && status < 400) {
acc.published.push(response.body);
}
else if (status === 404) {
// Extract the id manually from request path while waiting for Kinto/kinto#818
const regex = /(buckets|groups|collections|records)\/([^/]+)$/;
const extracts = request.path.match(regex);
const id = extracts && extracts.length === 3 ? extracts[2] : undefined;
acc.skipped.push({
id,
path: request.path,
error: response.body,
});
}
else if (status === 412) {
acc.conflicts.push({
// XXX: specifying the type is probably superfluous
type: "outgoing",
local: request.body,
remote: (response.body.details && response.body.details.existing) || null,
});
}
else {
acc.errors.push({
path: request.path,
sent: request,
error: response.body,
});
}
return acc;
}, results);
}
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto);
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
function rng() {
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
return getRandomValues(rnds8);
}
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf, offset) {
var i = offset || 0;
var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join('');
}
function v4(options, buf, offset) {
var i = buf && offset || 0;
if (typeof options == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
/**
* Abstract representation of a selected collection.
*
*/
class Collection {
/**
* Constructor.
*
* @param {KintoClient} client The client instance.
* @param {Bucket} bucket The bucket instance.
* @param {String} name The collection name.
* @param {Object} [options={}] The options object.
* @param {Object} [options.headers] The headers object option.
* @param {Boolean} [options.safe] The safe option.
* @param {Number} [options.retry] The retry option.
* @param {Boolean} [options.batch] (Private) Whether this
* Collection is operating as part of a batch.
*/
constructor(client, bucket, name, options = {}) {
/**
* @ignore
*/
this.client = client;
/**
* @ignore
*/
this.bucket = bucket;
/**
* The collection name.
* @type {String}
*/
this.name = name;
this._endpoints = client.endpoints;
/**
* @ignore
*/
this._retry = options.retry || 0;
this._safe = !!options.safe;
// FIXME: This is kind of ugly; shouldn't the bucket be responsible
// for doing the merge?
this._headers = Object.assign(Object.assign({}, this.bucket.headers), options.headers);
}
get execute() {
return this.client.execute.bind(this.client);
}
/**
* Get the value of "headers" for a given request, merging the
* per-request headers with our own "default" headers.
*
* @private
*/
_getHeaders(options) {
return Object.assign(Object.assign({}, this._headers), options.headers);
}
/**
* Get the value of "safe" for a given request, using the
* per-request option if present or falling back to our default
* otherwise.
*
* @private
* @param {Object} options The options for a request.
* @returns {Boolean}
*/
_getSafe(options) {
return Object.assign({ safe: this._safe }, options).safe;
}
/**
* As _getSafe, but for "retry".
*
* @private
*/
_getRetry(options) {
return Object.assign({ retry: this._retry }, options).retry;
}
/**
* Retrieves the total number of records in this collection.
*
* @param {Object} [options={}] The options object.
* @param {Object} [options.headers] The headers object option.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<Number, Error>}
*/
async getTotalRecords(options = {}) {
const path = this._endpoints.record(this.bucket.name, this.name);
const request = {
headers: this._getHeaders(options),
path,
method: "HEAD",
};
const { headers } = await this.client.execute(request, {
raw: true,
retry: this._getRetry(options),
});
return parseInt(headers.get("Total-Records"), 10);
}
/**
* Retrieves the ETag of the records list, for use with the `since` filtering option.
*
* @param {Object} [options={}] The options object.
* @param {Object} [options.headers] The headers object option.
* @param {Number} [options.retry=0] Number of retries to make
* when faced with transient errors.
* @return {Promise<String, Error>}
*/
async getRecordsTimestamp(options = {}) {
const path = this._endpoints.record(this.bucket.name, this.name);
const request = {