-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathcoreapi-0.1.1.js
More file actions
2043 lines (1694 loc) · 154 KB
/
Copy pathcoreapi-0.1.1.js
File metadata and controls
2043 lines (1694 loc) · 154 KB
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.coreapi = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var BasicAuthentication = function () {
function BasicAuthentication() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, BasicAuthentication);
var username = options.username;
var password = options.password;
var hash = window.btoa(username + ':' + password);
this.auth = 'Basic ' + hash;
}
_createClass(BasicAuthentication, [{
key: 'authenticate',
value: function authenticate(options) {
options.headers['Authorization'] = this.auth;
return options;
}
}]);
return BasicAuthentication;
}();
module.exports = {
BasicAuthentication: BasicAuthentication
};
},{}],2:[function(require,module,exports){
'use strict';
var basic = require('./basic');
var session = require('./session');
var token = require('./token');
module.exports = {
BasicAuthentication: basic.BasicAuthentication,
SessionAuthentication: session.SessionAuthentication,
TokenAuthentication: token.TokenAuthentication
};
},{"./basic":1,"./session":3,"./token":4}],3:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var utils = require('../utils');
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
function getCookie(cookieName, cookieString) {
cookieString = cookieString || window.document.cookie;
if (cookieString && cookieString !== '') {
var cookies = cookieString.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, cookieName.length + 1) === cookieName + '=') {
return decodeURIComponent(cookie.substring(cookieName.length + 1));
}
}
}
return null;
}
var SessionAuthentication = function () {
function SessionAuthentication() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, SessionAuthentication);
this.csrfToken = getCookie(options.csrfCookieName, options.cookieString);
this.csrfHeaderName = options.csrfHeaderName;
}
_createClass(SessionAuthentication, [{
key: 'authenticate',
value: function authenticate(options) {
options.credentials = 'same-origin';
if (this.csrfToken && !utils.csrfSafeMethod(options.method)) {
options.headers[this.csrfHeaderName] = this.csrfToken;
}
return options;
}
}]);
return SessionAuthentication;
}();
module.exports = {
SessionAuthentication: SessionAuthentication
};
},{"../utils":15}],4:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var TokenAuthentication = function () {
function TokenAuthentication() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, TokenAuthentication);
this.token = options.token;
this.scheme = options.scheme || 'Bearer';
}
_createClass(TokenAuthentication, [{
key: 'authenticate',
value: function authenticate(options) {
options.headers['Authorization'] = this.scheme + ' ' + this.token;
return options;
}
}]);
return TokenAuthentication;
}();
module.exports = {
TokenAuthentication: TokenAuthentication
};
},{}],5:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var document = require('./document');
var codecs = require('./codecs');
var errors = require('./errors');
var transports = require('./transports');
var utils = require('./utils');
function lookupLink(node, keys) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (node instanceof document.Document) {
node = node.content[key];
} else {
node = node[key];
}
if (node === undefined) {
throw new errors.LinkLookupError('Invalid link lookup: ' + JSON.stringify(keys));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (!(node instanceof document.Link)) {
throw new errors.LinkLookupError('Invalid link lookup: ' + JSON.stringify(keys));
}
return node;
}
var Client = function () {
function Client() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Client);
var transportOptions = {
auth: options.auth || null,
headers: options.headers || {},
requestCallback: options.requestCallback,
responseCallback: options.responseCallback
};
this.decoders = options.decoders || [new codecs.CoreJSONCodec(), new codecs.JSONCodec(), new codecs.TextCodec()];
this.transports = options.transports || [new transports.HTTPTransport(transportOptions)];
}
_createClass(Client, [{
key: 'action',
value: function action(document, keys) {
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var link = lookupLink(document, keys);
var transport = utils.determineTransport(this.transports, link.url);
return transport.action(link, this.decoders, params);
}
}, {
key: 'get',
value: function get(url) {
var link = new document.Link(url, 'get');
var transport = utils.determineTransport(this.transports, url);
return transport.action(link, this.decoders);
}
}]);
return Client;
}();
module.exports = {
Client: Client
};
},{"./codecs":7,"./document":10,"./errors":11,"./transports":14,"./utils":15}],6:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var document = require('../document');
var URL = require('url-parse');
function unescapeKey(key) {
if (key.match(/__(type|meta)$/)) {
return key.substring(1);
}
return key;
}
function getString(obj, key) {
var value = obj[key];
if (typeof value === 'string') {
return value;
}
return '';
}
function getBoolean(obj, key) {
var value = obj[key];
if (typeof value === 'boolean') {
return value;
}
return false;
}
function getObject(obj, key) {
var value = obj[key];
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
return value;
}
return {};
}
function getArray(obj, key) {
var value = obj[key];
if (value instanceof Array) {
return value;
}
return [];
}
function getContent(data, baseUrl) {
var excluded = ['_type', '_meta'];
var content = {};
for (var property in data) {
if (data.hasOwnProperty(property) && !excluded.includes(property)) {
var key = unescapeKey(property);
var value = primitiveToNode(data[property], baseUrl);
content[key] = value;
}
}
return content;
}
function primitiveToNode(data, baseUrl) {
var isObject = data instanceof Object && !(data instanceof Array);
if (isObject && data._type === 'document') {
// Document
var meta = getObject(data, '_meta');
var relativeUrl = getString(meta, 'url');
var url = relativeUrl ? URL(relativeUrl, baseUrl).toString() : '';
var title = getString(meta, 'title');
var description = getString(meta, 'description');
var content = getContent(data, url);
return new document.Document(url, title, description, content);
} else if (isObject && data._type === 'link') {
// Link
var _relativeUrl = getString(data, 'url');
var _url = _relativeUrl ? URL(_relativeUrl, baseUrl).toString() : '';
var method = getString(data, 'action') || 'get';
var _title = getString(data, 'title');
var _description = getString(data, 'description');
var fieldsData = getArray(data, 'fields');
var fields = [];
for (var idx = 0, len = fieldsData.length; idx < len; idx++) {
var value = fieldsData[idx];
var name = getString(value, 'name');
var required = getBoolean(value, 'required');
var location = getString(value, 'location');
var fieldDescription = getString(value, 'fieldDescription');
var field = new document.Field(name, required, location, fieldDescription);
fields.push(field);
}
return new document.Link(_url, method, 'application/json', fields, _title, _description);
} else if (isObject) {
// Object
var _content = {};
for (var key in data) {
if (data.hasOwnProperty(key)) {
_content[key] = primitiveToNode(data[key], baseUrl);
}
}
return _content;
} else if (data instanceof Array) {
// Object
var _content2 = [];
for (var _idx = 0, _len = data.length; _idx < _len; _idx++) {
_content2.push(primitiveToNode(data[_idx], baseUrl));
}
return _content2;
}
// Primitive
return data;
}
var CoreJSONCodec = function () {
function CoreJSONCodec() {
_classCallCheck(this, CoreJSONCodec);
this.mediaType = 'application/coreapi+json';
}
_createClass(CoreJSONCodec, [{
key: 'decode',
value: function decode(text) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var data = text;
if (options.preloaded === undefined || !options.preloaded) {
data = JSON.parse(text);
}
return primitiveToNode(data, options.url);
}
}]);
return CoreJSONCodec;
}();
module.exports = {
CoreJSONCodec: CoreJSONCodec
};
},{"../document":10,"url-parse":19}],7:[function(require,module,exports){
'use strict';
var corejson = require('./corejson');
var json = require('./json');
var text = require('./text');
module.exports = {
CoreJSONCodec: corejson.CoreJSONCodec,
JSONCodec: json.JSONCodec,
TextCodec: text.TextCodec
};
},{"./corejson":6,"./json":8,"./text":9}],8:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var JSONCodec = function () {
function JSONCodec() {
_classCallCheck(this, JSONCodec);
this.mediaType = 'application/json';
}
_createClass(JSONCodec, [{
key: 'decode',
value: function decode(text) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return JSON.parse(text);
}
}]);
return JSONCodec;
}();
module.exports = {
JSONCodec: JSONCodec
};
},{}],9:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var TextCodec = function () {
function TextCodec() {
_classCallCheck(this, TextCodec);
this.mediaType = 'text/*';
}
_createClass(TextCodec, [{
key: 'decode',
value: function decode(text) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return text;
}
}]);
return TextCodec;
}();
module.exports = {
TextCodec: TextCodec
};
},{}],10:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Document = function Document() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var title = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var description = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var content = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
_classCallCheck(this, Document);
this.url = url;
this.title = title;
this.description = description;
this.content = content;
};
var Link = function Link(url, method) {
var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'application/json';
var fields = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var title = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
var description = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '';
_classCallCheck(this, Link);
if (url === undefined) {
throw new Error('url argument is required');
}
if (method === undefined) {
throw new Error('method argument is required');
}
this.url = url;
this.method = method;
this.encoding = encoding;
this.fields = fields;
this.title = title;
this.description = description;
};
var Field = function Field(name) {
var required = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var location = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var description = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
_classCallCheck(this, Field);
if (name === undefined) {
throw new Error('name argument is required');
}
this.name = name;
this.required = required;
this.location = location;
this.description = description;
};
module.exports = {
Document: Document,
Link: Link,
Field: Field
};
},{}],11:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ParameterError = function (_Error) {
_inherits(ParameterError, _Error);
function ParameterError(message) {
_classCallCheck(this, ParameterError);
var _this = _possibleConstructorReturn(this, (ParameterError.__proto__ || Object.getPrototypeOf(ParameterError)).call(this, message));
_this.message = message;
_this.name = 'ParameterError';
return _this;
}
return ParameterError;
}(Error);
var LinkLookupError = function (_Error2) {
_inherits(LinkLookupError, _Error2);
function LinkLookupError(message) {
_classCallCheck(this, LinkLookupError);
var _this2 = _possibleConstructorReturn(this, (LinkLookupError.__proto__ || Object.getPrototypeOf(LinkLookupError)).call(this, message));
_this2.message = message;
_this2.name = 'LinkLookupError';
return _this2;
}
return LinkLookupError;
}(Error);
var ErrorMessage = function (_Error3) {
_inherits(ErrorMessage, _Error3);
function ErrorMessage(message, content) {
_classCallCheck(this, ErrorMessage);
var _this3 = _possibleConstructorReturn(this, (ErrorMessage.__proto__ || Object.getPrototypeOf(ErrorMessage)).call(this, message));
_this3.message = message;
_this3.content = content;
_this3.name = 'ErrorMessage';
return _this3;
}
return ErrorMessage;
}(Error);
module.exports = {
ParameterError: ParameterError,
LinkLookupError: LinkLookupError,
ErrorMessage: ErrorMessage
};
},{}],12:[function(require,module,exports){
'use strict';
var auth = require('./auth');
var client = require('./client');
var codecs = require('./codecs');
var document = require('./document');
var errors = require('./errors');
var transports = require('./transports');
var utils = require('./utils');
var coreapi = {
Client: client.Client,
Document: document.Document,
Link: document.Link,
auth: auth,
codecs: codecs,
errors: errors,
transports: transports,
utils: utils
};
module.exports = coreapi;
},{"./auth":2,"./client":5,"./codecs":7,"./document":10,"./errors":11,"./transports":14,"./utils":15}],13:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fetch = require('isomorphic-fetch');
var errors = require('../errors');
var utils = require('../utils');
var URL = require('url-parse');
var urlTemplate = require('url-template');
var parseResponse = function parseResponse(response, decoders, responseCallback) {
return response.text().then(function (text) {
if (responseCallback) {
responseCallback(response, text);
}
var contentType = response.headers.get('Content-Type');
var decoder = utils.negotiateDecoder(decoders, contentType);
var options = { url: response.url };
return decoder.decode(text, options);
});
};
var HTTPTransport = function () {
function HTTPTransport() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, HTTPTransport);
this.schemes = ['http', 'https'];
this.auth = options.auth || null;
this.headers = options.headers || {};
this.fetch = options.fetch || fetch;
this.FormData = options.FormData || window.FormData;
this.requestCallback = options.requestCallback;
this.responseCallback = options.responseCallback;
}
_createClass(HTTPTransport, [{
key: 'buildRequest',
value: function buildRequest(link, decoders) {
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var fields = link.fields;
var method = link.method.toUpperCase();
var queryParams = {};
var pathParams = {};
var formParams = {};
var fieldNames = [];
var hasBody = false;
for (var idx = 0, len = fields.length; idx < len; idx++) {
var field = fields[idx];
// Ensure any required fields are included
if (!params.hasOwnProperty(field.name)) {
if (field.required) {
throw new errors.ParameterError('Missing required field: "' + field.name + '"');
} else {
continue;
}
}
fieldNames.push(field.name);
if (field.location === 'query') {
queryParams[field.name] = params[field.name];
} else if (field.location === 'path') {
pathParams[field.name] = params[field.name];
} else if (field.location === 'form') {
formParams[field.name] = params[field.name];
hasBody = true;
} else if (field.location === 'body') {
formParams = params[field.name];
hasBody = true;
}
}
// Check for any parameters that did not have a matching field
for (var property in params) {
if (params.hasOwnProperty(property) && !fieldNames.includes(property)) {
throw new errors.ParameterError('Unknown parameter: "' + property + '"');
}
}
var requestOptions = { method: method, headers: {} };
Object.assign(requestOptions.headers, this.headers);
if (hasBody) {
if (link.encoding === 'application/json') {
requestOptions.body = JSON.stringify(formParams);
requestOptions.headers['Content-Type'] = 'application/json';
} else if (link.encoding === 'multipart/form-data') {
var form = new this.FormData();
for (var paramKey in formParams) {
form.append(paramKey, formParams[paramKey]);
}
requestOptions.body = form;
} else if (link.encoding === 'application/x-www-form-urlencoded') {
var formBody = [];
for (var _paramKey in formParams) {
var encodedKey = encodeURIComponent(_paramKey);
var encodedValue = encodeURIComponent(formParams[_paramKey]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
requestOptions.body = formBody;
requestOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
}
if (this.auth) {
requestOptions = this.auth.authenticate(requestOptions);
}
var parsedUrl = urlTemplate.parse(link.url);
parsedUrl = parsedUrl.expand(pathParams);
parsedUrl = new URL(parsedUrl);
parsedUrl.set('query', queryParams);
return {
url: parsedUrl.toString(),
options: requestOptions
};
}
}, {
key: 'action',
value: function action(link, decoders) {
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var responseCallback = this.responseCallback;
var request = this.buildRequest(link, decoders, params);
if (this.requestCallback) {
this.requestCallback(request);
}
return this.fetch(request.url, request.options).then(function (response) {
if (response.status === 204) {
return;
}
return parseResponse(response, decoders, responseCallback).then(function (data) {
if (response.ok) {
return data;
} else {
var title = response.status + ' ' + response.statusText;
var error = new errors.ErrorMessage(title, data);
return Promise.reject(error);
}
});
});
}
}]);
return HTTPTransport;
}();
module.exports = {
HTTPTransport: HTTPTransport
};
},{"../errors":11,"../utils":15,"isomorphic-fetch":16,"url-parse":19,"url-template":21}],14:[function(require,module,exports){
'use strict';
var http = require('./http');
module.exports = {
HTTPTransport: http.HTTPTransport
};
},{"./http":13}],15:[function(require,module,exports){
'use strict';
var URL = require('url-parse');
var determineTransport = function determineTransport(transports, url) {
var parsedUrl = new URL(url);
var scheme = parsedUrl.protocol.replace(':', '');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = transports[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var transport = _step.value;
if (transport.schemes.includes(scheme)) {
return transport;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
throw Error('Unsupported scheme in URL: ' + url);
};
var negotiateDecoder = function negotiateDecoder(decoders, contentType) {
if (contentType === undefined || contentType === null) {
return decoders[0];
}
var fullType = contentType.toLowerCase().split(';')[0].trim();
var mainType = fullType.split('/')[0] + '/*';
var wildcardType = '*/*';
var acceptableTypes = [fullType, mainType, wildcardType];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = decoders[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var decoder = _step2.value;
if (acceptableTypes.includes(decoder.mediaType)) {
return decoder;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
throw Error('Unsupported media in Content-Type header: ' + contentType);
};
var csrfSafeMethod = function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)
);
};
module.exports = {
determineTransport: determineTransport,
negotiateDecoder: negotiateDecoder,
csrfSafeMethod: csrfSafeMethod
};
},{"url-parse":19}],16:[function(require,module,exports){
// the whatwg-fetch polyfill installs the fetch() function
// on the global object (window or self)
//
// Return that as the export for use in Webpack, Browserify etc.
require('whatwg-fetch');
module.exports = self.fetch.bind(self);
},{"whatwg-fetch":22}],17:[function(require,module,exports){
'use strict';
var has = Object.prototype.hasOwnProperty;
/**
* Simple query string parser.
*
* @param {String} query The query string that needs to be parsed.
* @returns {Object}
* @api public
*/
function querystring(query) {
var parser = /([^=?&]+)=?([^&]*)/g
, result = {}
, part;
//
// Little nifty parsing hack, leverage the fact that RegExp.exec increments
// the lastIndex property so we can continue executing this loop until we've
// parsed all results.
//
for (;
part = parser.exec(query);
result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
);
return result;
}
/**
* Transform a query string to an object.
*
* @param {Object} obj Object that should be transformed.
* @param {String} prefix Optional prefix.
* @returns {String}
* @api public
*/
function querystringify(obj, prefix) {
prefix = prefix || '';
var pairs = [];
//
// Optionally prefix with a '?' if needed
//
if ('string' !== typeof prefix) prefix = '?';
for (var key in obj) {
if (has.call(obj, key)) {
pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
}
}
return pairs.length ? prefix + pairs.join('&') : '';
}
//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;
},{}],18:[function(require,module,exports){
'use strict';
/**
* Check if we're required to add a port number.
*
* @see https://url.spec.whatwg.org/#default-port
* @param {Number|String} port Port number we need to check
* @param {String} protocol Protocol we need to check against.
* @returns {Boolean} Is it a default port for the given protocol
* @api private
*/
module.exports = function required(port, protocol) {
protocol = protocol.split(':')[0];
port = +port;
if (!port) return false;
switch (protocol) {
case 'http':
case 'ws':
return port !== 80;
case 'https':
case 'wss':
return port !== 443;
case 'ftp':
return port !== 21;
case 'gopher':
return port !== 70;
case 'file':
return false;
}
return port !== 0;
};
},{}],19:[function(require,module,exports){
'use strict';
var required = require('requires-port')
, lolcation = require('./lolcation')
, qs = require('querystringify')
, protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i;
/**
* These are the parse rules for the URL parser, it informs the parser
* about:
*
* 0. The char it Needs to parse, if it's a string it should be done using
* indexOf, RegExp using exec and NaN means set as current value.
* 1. The property we should set when parsing this value.
* 2. Indication if it's backwards or forward parsing, when set as number it's
* the value of extra chars that should be split off.
* 3. Inherit from location if non existing in the parser.
* 4. `toLowerCase` the resulting value.
*/
var rules = [
['#', 'hash'], // Extract from the back.
['?', 'query'], // Extract from the back.
['/', 'pathname'], // Extract from the back.
['@', 'auth', 1], // Extract from the front.