clerk 0.8.3 → 0.8.4

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/dist/clerk.js DELETED
@@ -1,2708 +0,0 @@
1
- (function webpackUniversalModuleDefinition(root, factory) {
2
- if(typeof exports === 'object' && typeof module === 'object')
3
- module.exports = factory();
4
- else if(typeof define === 'function' && define.amd)
5
- define(factory);
6
- else if(typeof exports === 'object')
7
- exports["clerk"] = factory();
8
- else
9
- root["clerk"] = factory();
10
- })(this, function() {
11
- return /******/ (function(modules) { // webpackBootstrap
12
- /******/ // The module cache
13
- /******/ var installedModules = {};
14
- /******/
15
- /******/ // The require function
16
- /******/ function __webpack_require__(moduleId) {
17
- /******/
18
- /******/ // Check if module is in cache
19
- /******/ if(installedModules[moduleId])
20
- /******/ return installedModules[moduleId].exports;
21
- /******/
22
- /******/ // Create a new module (and put it into the cache)
23
- /******/ var module = installedModules[moduleId] = {
24
- /******/ exports: {},
25
- /******/ id: moduleId,
26
- /******/ loaded: false
27
- /******/ };
28
- /******/
29
- /******/ // Execute the module function
30
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31
- /******/
32
- /******/ // Flag the module as loaded
33
- /******/ module.loaded = true;
34
- /******/
35
- /******/ // Return the exports of the module
36
- /******/ return module.exports;
37
- /******/ }
38
- /******/
39
- /******/
40
- /******/ // expose the modules object (__webpack_modules__)
41
- /******/ __webpack_require__.m = modules;
42
- /******/
43
- /******/ // expose the module cache
44
- /******/ __webpack_require__.c = installedModules;
45
- /******/
46
- /******/ // __webpack_public_path__
47
- /******/ __webpack_require__.p = "";
48
- /******/
49
- /******/ // Load entry module and return exports
50
- /******/ return __webpack_require__(0);
51
- /******/ })
52
- /************************************************************************/
53
- /******/ ([
54
- /* 0 */
55
- /***/ function(module, exports, __webpack_require__) {
56
-
57
- "use strict";
58
-
59
- /*!
60
-
61
- clerk - CouchDB client for node and the browser.
62
- Copyright 2012-2015 Michael Phan-Ba
63
-
64
- Licensed under the Apache License, Version 2.0 (the "License");
65
- you may not use this file except in compliance with the License.
66
- You may obtain a copy of the License at
67
-
68
- http://www.apache.org/licenses/LICENSE-2.0
69
-
70
- Unless required by applicable law or agreed to in writing, software
71
- distributed under the License is distributed on an "AS IS" BASIS,
72
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
73
- See the License for the specific language governing permissions and
74
- limitations under the License.
75
-
76
- */
77
-
78
- // Module dependencies.
79
- var request = __webpack_require__(1);
80
-
81
- /**
82
- * Copy properties from sources to target.
83
- *
84
- * @param {Object} target The target object.
85
- * @param {...Object} sources The source object.
86
- * @return {Object} The target object.
87
- * @private
88
- */
89
-
90
- var extend = function (target /* ...sources */) {
91
- var source, key, i = 1;
92
- while (source = arguments[i++]) {
93
- for (key in source) target[key] = source[key];
94
- }
95
- return target;
96
- };
97
-
98
- /**
99
- * Stringify value.
100
- *
101
- * @param {Object} that That value to stringify.
102
- * @return {String} The stringifyed value.
103
- * @private
104
- */
105
-
106
- var asString = function (that) {
107
- return Object.prototype.toString.call(that);
108
- };
109
-
110
- /**
111
- * Check if value is a string.
112
- *
113
- * @param {Object} that That value to check.
114
- * @return {Boolean} `true` if string, `false` otherwise.
115
- * @private
116
- */
117
-
118
- var isString = function (that) {
119
- return asString(that) == "[object String]";
120
- };
121
-
122
- /**
123
- * Check if value is an object.
124
- *
125
- * @param {Object} that That value to check.
126
- * @return {Boolean} `true` if object, `false` otherwise.
127
- * @private
128
- */
129
-
130
- var isObject = function (that) {
131
- return asString(that) == "[object Object]";
132
- };
133
-
134
- /**
135
- * Check if value is an array.
136
- *
137
- * @param {Object} that That value to check.
138
- * @return {Boolean} `true` if array, `false` otherwise.
139
- * @private
140
- */
141
-
142
- var isArray = function (that) {
143
- return asString(that) == "[object Array]";
144
- };
145
-
146
- /**
147
- * Check if value is a function.
148
- *
149
- * @param {Object} that That value to check.
150
- * @return {Boolean} `true` if function, `false` otherwise.
151
- * @private
152
- */
153
-
154
- var isFunction = function (that) {
155
- return asString(that) == "[object Function]";
156
- };
157
-
158
- /**
159
- * Clerk library entry point.
160
- *
161
- * @param {String} uri CouchDB server URI.
162
- * @return {Client|DB} If a URI path is given, returns a `DB`, otherwise
163
- * returns a `Client`.
164
- * @see {@link http://docs.couchdb.org|CouchDB Documentation}
165
- * @see {@link http://guide.couchdb.org/|CouchDB Guide}
166
- * @see {@link http://wiki.apache.org/couchdb/|CouchDB Wiki}
167
- */
168
-
169
- function clerk (uri) {
170
- return clerk.make(uri);
171
- };
172
-
173
- /**
174
- * Promise implementation.
175
- * @type {Promise}
176
- */
177
-
178
- clerk.Promise = typeof Promise !== "undefined" && Promise;
179
-
180
- /**
181
- * Library version.
182
- * @type {String}
183
- */
184
-
185
- clerk.version = "0.8.2";
186
-
187
- /**
188
- * Default host.
189
- * @type {String}
190
- */
191
-
192
- clerk.defaultHost = "http://127.0.0.1:5984";
193
-
194
- /**
195
- * Create single CouchDB client.
196
- *
197
- * @param {String} uri Fully qualified URI.
198
- * @return {Client|DB} If `uri` has a path, the last segment of the
199
- * path is used as the database name and a `DB` instance is
200
- * returned. Otherwise, a `Client` instance is returned.
201
- */
202
-
203
- clerk.make = function (uri) {
204
- if (!uri) return new Client(this.defaultHost);
205
-
206
- uri = clerk._parseURI(uri);
207
-
208
- var db = /\/*([^\/]+)\/*$/.exec(uri.path);
209
- if (db) {
210
- uri.path = uri.path.substr(0, db.index);
211
- db = db[1] && decodeURIComponent(db[1]);
212
- }
213
-
214
- // weird way of doing it, but it's more efficient...
215
- if (uri.auth) uri.auth = 'Basic ' + clerk.btoa(uri.auth);
216
-
217
- var client = new clerk.Client(uri.base + uri.path, uri.auth);
218
- return db ? client.db(db) : client;
219
- };
220
-
221
- /**
222
- * Base64-encode a string.
223
- *
224
- * @param {String} str
225
- * @return {String}
226
- */
227
-
228
- clerk.btoa = typeof Buffer != "undefined" ? function (str) {
229
- return new Buffer(str).toString("base64");
230
- } : function (str) {
231
- return btoa(str);
232
- };
233
-
234
- /**
235
- * Parse URI.
236
- *
237
- * The URI is normalized by removing extra `//` in the path.
238
- *
239
- * @param {String} uri Fully qualified URI.
240
- * @return {String} The normalized URI.
241
- * @private
242
- */
243
-
244
- clerk._parseURI = function (uri) {
245
- var match;
246
-
247
- if (uri) {
248
- if (match = /^(https?:\/\/)(?:([^\/@]+)@)?([^\/]+)(.*)\/*$/.exec(uri)) {
249
- return {
250
- base: match[1] + match[3].replace(/\/+/g, "\/"),
251
- path: match[4],
252
- auth: match[2] && decodeURIComponent(match[2])
253
- };
254
- }
255
- }
256
-
257
- return { base: uri || "", path: "" };
258
- };
259
-
260
- /**
261
- * Base prototype for `Client` and `DB`.
262
- * Encapsulates HTTP methods, JSON handling, and response coersion.
263
- *
264
- * @constructor
265
- * @memberof clerk
266
- */
267
-
268
- function Base () {};
269
-
270
- /**
271
- * Service request and parse JSON response.
272
- *
273
- * @param {String} [method=GET] HTTP method.
274
- * @param {String} [path=this.uri] HTTP URI.
275
- * @param {Object} [query] HTTP query options.
276
- * @param {Object} [body] HTTP body.
277
- * @param {Object} [headers] HTTP headers.
278
- * @param {handler} [callback] Callback function.
279
- * @return {Promise}
280
- */
281
-
282
- Base.prototype.request = function (/* [method], [path], [query], [body], [headers], [callback] */) {
283
- var args = [].slice.call(arguments);
284
- var callback = isFunction (args[args.length - 1]) && args.pop();
285
-
286
- return this._request({
287
- method: args[0],
288
- path: args[1],
289
- query: args[2],
290
- data: args[3],
291
- headers: args[4],
292
- fn: callback
293
- });
294
- };
295
-
296
- /**
297
- * Internal service request and parse JSON response handler.
298
- *
299
- * @param {String} options
300
- * @param {String} method HTTP method.
301
- * @param {String} path HTTP URI.
302
- * @param {Object} query HTTP query options.
303
- * @param {Object} data HTTP body data.
304
- * @param {Object} headers HTTP headers.
305
- * @param {handler} [callback] Callback function.
306
- * @private
307
- */
308
-
309
- Base.prototype._request = function (options) {
310
- var self = this;
311
-
312
- if (options.method == null) options.method = "GET";
313
- if (options.headers == null) options.headers = {};
314
- if (options.auth == null) options.auth = this.auth;
315
-
316
- options.path = options.path ? "/" + options.path : "";
317
-
318
- // set default headers
319
- if (options.headers["Content-Type"] == null) {
320
- options.headers["Content-Type"] = "application/json";
321
- }
322
- if (options.headers["Accept"] == null) {
323
- options.headers["Accept"] = "application/json";
324
- }
325
- if (this.auth && options.headers["Authorization"] == null) {
326
- options.headers["Authorization"] = this.auth;
327
- }
328
-
329
- options.uri = this.uri + options.path;
330
- options.body = options.data && JSON.stringify(options.data,
331
- /^\/_design/.test(options.path) && this._replacer
332
- ) || "";
333
-
334
- // create promise if no callback given
335
- var promise, req;
336
- if (!options.fn && clerk.Promise) {
337
- promise = new clerk.Promise(function (resolve, reject) {
338
- options.fn = function (err, data, status, headers, res) {
339
- if (err) {
340
- err.body = data;
341
- err.status = status;
342
- err.headers = headers;
343
- err.res = res;
344
- reject(err);
345
- } else {
346
- if (isObject(data) && Object.defineProperties) {
347
- Object.defineProperties(data, {
348
- _status: { value: status },
349
- _headers: { value: headers },
350
- _response: { value: res },
351
- });
352
- }
353
- resolve(data);
354
- };
355
- };
356
- });
357
- req = send();
358
- promise.request = req;
359
- promise.abort = function () {
360
- req.abort();
361
- options.fn(new Error("abort"));
362
- return promise;
363
- };
364
- return promise;
365
- }
366
-
367
- send();
368
-
369
- function send () {
370
- // apply response transforms
371
- var g = options._;
372
- var fn = options.fn;
373
- if (fn) {
374
- options.fn = g ? function () {
375
- fn.apply(self, g.apply(self, arguments) || arguments);
376
- } : fn;
377
- }
378
- return self._do(options);
379
- }
380
- };
381
-
382
- /**
383
- * Provider for servicing requests and parsing JSON responses.
384
- *
385
- * @param {String} options
386
- * @param {String} method HTTP method.
387
- * @param {String} uri HTTP URI.
388
- * @param {Object} query HTTP query options.
389
- * @param {Object} body HTTP body.
390
- * @param {Object} headers HTTP headers.
391
- * @param {Object} auth HTTP authentication.
392
- * @param {handler} [callback] Callback function.
393
- * @private
394
- */
395
-
396
- Base.prototype._do = function (options) {
397
- var self = this;
398
- var key, value;
399
- var fn = options.fn;
400
-
401
- // create request
402
- var req = request(options.method, options.uri);
403
-
404
- // query string
405
- if (options.query) {
406
- // ensure query Array values are JSON encoded
407
- for (key in options.query) {
408
- if (isObject(value = options.query[key])) {
409
- options.query[key] = JSON.stringify(value);
410
- }
411
- }
412
- // set query on request
413
- req.query(options.query);
414
- }
415
-
416
- // set headers
417
- if (options.headers) {
418
- req.set(options.headers);
419
- // if authenticating
420
- if (req.withCredentials && options.headers["Authorization"] != null) {
421
- req.withCredentials();
422
- }
423
- }
424
-
425
- // send body
426
- if (options.body) req.send(options.body);
427
-
428
- // send request
429
- req.end(function (err, res) {
430
- var data;
431
-
432
- if (!err) {
433
- if (!(data = res.body)) { data = res.text; }
434
- else if (data.error) err = self._error(data);
435
- else data = self._response(data);
436
- }
437
-
438
- if (err && fn) {
439
- var response = res || {};
440
- return fn(err, data, response.status, response.header, res);
441
- }
442
-
443
- res.data = data;
444
- if (fn) fn(err || null, data, res.status, res.header, res);
445
- });
446
-
447
- return req;
448
- };
449
-
450
- /**
451
- * Coerce response to normalize access to `_id` and `_rev`.
452
- *
453
- * @param {Object} json The response JSON.
454
- * @return The coerced JSON.
455
- * @private
456
- */
457
-
458
- Base.prototype._response = function (json) {
459
- var data = json.rows || json.results || json.uuids || isArray(json) && json;
460
- var meta = this._meta;
461
- var i = 0, len, item;
462
-
463
- if (data) {
464
- extend(data, json).json = json;
465
- for (len = data.length; i < len; i++) {
466
- item = data[i] = meta(data[i]);
467
- if (item.doc) item.doc = meta(item.doc);
468
- }
469
- } else {
470
- data = meta(json);
471
- }
472
-
473
- return data;
474
- };
475
-
476
- /**
477
- * Make an error out of the response.
478
- *
479
- * @param {Object} json The response JSON.
480
- * @return An `Error` object.
481
- * @private
482
- */
483
-
484
- Base.prototype._error = function (json) {
485
- var err = new Error(json.reason);
486
- err.code = json.error;
487
- return extend(err, json);
488
- };
489
-
490
- /**
491
- * JSON stringify functions. Used for encoding view documents to JSON.
492
- *
493
- * @param {String} key The key to stringify.
494
- * @param {Object} val The value to stringify.
495
- * @return {Object} The stringified function value or the value.
496
- * @private
497
- */
498
-
499
- Base.prototype._replacer = function (key, val) {
500
- return isFunction (val) ? val.toString() : val;
501
- };
502
-
503
- /**
504
- * Coerce documents with prototypical `_id` and `_rev`
505
- * values.
506
- *
507
- * @param {Object} doc The document to coerce.
508
- * @return {Object} The coerced document.
509
- * @private
510
- */
511
-
512
- Base.prototype._meta = function (doc) {
513
- var hasId = !doc._id && doc.id;
514
- var hasRev = !doc._rev && doc.rev;
515
- var proto;
516
-
517
- if (hasId || hasRev) {
518
- proto = function (){};
519
- doc = extend(new proto(), doc);
520
- proto = proto.prototype;
521
- if (hasId) proto._id = doc.id;
522
- if (hasRev) proto._rev = doc.rev;
523
- }
524
-
525
- return doc;
526
- };
527
-
528
- /**
529
- * Parse arguments.
530
- *
531
- * @param {Array} args The arguments.
532
- * @param {Integer} [start] The index from which to start reading arguments.
533
- * @param {Boolean} [withBody] Set to `true` if the request body is given as a
534
- * parameter before HTTP query options.
535
- * @param {Boolean} [notDoc] The request body is not a document.
536
- * @return {Promise} A Promise, if no callback is provided, otherwise `null`.
537
- * @private
538
- */
539
-
540
- Base.prototype._ = function (args, start, withBody, notDoc) {
541
- var self = this, doc, id, rev;
542
-
543
- function request(method, path, options) {
544
- if (!options) options = {};
545
- return self._request({
546
- method: method,
547
- path: path || request.p,
548
- query: options.q || request.q,
549
- data: options.b || request.b,
550
- headers: options.h || request.h,
551
- fn: options.f || request.f,
552
- _: options._ || request._
553
- });
554
- }
555
-
556
- // [id], [doc], [query], [header], [callback]
557
- args = [].slice.call(args, start || 0);
558
-
559
- request.f = isFunction(args[args.length - 1]) && args.pop();
560
- request.p = isString(args[0]) && encodeURI(args.shift());
561
- request.q = args[withBody ? 1 : 0] || {};
562
- request.h = args[withBody ? 2 : 1] || {};
563
-
564
- if (withBody) {
565
- doc = request.b = args[0];
566
- if (!notDoc) {
567
- if (id = request.p || doc._id || doc.id) request.p = id;
568
- if (rev = request.q.rev || doc._rev || doc.rev) request.q.rev = rev;
569
- }
570
- }
571
-
572
- return request;
573
- };
574
-
575
- /**
576
- * Clerk CouchDB client.
577
- *
578
- * @param {String} uri Fully qualified URI.
579
- * @param {String} [auth] Authentication header value.
580
- * @constructor
581
- * @memberof clerk
582
- * @see {@link http://wiki.apache.org/couchdb/Complete_HTTP_API_Reference|CouchDB Wiki}
583
- */
584
-
585
- function Client (uri, auth) {
586
- this.uri = uri;
587
- this._db = {};
588
- this.auth = auth;
589
- };
590
-
591
- Client.prototype = new Base();
592
-
593
- /**
594
- * Select database to manipulate.
595
- *
596
- * @param {String} name DB name.
597
- * @return {DB} DB object.
598
- */
599
-
600
- Client.prototype.db = function (name) {
601
- var db = this._db;
602
- return db[name] || (db[name] = new DB(this, name, this.auth));
603
- };
604
-
605
- /**
606
- * List all databases.
607
- *
608
- * @param {Object} [query] HTTP query options.
609
- * @param {Object} [headers] HTTP headers.
610
- * @param {handler} [callback] Callback function.
611
- * @return {Promise} A Promise, if no callback is provided,
612
- * otherwise `null`.
613
- * @see {@link http://wiki.apache.org/couchdb/HttpGetAllDbs|CouchDB Wiki}
614
- */
615
-
616
- Client.prototype.dbs = function (/* [query], [headers], [callback] */) {
617
- return this._(arguments)("GET", "_all_dbs");
618
- };
619
-
620
- /**
621
- * Get UUIDs.
622
- *
623
- * @param {Integer} [count=1] Number of UUIDs to get.
624
- * @param {Object} [query] HTTP query options.
625
- * @param {Object} [headers] HTTP headers.
626
- * @param {handler} [callback] Callback function.
627
- * @return {Promise} A Promise, if no callback is provided,
628
- * otherwise `null`.
629
- * @see {@link http://wiki.apache.org/couchdb/HttpGetUuids|CouchDB Wiki}
630
- */
631
-
632
- Client.prototype.uuids = function (count /* [query], [headers], [callback] */) {
633
- var request = this._(arguments, +count == count ? 1 : 0);
634
- if (count > 1) request.q.count = count;
635
- return request("GET", "_uuids");
636
- };
637
-
638
- /**
639
- * Get server information.
640
- *
641
- * @param {Object} [query] HTTP query options.
642
- * @param {Object} [headers] HTTP headers.
643
- * @param {handler} [callback] Callback function.
644
- * @return {Promise} A Promise, if no callback is provided,
645
- * otherwise `null`.
646
- * @see {@link http://wiki.apache.org/couchdb/HttpGetRoot|CouchDB Wiki}
647
- */
648
-
649
- Client.prototype.info = function (/* [query], [headers], [callback] */) {
650
- return this._(arguments)("GET");
651
- };
652
-
653
- /**
654
- * Get server stats.
655
- *
656
- * @param {Object} [query] HTTP query options.
657
- * @param {Object} [headers] HTTP headers.
658
- * @param {handler} [callback] Callback function.
659
- * @return {Promise} A Promise, if no callback is provided,
660
- * otherwise `null`.
661
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
662
- */
663
-
664
- Client.prototype.stats = function (/* [query], [headers], [callback] */) {
665
- return this._(arguments)("GET", "_stats");
666
- };
667
-
668
- /**
669
- * Get tail of the server log file.
670
- *
671
- * @param {Object} [query] Query parameters.
672
- * @param {Integer} [query.bytes] Number of bytes to read.
673
- * @param {Integer} [query.offset] Number of bytes from the end of
674
- * log file to start reading.
675
- * @param {Object} [headers] HTTP headers.
676
- * @param {handler} [callback] Callback function.
677
- * @return {Promise} A Promise, if no callback is provided,
678
- * otherwise `null`.
679
- * @see {@link http://wiki.apache.org/couchdb/HttpGetLog|CouchDB Wiki}
680
- */
681
-
682
- Client.prototype.log = function (/* [query], [headers], [callback] */) {
683
- return this._(arguments)("GET", "_log");
684
- };
685
-
686
- /**
687
- * List running tasks.
688
- *
689
- * @param {Object} [query] HTTP query options.
690
- * @param {Object} [headers] HTTP headers.
691
- * @param {handler} [callback] Callback function.
692
- * @return {Promise} A Promise, if no callback is provided,
693
- * otherwise `null`.
694
- * @see {@link http://wiki.apache.org/couchdb/HttpGetActiveTasks|CouchDB Wiki}
695
- */
696
-
697
- Client.prototype.tasks = function (/* [query], [headers], [callback] */) {
698
- return this._(arguments)("GET", "_active_tasks");
699
- };
700
-
701
- /**
702
- * Get or set configuration values.
703
- *
704
- * @param {String} [key] Configuration section or key.
705
- * @param {String} [value] Configuration value.
706
- * @param {Object} [query] HTTP query options.
707
- * @param {Object} [headers] HTTP headers.
708
- * @param {handler} [callback] Callback function.
709
- * @return {Promise} A Promise, if no callback is provided,
710
- * otherwise `null`.
711
- */
712
-
713
- Client.prototype.config = function (/* [key], [value], [query], [headers], [callback] */) {
714
- var args = [].slice.call(arguments);
715
- var key = isString(args[0]) && args.shift() || "";
716
- var value = isString(args[0]) && args.shift();
717
- var method = isString(value) ? "PUT" : "GET";
718
- return this._(args)(method, "_config/" + key, { b: value });
719
- };
720
-
721
- /**
722
- * Replicate databases.
723
- *
724
- * @param {Object} options Options.
725
- * @param {String} options.source Source database URL or local name.
726
- * @param {String} options.target Target database URL or local name.
727
- * @param {Boolean} [options.cancel] Set to `true` to cancel replication.
728
- * @param {Boolean} [options.continuous] Set to `true` for continuous
729
- * replication.
730
- * @param {Boolean} [options.create_target] Set to `true` to create the
731
- * target database.
732
- * @param {String} [options.filter] Filter name for filtered replication.
733
- * Example: "mydesign/myfilter".
734
- * @param {Object} [options.query] Query parameters for filter.
735
- * @param {String[]} [options.doc_ids] Document IDs to replicate.
736
- * @param {String} [options.proxy] Proxy through which to replicate.
737
- * @param {Object} [query] HTTP query options.
738
- * @param {Object} [headers] HTTP headers.
739
- * @param {handler} [callback] Callback function.
740
- * @return {Promise} A Promise, if no callback is provided,
741
- * otherwise `null`.
742
- * @see {@link http://wiki.apache.org/couchdb/Replication|CouchDB Wiki}
743
- */
744
-
745
- Client.prototype.replicate = function (options /* [query], [headers], [callback] */) {
746
- return this._(arguments, 1)("POST", "_replicate", { b: options });
747
- };
748
-
749
- /**
750
- * Methods for CouchDB database.
751
- *
752
- * @param {Client} client Clerk client.
753
- * @param {String} name DB name.
754
- * @param {String} [auth] Authentication header value.
755
- * @constructor
756
- * @memberof clerk
757
- * @return This object for chaining.
758
- */
759
-
760
- function DB (client, name, auth) {
761
- this.client = client;
762
- this.name = name;
763
- this.uri = client.uri + "/" + encodeURIComponent(name);
764
- this.auth = auth;
765
- };
766
-
767
- DB.prototype = new Base();
768
-
769
- /**
770
- * Create database.
771
- *
772
- * @param {Object} [query] HTTP query options.
773
- * @param {Object} [headers] HTTP headers.
774
- * @param {handler} [callback] Callback function.
775
- * @return {Promise} A Promise, if no callback is provided,
776
- * otherwise `null`.
777
- */
778
-
779
- DB.prototype.create = function (/* [query], [headers], [callback] */) {
780
- return this._(arguments)("PUT");
781
- };
782
-
783
- /**
784
- * Destroy database.
785
- *
786
- * @param {Object} [query] HTTP query options.
787
- * @param {Object} [headers] HTTP headers.
788
- * @param {handler} [callback] Callback function.
789
- * @return {Promise} A Promise, if no callback is provided,
790
- * otherwise `null`.
791
- */
792
-
793
- DB.prototype.destroy = function (/* [query], [headers], [callback] */) {
794
- return this._(arguments)("DELETE");
795
- };
796
-
797
- /**
798
- * Get database info.
799
- *
800
- * @param {Object} [query] HTTP query options.
801
- * @param {Object} [headers] HTTP headers.
802
- * @param {handler} [callback] Callback function.
803
- * @return {Promise} A Promise, if no callback is provided,
804
- * otherwise `null`.
805
- */
806
-
807
- DB.prototype.info = function (/* [query], [headers], callback */) {
808
- return this._(arguments)("GET");
809
- };
810
-
811
- /**
812
- * Check if database exists.
813
- *
814
- * @param {Object} [query] HTTP query options.
815
- * @param {Object} [headers] HTTP headers.
816
- * @param {handler} [callback] Callback function.
817
- * @return {Promise} A Promise, if no callback is provided,
818
- * otherwise `null`.
819
- */
820
-
821
- DB.prototype.exists = function (/* [query], [headers], callback */) {
822
- var request = this._(arguments);
823
- request._ = function (err, body, status, headers, req) {
824
- if (status === 404) err = null;
825
- return [err, status === 200, status, headers, req];
826
- };
827
- return request("HEAD");
828
- };
829
-
830
- /**
831
- * Fetch document.
832
- *
833
- * Set `rev` in `query`.
834
- *
835
- * @param {String} id Document ID.
836
- * @param {Object} [query] HTTP query options.
837
- * @param {Boolean} [query.revs] Fetch list of revisions.
838
- * @param {Boolean} [query.revs_info] Fetch detailed revision information.
839
- * @param {Object} [headers] HTTP headers.
840
- * @param {handler} [callback] Callback function.
841
- * @return {Promise} A Promise, if no callback is provided,
842
- * otherwise `null`.
843
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#GET|CouchDB Wiki}
844
- */
845
-
846
- DB.prototype.get = function (/* [id], [query], [headers], [callback] */) {
847
- return this._(arguments)("GET");
848
- };
849
-
850
- /**
851
- * Get document metadata.
852
- *
853
- * @param {String} id Document ID.
854
- * @param {Object} [query] HTTP query options.
855
- * @param {Object} [headers] HTTP headers.
856
- * @param {handler} [callback] Callback function.
857
- * @return {Promise} A Promise, if no callback is provided,
858
- * otherwise `null`.
859
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#HEAD|CouchDB Wiki}
860
- */
861
-
862
- DB.prototype.head = function (/* [id], [query], [headers], callback */) {
863
- var self = this;
864
- var request = self._(arguments);
865
- request._ = function (err, body, status, headers, res) {
866
- return [err, err ? null : {
867
- _id: request.p,
868
- _rev: headers.etag && JSON.parse(headers.etag),
869
- contentType: headers["content-type"],
870
- contentLength: headers["content-length"]
871
- }, status, headers, res];
872
- };
873
- return request("HEAD");
874
- };
875
-
876
- /**
877
- * Post document(s) to database.
878
- *
879
- * If documents have no ID, a document ID will be automatically generated
880
- * on the server. Attachments are not currently supported.
881
- *
882
- * @param {Object|Object[]} doc Document or array of documents.
883
- * @param {String} [doc._id] Document ID. If set, uses given document ID.
884
- * @param {String} [doc._rev] Document revision. If set, allows update to
885
- * existing document.
886
- * @param {Object} [doc._attachments] Attachments. If given, must be a
887
- * map of filenames to attachment properties.
888
- * @param {String} [doc._attachments[filename]] Attachment filename, as
889
- * hash key.
890
- * @param {String} [doc._attachments[filename].contentType] Attachment
891
- * MIME content type.
892
- * @param {String|Object} [doc._attachments[filename].data] Attachment
893
- * data. Will be Base64 encoded.
894
- * @param {Object} [query] HTTP query options.
895
- * @param {Boolean} [query.batch] Allow server to write document in
896
- * batch mode. Documents will not be written to disk immediately,
897
- * increasing the chances of write failure.
898
- * @param {Boolean} [query.all_or_nothing] For batch updating of
899
- * documents, use all-or-nothing semantics.
900
- * @param {Object} [headers] HTTP headers.
901
- * @param {handler} [callback] Callback function.
902
- * @return {Promise} A Promise, if no callback is provided,
903
- * otherwise `null`.
904
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#POST|CouchDB Wiki}
905
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
906
- */
907
-
908
- DB.prototype.post = function (docs /* [query], [headers], [callback] */) {
909
- var request = this._(arguments, 1);
910
- if (isArray(docs)) {
911
- request.p = "_bulk_docs";
912
- request.b = extend({ docs: docs }, request.q);
913
- request.q = null
914
- } else {
915
- request.b = docs;
916
- }
917
- return request("POST");
918
- };
919
-
920
- /**
921
- * Put document in database.
922
- *
923
- * @param {Object} doc Document data. Requires `_id` and `_rev`.
924
- * @param {String} [options] Options.
925
- * @param {Object} [query] HTTP query options.
926
- * @param {Object} [headers] HTTP headers.
927
- * @param {handler} [callback] Callback function.
928
- * @return {Promise} A Promise, if no callback is provided,
929
- * otherwise `null`.
930
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#PUT|CouchDB Wiki}
931
- */
932
-
933
- DB.prototype.put = function (/* [id], [doc], [query], [headers], [callback] */) {
934
- var request = this._(arguments, 0, 1);
935
- // prevent acidentally creating database
936
- if (!request.p) request.p = request.b._id || request.b.id;
937
- if (!request.p) throw new Error("missing id");
938
- return request("PUT");
939
- };
940
-
941
- /**
942
- * Delete document(s).
943
- *
944
- * @param {Object|Object[]} docs Document or array of documents.
945
- * @param {Object} [query] HTTP query options.
946
- * @param {Object} [headers] HTTP headers.
947
- * @param {handler} [callback] Callback function.
948
- * @return {Promise} A Promise, if no callback is provided,
949
- * otherwise `null`.
950
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#DELETE|CouchDB Wiki}
951
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
952
- */
953
-
954
- DB.prototype.del = function (docs /* [query], [headers], [callback] */) {
955
- if (isArray(docs)) {
956
- var i = 0, len = docs.length, doc;
957
- for (; i < len; i++) {
958
- doc = docs[i], docs[i] = {
959
- _id: doc._id || doc.id,
960
- _rev: doc._rev || doc.rev,
961
- _deleted: true
962
- };
963
- }
964
- return this.post.apply(this, arguments);
965
- } else {
966
- var request = this._(arguments, 0, 1);
967
- // prevent acidentally deleting database
968
- if (!request.p) throw new Error("missing id");
969
- return request("DELETE");
970
- }
971
- };
972
-
973
- /**
974
- * Copy document.
975
- *
976
- * @param {Object} source Source document.
977
- * @param {String} source.id Source document ID.
978
- * @param {String} [source.rev] Source document revision.
979
- * @param {String} [source._id] Source document ID. Alternate key for
980
- * `source.id`.
981
- * @param {String} [source._rev] Source document revision. Alternate key
982
- * for `source.id`.
983
- * @param {Object} target Target document.
984
- * @param {String} target.id Target document ID.
985
- * @param {String} [target.rev] Target document revision.
986
- * @param {String} [target._id] Target document ID. Alternate key for
987
- * `target.id`.
988
- * @param {String} [target._rev] Target document revision. Alternate key
989
- * for `target.id`.
990
- * @param {Object} [query] HTTP query options.
991
- * @param {Object} [headers] HTTP headers.
992
- * @param {handler} [callback] Callback function.
993
- * @return {Promise} A Promise, if no callback is provided,
994
- * otherwise `null`.
995
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Document_API#COPY|CouchDB Wiki}
996
- */
997
-
998
- DB.prototype.copy = function (source, target /* [query], [headers], [callback] */) {
999
- var request = this._(arguments, 2);
1000
- var sourcePath = encodeURIComponent(source.id || source._id || source);
1001
- var targetPath = encodeURIComponent(target.id || target._id || target);
1002
- var sourceRev = source.rev || source._rev;
1003
- var targetRev = target.rev || target._rev;
1004
-
1005
- if (sourceRev) request.q.rev = sourceRev;
1006
- if (targetRev) targetPath += "?rev=" + encodeURIComponent(targetRev);
1007
-
1008
- request.h.Destination = targetPath;
1009
-
1010
- return request("COPY", sourcePath);
1011
- };
1012
-
1013
- /**
1014
- * Query all documents by ID.
1015
- *
1016
- * @param {Object} [query] HTTP query options.
1017
- * @param {JSON} [query.startkey] Start returning results from this
1018
- * document ID.
1019
- * @param {JSON} [query.endkey] Stop returning results at this document
1020
- * ID.
1021
- * @param {Integer} [query.limit] Limit number of results returned.
1022
- * @param {Boolean} [query.descending=false] Lookup results in reverse
1023
- * order by key, returning documents in descending order by key.
1024
- * @param {Integer} [query.skip] Skip this many records before
1025
- * returning results.
1026
- * @param {Boolean} [query.include_docs=false] Include document source for
1027
- * each result.
1028
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
1029
- * in results.
1030
- * @param {Boolean} [query.update_seq=false] Include sequence value
1031
- * of the database corresponding to the view.
1032
- * @param {Object} [headers] HTTP headers.
1033
- * @param {handler} [callback] Callback function.
1034
- * @return {Promise} A Promise, if no callback is provided,
1035
- * otherwise `null`.
1036
- * @see {@link http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API|CouchDB Wiki}
1037
- */
1038
-
1039
- DB.prototype.all = function (/* [query], [headers], [callback] */) {
1040
- var request = this._(arguments);
1041
- var body = this._viewOptions(request.q);
1042
- return request(body ? "POST" : "GET", "_all_docs", { b: body });
1043
- };
1044
-
1045
- /**
1046
- * Query a view.
1047
- *
1048
- * @param {String|Object} view View name (e.g. mydesign/myview) or
1049
- * temporary view definition. Using a temporary view is strongly not
1050
- * recommended for production use.
1051
- * @param {Object} [query] HTTP query options.
1052
- * @param {JSON} [query.key] Key to lookup.
1053
- * @param {JSON} [query.startkey] Start returning results from this key.
1054
- * @param {String} [query.startkey_docid] Start returning results
1055
- * from this document ID. Allows pagination with duplicate keys.
1056
- * @param {JSON} [query.endkey] Stop returning results at this key.
1057
- * @param {String} [query.endkey_docid] Stop returning results at
1058
- * this document ID. Allows pagination with duplicate keys.
1059
- * @param {Integer} [query.limit] Limit number of results returned.
1060
- * @param {Boolean|String} [query.stale] Do not refresh view even if
1061
- * stale. For CouchDB versions `1.1.0` and up, set to `update_after` to
1062
- * update view after results are returned.
1063
- * @param {Boolean} [query.descending=false] Lookup results in reverse
1064
- * order by key, returning documents in descending order by key.
1065
- * @param {Integer} [query.skip] Skip this many records before
1066
- * returning results.
1067
- * @param {Boolean|Integer} [query.group=false] Use the reduce function
1068
- * to group results by key. Set to an integer specify `group_level`.
1069
- * @param {Boolean|Integer} [query.reduce=true] Use the reduce function.
1070
- * @param {Boolean} [query.fetch=false] Include document source for
1071
- * each result.
1072
- * @param {Boolean} [query.include_end=true] Include `query.endkey`
1073
- * in results.
1074
- * @param {Boolean} [query.update_seq=false] Include sequence value
1075
- * of the database corresponding to the view.
1076
- * @param {Object} [headers] HTTP headers.
1077
- * @param {handler} [callback] Callback function.
1078
- * @return {Promise} A Promise, if no callback is provided,
1079
- * otherwise `null`.
1080
- * @see {@link http://wiki.apache.org/couchdb/HTTP_view_API|CouchDB Wiki}
1081
- */
1082
-
1083
- DB.prototype.find = function (view /* [query], [headers], [callback] */) {
1084
- var request = this._(arguments, 1), path, body;
1085
-
1086
- if (isString(view)) {
1087
- path = view.split("/", 2);
1088
- path = "_design/" + encodeURIComponent(path[0]) +
1089
- "/_view/" + encodeURIComponent(path[1]);
1090
- } else {
1091
- path = "_temp_view";
1092
- body = view;
1093
- }
1094
-
1095
- body = this._viewOptions(request.q, body);
1096
- return request(body ? "POST" : "GET", path, { b: body });
1097
- };
1098
-
1099
- /**
1100
- * Get database changes.
1101
- *
1102
- * The `feed` option determines how the callback is called:
1103
- *
1104
- * - `normal` calls the callback once.
1105
- * - `longpoll` waits for a response, then calls the callback once.
1106
- * - `continuous` calls the callback each time an update is received.
1107
- * Implemented as the `database#follow()` method.
1108
- *
1109
- * @param {Object} [query] HTTP query options.
1110
- * @param {String} [query.feed="normal"] Type of feed. See comments
1111
- * above.
1112
- * @param {String} [query.filter] Filter updates using this filter.
1113
- * @param {Integer} [query.limit] Maximum number of rows to return.
1114
- * @param {Integer} [query.since=0] Start results from this sequence
1115
- * number.
1116
- * @param {Boolean} [query.include_docs=false] Include documents with
1117
- * results.
1118
- * @param {Integer} [query.timeout=1000] Maximum period in milliseconds
1119
- * to wait for a change before sending a response, even if there are no
1120
- * results.
1121
- * @param {Integer} [query.heartbeat=1000] Period in milliseconds after
1122
- * which an empty line is sent. Applicable only to feed types
1123
- * `longpoll` and `continuous`. Overrides `query.timeout` to keep the
1124
- * feed alive indefinitely.
1125
- * @param {Object} [headers] HTTP headers.
1126
- * @param {handler} [callback] Callback function.
1127
- * @return {Promise} A Promise, if no callback is provided,
1128
- * otherwise `null`.
1129
- * @see {@link http://wiki.apache.org/couchdb/HTTP_database_API#Changes|CouchDB Wiki}
1130
- */
1131
-
1132
- DB.prototype.changes = function (/* [query], [headers], [callback] */) {
1133
- var request = this._(arguments);
1134
- if (request.q.feed != "longpoll") delete request.q.feed;
1135
- return this._changes(request);
1136
- };
1137
-
1138
- /**
1139
- * Follow database changes.
1140
- *
1141
- * @see `#changes()`.
1142
- */
1143
-
1144
- DB.prototype.follow = function (/* [query], [headers], callback */) {
1145
- var self = this;
1146
- var request = this._(arguments);
1147
- var fn = request.f;
1148
-
1149
- if (!fn) return this;
1150
-
1151
- request.q.feed = "longpoll";
1152
- request.f = function (err, body) {
1153
- var args = [].slice.call(arguments);
1154
- var done, i;
1155
- for (i = 0; i < body.length; i++) {
1156
- args[1] = body[i];
1157
- if (done = fn.apply(self, args) === false || err) break;
1158
- }
1159
- if (!done) self._changes(request);
1160
- };
1161
-
1162
- return this._changes(request);
1163
- };
1164
-
1165
- /**
1166
- * Service a changes request.
1167
- *
1168
- * @private
1169
- */
1170
-
1171
- DB.prototype._changes = function (request) {
1172
- return request("GET", "_changes");
1173
- };
1174
-
1175
- /**
1176
- * Update document using server-side handler.
1177
- *
1178
- * @param {String} handler Update handler. Example: mydesign/myhandler
1179
- * @param {String} [id] Document ID.
1180
- * @param {any} data Data.
1181
- * @param {Object} [query] HTTP query options.
1182
- * @param {Object} [headers] Headers.
1183
- * @param {handler} [callback] Callback function.
1184
- * @return {Promise} A Promise, if no callback is provided,
1185
- * otherwise `null`.
1186
- * @see {@link http://wiki.apache.org/couchdb/Document_Update_Handlers|CouchDB Wiki}
1187
- */
1188
-
1189
- DB.prototype.update = function (handler /* [id], [data], [query], [headers], [callback] */) {
1190
- var request = this._(arguments, 1, 1, 1);
1191
- var path = handler.split("/", 2);
1192
-
1193
- path = "_design/" + encodeURIComponent(path[0]) +
1194
- "/_update/" + encodeURIComponent(path[1]);
1195
-
1196
- if (request.p) path += "/" + request.p;
1197
-
1198
- return request("POST", path);
1199
- };
1200
-
1201
- /**
1202
- * Download attachment from document.
1203
- *
1204
- * @param {Object|String} docOrId Document or document ID.
1205
- * @param {String} attachmentName Attachment name.
1206
- * @param {Object} [query] HTTP query options.
1207
- * @param {Object} [headers] HTTP headers.
1208
- * @param {handler} [callback] Callback function.
1209
- * @return {Promise} A Promise, if no callback is provided,
1210
- * otherwise `null`.
1211
- */
1212
-
1213
- DB.prototype.attachment = function (doc, attachmentName /* [query], [headers], [callback] */) {
1214
- var request = this._(arguments, 2);
1215
- var path = encodeURIComponent(doc._id || doc.id || doc) + "/" +
1216
- encodeURIComponent(attachmentName);
1217
- return request("GET", path, options);
1218
- };
1219
-
1220
- /**
1221
- * Upload attachment to document.
1222
- *
1223
- * Set the `Content-Type` header.
1224
- *
1225
- * @param {Object} [doc] Document. Requires `id`. `rev` can be specified
1226
- * here or in `query`.
1227
- * @param {String} attachmentName Attachment name.
1228
- * @param {Object} data Data.
1229
- * @param {Object} [query] HTTP query options.
1230
- * @param {Object} [headers] HTTP headers.
1231
- * @param {handler} [callback] Callback function.
1232
- * @return {Promise} A Promise, if no callback is provided,
1233
- * otherwise `null`.
1234
- */
1235
-
1236
- DB.prototype.attach = function (doc, attachmentName, data /* [query], [headers], [callback] */) {
1237
- var request = this._(arguments, 3);
1238
- request.p = encodeURIComponent(doc._id || doc.id) + "/" +
1239
- encodeURIComponent(attachmentName);
1240
- if (!request.q.rev) request.q.rev = doc._rev || doc.rev;
1241
- request.q.body = data;
1242
- return request("PUT", path);
1243
- };
1244
-
1245
- /**
1246
- * Replicate database.
1247
- *
1248
- * This convenience function sets `options.source` and `options.target` to
1249
- * the selected database name. Either `options.source` or `options.target`
1250
- * must be overridden for a successful replication request.
1251
- *
1252
- * @param {Options} options Options. Accepts all options from
1253
- * `Client.replicate()`.
1254
- * @param {String} [options.source=this.name] Source database URL or
1255
- * local name. Defaults to the selected database name if not given.
1256
- * @param {String} [options.target=this.name] Target database URL or
1257
- * local name. Defaults to the selected database name if not given.
1258
- * @param {Object} [query] HTTP query options.
1259
- * @param {Object} [headers] HTTP headers.
1260
- * @param {handler} [callback] Callback function.
1261
- * @return {Promise} A Promise, if no callback is provided,
1262
- * otherwise `null`.
1263
- */
1264
-
1265
- DB.prototype.replicate = function (options /* [query], [headers], [callback] */) {
1266
- if (!options.source) options.source = this.name;
1267
- if (!options.target) options.target = this.name;
1268
- return this.client.replicate.apply(this.client, arguments);
1269
- };
1270
-
1271
- /**
1272
- * Ensure recent changes are committed to disk.
1273
- *
1274
- * @param {Object} [query] HTTP query options.
1275
- * @param {Object} [headers] HTTP headers.
1276
- * @param {handler} [callback] Callback function.
1277
- * @return {Promise} A Promise, if no callback is provided,
1278
- * otherwise `null`.
1279
- */
1280
-
1281
- DB.prototype.commit = function (/* [query], [headers], [callback] */) {
1282
- return this._(arguments)("POST", "_ensure_full_commit");
1283
- };
1284
-
1285
- /**
1286
- * Purge deleted documents from database.
1287
- *
1288
- * @param {Object} revs Map of document IDs to revisions to be purged.
1289
- * @param {Object} [query] HTTP query options.
1290
- * @param {Object} [headers] HTTP headers.
1291
- * @param {handler} [callback] Callback function.
1292
- * @return {Promise} A Promise, if no callback is provided,
1293
- * otherwise `null`.
1294
- */
1295
-
1296
- DB.prototype.purge = function (revs /* [query], [headers], [callback] */) {
1297
- return this._(arguments, 1)("POST", "_purge", { b: revs });
1298
- };
1299
-
1300
- /**
1301
- * Compact database or design.
1302
- *
1303
- * @param {String} [design] Design name if compacting design indexes.
1304
- * @param {Object} [query] HTTP query options.
1305
- * @param {Object} [headers] HTTP headers.
1306
- * @param {handler} [callback] Callback function.
1307
- * @return {Promise} A Promise, if no callback is provided,
1308
- * otherwise `null`.
1309
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1310
- */
1311
-
1312
- DB.prototype.compact = function (/* [design], [query], [headers], [callback] */) {
1313
- var request = this._(arguments);
1314
- return request("POST", "_compact/" + (request.p || ""));
1315
- };
1316
-
1317
- /**
1318
- * Remove unused views.
1319
- *
1320
- * @param {Object} [query] HTTP query options.
1321
- * @param {Object} [headers] HTTP headers.
1322
- * @param {handler} [callback] Callback function.
1323
- * @return {Promise} A Promise, if no callback is provided,
1324
- * otherwise `null`.
1325
- * @see {@link http://wiki.apache.org/couchdb/Compaction|CouchDB Wiki}
1326
- */
1327
-
1328
- DB.prototype.vacuum = function (/* [query], [headers], [callback] */) {
1329
- return this._(arguments)("POST", "_view_cleanup");
1330
- };
1331
-
1332
- /**
1333
- * Parse view options.
1334
- *
1335
- * @param {Object} query The HTTP query options.
1336
- * @param {Object} body The body payload.
1337
- * @param {handler} [callback] Callback function.
1338
- * @return {Object} The body payload.
1339
- * @private
1340
- */
1341
-
1342
- DB.prototype._viewOptions = function (q, body) {
1343
- if (q) {
1344
- if (q.key) q.key = JSON.stringify(q.key);
1345
- if (q.startkey) q.startkey = JSON.stringify(q.startkey);
1346
- if (q.endkey) q.endkey = JSON.stringify(q.endkey);
1347
- if (q.stale && q.stale != "update_after") q.stale = "ok";
1348
- if (q.keys) {
1349
- if (!body) body = {};
1350
- body.keys = q.keys;
1351
- delete q.keys;
1352
- }
1353
- }
1354
- return body;
1355
- };
1356
-
1357
- /**
1358
- * Handle a clerk response.
1359
- *
1360
- * @callback handler
1361
- * @param {Error|null} error Error or `null` on success.
1362
- * @param {Object} data Response data.
1363
- * @param {Integer} status Response status code.
1364
- * @param {Object} headers Response headers.
1365
- * @param {superagent.Response} res Superagent response object.
1366
- */
1367
-
1368
- clerk.Base = Base;
1369
- clerk.Client = Client;
1370
- clerk.DB = DB;
1371
-
1372
- // Export clerk.
1373
- module.exports = clerk;
1374
-
1375
-
1376
- /***/ },
1377
- /* 1 */
1378
- /***/ function(module, exports, __webpack_require__) {
1379
-
1380
- /**
1381
- * Module dependencies.
1382
- */
1383
-
1384
- var Emitter = __webpack_require__(2);
1385
- var reduce = __webpack_require__(3);
1386
-
1387
- /**
1388
- * Root reference for iframes.
1389
- */
1390
-
1391
- var root = 'undefined' == typeof window
1392
- ? (this || self)
1393
- : window;
1394
-
1395
- /**
1396
- * Noop.
1397
- */
1398
-
1399
- function noop(){};
1400
-
1401
- /**
1402
- * Check if `obj` is a host object,
1403
- * we don't want to serialize these :)
1404
- *
1405
- * TODO: future proof, move to compoent land
1406
- *
1407
- * @param {Object} obj
1408
- * @return {Boolean}
1409
- * @api private
1410
- */
1411
-
1412
- function isHost(obj) {
1413
- var str = {}.toString.call(obj);
1414
-
1415
- switch (str) {
1416
- case '[object File]':
1417
- case '[object Blob]':
1418
- case '[object FormData]':
1419
- return true;
1420
- default:
1421
- return false;
1422
- }
1423
- }
1424
-
1425
- /**
1426
- * Determine XHR.
1427
- */
1428
-
1429
- request.getXHR = function () {
1430
- if (root.XMLHttpRequest
1431
- && (!root.location || 'file:' != root.location.protocol
1432
- || !root.ActiveXObject)) {
1433
- return new XMLHttpRequest;
1434
- } else {
1435
- try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
1436
- try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
1437
- try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
1438
- try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
1439
- }
1440
- return false;
1441
- };
1442
-
1443
- /**
1444
- * Removes leading and trailing whitespace, added to support IE.
1445
- *
1446
- * @param {String} s
1447
- * @return {String}
1448
- * @api private
1449
- */
1450
-
1451
- var trim = ''.trim
1452
- ? function(s) { return s.trim(); }
1453
- : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
1454
-
1455
- /**
1456
- * Check if `obj` is an object.
1457
- *
1458
- * @param {Object} obj
1459
- * @return {Boolean}
1460
- * @api private
1461
- */
1462
-
1463
- function isObject(obj) {
1464
- return obj === Object(obj);
1465
- }
1466
-
1467
- /**
1468
- * Serialize the given `obj`.
1469
- *
1470
- * @param {Object} obj
1471
- * @return {String}
1472
- * @api private
1473
- */
1474
-
1475
- function serialize(obj) {
1476
- if (!isObject(obj)) return obj;
1477
- var pairs = [];
1478
- for (var key in obj) {
1479
- if (null != obj[key]) {
1480
- pairs.push(encodeURIComponent(key)
1481
- + '=' + encodeURIComponent(obj[key]));
1482
- }
1483
- }
1484
- return pairs.join('&');
1485
- }
1486
-
1487
- /**
1488
- * Expose serialization method.
1489
- */
1490
-
1491
- request.serializeObject = serialize;
1492
-
1493
- /**
1494
- * Parse the given x-www-form-urlencoded `str`.
1495
- *
1496
- * @param {String} str
1497
- * @return {Object}
1498
- * @api private
1499
- */
1500
-
1501
- function parseString(str) {
1502
- var obj = {};
1503
- var pairs = str.split('&');
1504
- var parts;
1505
- var pair;
1506
-
1507
- for (var i = 0, len = pairs.length; i < len; ++i) {
1508
- pair = pairs[i];
1509
- parts = pair.split('=');
1510
- obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
1511
- }
1512
-
1513
- return obj;
1514
- }
1515
-
1516
- /**
1517
- * Expose parser.
1518
- */
1519
-
1520
- request.parseString = parseString;
1521
-
1522
- /**
1523
- * Default MIME type map.
1524
- *
1525
- * superagent.types.xml = 'application/xml';
1526
- *
1527
- */
1528
-
1529
- request.types = {
1530
- html: 'text/html',
1531
- json: 'application/json',
1532
- xml: 'application/xml',
1533
- urlencoded: 'application/x-www-form-urlencoded',
1534
- 'form': 'application/x-www-form-urlencoded',
1535
- 'form-data': 'application/x-www-form-urlencoded'
1536
- };
1537
-
1538
- /**
1539
- * Default serialization map.
1540
- *
1541
- * superagent.serialize['application/xml'] = function(obj){
1542
- * return 'generated xml here';
1543
- * };
1544
- *
1545
- */
1546
-
1547
- request.serialize = {
1548
- 'application/x-www-form-urlencoded': serialize,
1549
- 'application/json': JSON.stringify
1550
- };
1551
-
1552
- /**
1553
- * Default parsers.
1554
- *
1555
- * superagent.parse['application/xml'] = function(str){
1556
- * return { object parsed from str };
1557
- * };
1558
- *
1559
- */
1560
-
1561
- request.parse = {
1562
- 'application/x-www-form-urlencoded': parseString,
1563
- 'application/json': JSON.parse
1564
- };
1565
-
1566
- /**
1567
- * Parse the given header `str` into
1568
- * an object containing the mapped fields.
1569
- *
1570
- * @param {String} str
1571
- * @return {Object}
1572
- * @api private
1573
- */
1574
-
1575
- function parseHeader(str) {
1576
- var lines = str.split(/\r?\n/);
1577
- var fields = {};
1578
- var index;
1579
- var line;
1580
- var field;
1581
- var val;
1582
-
1583
- lines.pop(); // trailing CRLF
1584
-
1585
- for (var i = 0, len = lines.length; i < len; ++i) {
1586
- line = lines[i];
1587
- index = line.indexOf(':');
1588
- field = line.slice(0, index).toLowerCase();
1589
- val = trim(line.slice(index + 1));
1590
- fields[field] = val;
1591
- }
1592
-
1593
- return fields;
1594
- }
1595
-
1596
- /**
1597
- * Return the mime type for the given `str`.
1598
- *
1599
- * @param {String} str
1600
- * @return {String}
1601
- * @api private
1602
- */
1603
-
1604
- function type(str){
1605
- return str.split(/ *; */).shift();
1606
- };
1607
-
1608
- /**
1609
- * Return header field parameters.
1610
- *
1611
- * @param {String} str
1612
- * @return {Object}
1613
- * @api private
1614
- */
1615
-
1616
- function params(str){
1617
- return reduce(str.split(/ *; */), function(obj, str){
1618
- var parts = str.split(/ *= */)
1619
- , key = parts.shift()
1620
- , val = parts.shift();
1621
-
1622
- if (key && val) obj[key] = val;
1623
- return obj;
1624
- }, {});
1625
- };
1626
-
1627
- /**
1628
- * Initialize a new `Response` with the given `xhr`.
1629
- *
1630
- * - set flags (.ok, .error, etc)
1631
- * - parse header
1632
- *
1633
- * Examples:
1634
- *
1635
- * Aliasing `superagent` as `request` is nice:
1636
- *
1637
- * request = superagent;
1638
- *
1639
- * We can use the promise-like API, or pass callbacks:
1640
- *
1641
- * request.get('/').end(function(res){});
1642
- * request.get('/', function(res){});
1643
- *
1644
- * Sending data can be chained:
1645
- *
1646
- * request
1647
- * .post('/user')
1648
- * .send({ name: 'tj' })
1649
- * .end(function(res){});
1650
- *
1651
- * Or passed to `.send()`:
1652
- *
1653
- * request
1654
- * .post('/user')
1655
- * .send({ name: 'tj' }, function(res){});
1656
- *
1657
- * Or passed to `.post()`:
1658
- *
1659
- * request
1660
- * .post('/user', { name: 'tj' })
1661
- * .end(function(res){});
1662
- *
1663
- * Or further reduced to a single call for simple cases:
1664
- *
1665
- * request
1666
- * .post('/user', { name: 'tj' }, function(res){});
1667
- *
1668
- * @param {XMLHTTPRequest} xhr
1669
- * @param {Object} options
1670
- * @api private
1671
- */
1672
-
1673
- function Response(req, options) {
1674
- options = options || {};
1675
- this.req = req;
1676
- this.xhr = this.req.xhr;
1677
- // responseText is accessible only if responseType is '' or 'text' and on older browsers
1678
- this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
1679
- ? this.xhr.responseText
1680
- : null;
1681
- this.statusText = this.req.xhr.statusText;
1682
- this.setStatusProperties(this.xhr.status);
1683
- this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
1684
- // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
1685
- // getResponseHeader still works. so we get content-type even if getting
1686
- // other headers fails.
1687
- this.header['content-type'] = this.xhr.getResponseHeader('content-type');
1688
- this.setHeaderProperties(this.header);
1689
- this.body = this.req.method != 'HEAD'
1690
- ? this.parseBody(this.text ? this.text : this.xhr.response)
1691
- : null;
1692
- }
1693
-
1694
- /**
1695
- * Get case-insensitive `field` value.
1696
- *
1697
- * @param {String} field
1698
- * @return {String}
1699
- * @api public
1700
- */
1701
-
1702
- Response.prototype.get = function(field){
1703
- return this.header[field.toLowerCase()];
1704
- };
1705
-
1706
- /**
1707
- * Set header related properties:
1708
- *
1709
- * - `.type` the content type without params
1710
- *
1711
- * A response of "Content-Type: text/plain; charset=utf-8"
1712
- * will provide you with a `.type` of "text/plain".
1713
- *
1714
- * @param {Object} header
1715
- * @api private
1716
- */
1717
-
1718
- Response.prototype.setHeaderProperties = function(header){
1719
- // content-type
1720
- var ct = this.header['content-type'] || '';
1721
- this.type = type(ct);
1722
-
1723
- // params
1724
- var obj = params(ct);
1725
- for (var key in obj) this[key] = obj[key];
1726
- };
1727
-
1728
- /**
1729
- * Parse the given body `str`.
1730
- *
1731
- * Used for auto-parsing of bodies. Parsers
1732
- * are defined on the `superagent.parse` object.
1733
- *
1734
- * @param {String} str
1735
- * @return {Mixed}
1736
- * @api private
1737
- */
1738
-
1739
- Response.prototype.parseBody = function(str){
1740
- var parse = request.parse[this.type];
1741
- return parse && str && (str.length || str instanceof Object)
1742
- ? parse(str)
1743
- : null;
1744
- };
1745
-
1746
- /**
1747
- * Set flags such as `.ok` based on `status`.
1748
- *
1749
- * For example a 2xx response will give you a `.ok` of __true__
1750
- * whereas 5xx will be __false__ and `.error` will be __true__. The
1751
- * `.clientError` and `.serverError` are also available to be more
1752
- * specific, and `.statusType` is the class of error ranging from 1..5
1753
- * sometimes useful for mapping respond colors etc.
1754
- *
1755
- * "sugar" properties are also defined for common cases. Currently providing:
1756
- *
1757
- * - .noContent
1758
- * - .badRequest
1759
- * - .unauthorized
1760
- * - .notAcceptable
1761
- * - .notFound
1762
- *
1763
- * @param {Number} status
1764
- * @api private
1765
- */
1766
-
1767
- Response.prototype.setStatusProperties = function(status){
1768
- // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
1769
- if (status === 1223) {
1770
- status = 204;
1771
- }
1772
-
1773
- var type = status / 100 | 0;
1774
-
1775
- // status / class
1776
- this.status = status;
1777
- this.statusType = type;
1778
-
1779
- // basics
1780
- this.info = 1 == type;
1781
- this.ok = 2 == type;
1782
- this.clientError = 4 == type;
1783
- this.serverError = 5 == type;
1784
- this.error = (4 == type || 5 == type)
1785
- ? this.toError()
1786
- : false;
1787
-
1788
- // sugar
1789
- this.accepted = 202 == status;
1790
- this.noContent = 204 == status;
1791
- this.badRequest = 400 == status;
1792
- this.unauthorized = 401 == status;
1793
- this.notAcceptable = 406 == status;
1794
- this.notFound = 404 == status;
1795
- this.forbidden = 403 == status;
1796
- };
1797
-
1798
- /**
1799
- * Return an `Error` representative of this response.
1800
- *
1801
- * @return {Error}
1802
- * @api public
1803
- */
1804
-
1805
- Response.prototype.toError = function(){
1806
- var req = this.req;
1807
- var method = req.method;
1808
- var url = req.url;
1809
-
1810
- var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
1811
- var err = new Error(msg);
1812
- err.status = this.status;
1813
- err.method = method;
1814
- err.url = url;
1815
-
1816
- return err;
1817
- };
1818
-
1819
- /**
1820
- * Expose `Response`.
1821
- */
1822
-
1823
- request.Response = Response;
1824
-
1825
- /**
1826
- * Initialize a new `Request` with the given `method` and `url`.
1827
- *
1828
- * @param {String} method
1829
- * @param {String} url
1830
- * @api public
1831
- */
1832
-
1833
- function Request(method, url) {
1834
- var self = this;
1835
- Emitter.call(this);
1836
- this._query = this._query || [];
1837
- this.method = method;
1838
- this.url = url;
1839
- this.header = {};
1840
- this._header = {};
1841
- this.on('end', function(){
1842
- var err = null;
1843
- var res = null;
1844
-
1845
- try {
1846
- res = new Response(self);
1847
- } catch(e) {
1848
- err = new Error('Parser is unable to parse the response');
1849
- err.parse = true;
1850
- err.original = e;
1851
- return self.callback(err);
1852
- }
1853
-
1854
- self.emit('response', res);
1855
-
1856
- if (err) {
1857
- return self.callback(err, res);
1858
- }
1859
-
1860
- if (res.status >= 200 && res.status < 300) {
1861
- return self.callback(err, res);
1862
- }
1863
-
1864
- var new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
1865
- new_err.original = err;
1866
- new_err.response = res;
1867
- new_err.status = res.status;
1868
-
1869
- self.callback(err || new_err, res);
1870
- });
1871
- }
1872
-
1873
- /**
1874
- * Mixin `Emitter`.
1875
- */
1876
-
1877
- Emitter(Request.prototype);
1878
-
1879
- /**
1880
- * Allow for extension
1881
- */
1882
-
1883
- Request.prototype.use = function(fn) {
1884
- fn(this);
1885
- return this;
1886
- }
1887
-
1888
- /**
1889
- * Set timeout to `ms`.
1890
- *
1891
- * @param {Number} ms
1892
- * @return {Request} for chaining
1893
- * @api public
1894
- */
1895
-
1896
- Request.prototype.timeout = function(ms){
1897
- this._timeout = ms;
1898
- return this;
1899
- };
1900
-
1901
- /**
1902
- * Clear previous timeout.
1903
- *
1904
- * @return {Request} for chaining
1905
- * @api public
1906
- */
1907
-
1908
- Request.prototype.clearTimeout = function(){
1909
- this._timeout = 0;
1910
- clearTimeout(this._timer);
1911
- return this;
1912
- };
1913
-
1914
- /**
1915
- * Abort the request, and clear potential timeout.
1916
- *
1917
- * @return {Request}
1918
- * @api public
1919
- */
1920
-
1921
- Request.prototype.abort = function(){
1922
- if (this.aborted) return;
1923
- this.aborted = true;
1924
- this.xhr.abort();
1925
- this.clearTimeout();
1926
- this.emit('abort');
1927
- return this;
1928
- };
1929
-
1930
- /**
1931
- * Set header `field` to `val`, or multiple fields with one object.
1932
- *
1933
- * Examples:
1934
- *
1935
- * req.get('/')
1936
- * .set('Accept', 'application/json')
1937
- * .set('X-API-Key', 'foobar')
1938
- * .end(callback);
1939
- *
1940
- * req.get('/')
1941
- * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
1942
- * .end(callback);
1943
- *
1944
- * @param {String|Object} field
1945
- * @param {String} val
1946
- * @return {Request} for chaining
1947
- * @api public
1948
- */
1949
-
1950
- Request.prototype.set = function(field, val){
1951
- if (isObject(field)) {
1952
- for (var key in field) {
1953
- this.set(key, field[key]);
1954
- }
1955
- return this;
1956
- }
1957
- this._header[field.toLowerCase()] = val;
1958
- this.header[field] = val;
1959
- return this;
1960
- };
1961
-
1962
- /**
1963
- * Remove header `field`.
1964
- *
1965
- * Example:
1966
- *
1967
- * req.get('/')
1968
- * .unset('User-Agent')
1969
- * .end(callback);
1970
- *
1971
- * @param {String} field
1972
- * @return {Request} for chaining
1973
- * @api public
1974
- */
1975
-
1976
- Request.prototype.unset = function(field){
1977
- delete this._header[field.toLowerCase()];
1978
- delete this.header[field];
1979
- return this;
1980
- };
1981
-
1982
- /**
1983
- * Get case-insensitive header `field` value.
1984
- *
1985
- * @param {String} field
1986
- * @return {String}
1987
- * @api private
1988
- */
1989
-
1990
- Request.prototype.getHeader = function(field){
1991
- return this._header[field.toLowerCase()];
1992
- };
1993
-
1994
- /**
1995
- * Set Content-Type to `type`, mapping values from `request.types`.
1996
- *
1997
- * Examples:
1998
- *
1999
- * superagent.types.xml = 'application/xml';
2000
- *
2001
- * request.post('/')
2002
- * .type('xml')
2003
- * .send(xmlstring)
2004
- * .end(callback);
2005
- *
2006
- * request.post('/')
2007
- * .type('application/xml')
2008
- * .send(xmlstring)
2009
- * .end(callback);
2010
- *
2011
- * @param {String} type
2012
- * @return {Request} for chaining
2013
- * @api public
2014
- */
2015
-
2016
- Request.prototype.type = function(type){
2017
- this.set('Content-Type', request.types[type] || type);
2018
- return this;
2019
- };
2020
-
2021
- /**
2022
- * Set Accept to `type`, mapping values from `request.types`.
2023
- *
2024
- * Examples:
2025
- *
2026
- * superagent.types.json = 'application/json';
2027
- *
2028
- * request.get('/agent')
2029
- * .accept('json')
2030
- * .end(callback);
2031
- *
2032
- * request.get('/agent')
2033
- * .accept('application/json')
2034
- * .end(callback);
2035
- *
2036
- * @param {String} accept
2037
- * @return {Request} for chaining
2038
- * @api public
2039
- */
2040
-
2041
- Request.prototype.accept = function(type){
2042
- this.set('Accept', request.types[type] || type);
2043
- return this;
2044
- };
2045
-
2046
- /**
2047
- * Set Authorization field value with `user` and `pass`.
2048
- *
2049
- * @param {String} user
2050
- * @param {String} pass
2051
- * @return {Request} for chaining
2052
- * @api public
2053
- */
2054
-
2055
- Request.prototype.auth = function(user, pass){
2056
- var str = btoa(user + ':' + pass);
2057
- this.set('Authorization', 'Basic ' + str);
2058
- return this;
2059
- };
2060
-
2061
- /**
2062
- * Add query-string `val`.
2063
- *
2064
- * Examples:
2065
- *
2066
- * request.get('/shoes')
2067
- * .query('size=10')
2068
- * .query({ color: 'blue' })
2069
- *
2070
- * @param {Object|String} val
2071
- * @return {Request} for chaining
2072
- * @api public
2073
- */
2074
-
2075
- Request.prototype.query = function(val){
2076
- if ('string' != typeof val) val = serialize(val);
2077
- if (val) this._query.push(val);
2078
- return this;
2079
- };
2080
-
2081
- /**
2082
- * Write the field `name` and `val` for "multipart/form-data"
2083
- * request bodies.
2084
- *
2085
- * ``` js
2086
- * request.post('/upload')
2087
- * .field('foo', 'bar')
2088
- * .end(callback);
2089
- * ```
2090
- *
2091
- * @param {String} name
2092
- * @param {String|Blob|File} val
2093
- * @return {Request} for chaining
2094
- * @api public
2095
- */
2096
-
2097
- Request.prototype.field = function(name, val){
2098
- if (!this._formData) this._formData = new root.FormData();
2099
- this._formData.append(name, val);
2100
- return this;
2101
- };
2102
-
2103
- /**
2104
- * Queue the given `file` as an attachment to the specified `field`,
2105
- * with optional `filename`.
2106
- *
2107
- * ``` js
2108
- * request.post('/upload')
2109
- * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
2110
- * .end(callback);
2111
- * ```
2112
- *
2113
- * @param {String} field
2114
- * @param {Blob|File} file
2115
- * @param {String} filename
2116
- * @return {Request} for chaining
2117
- * @api public
2118
- */
2119
-
2120
- Request.prototype.attach = function(field, file, filename){
2121
- if (!this._formData) this._formData = new root.FormData();
2122
- this._formData.append(field, file, filename);
2123
- return this;
2124
- };
2125
-
2126
- /**
2127
- * Send `data`, defaulting the `.type()` to "json" when
2128
- * an object is given.
2129
- *
2130
- * Examples:
2131
- *
2132
- * // querystring
2133
- * request.get('/search')
2134
- * .end(callback)
2135
- *
2136
- * // multiple data "writes"
2137
- * request.get('/search')
2138
- * .send({ search: 'query' })
2139
- * .send({ range: '1..5' })
2140
- * .send({ order: 'desc' })
2141
- * .end(callback)
2142
- *
2143
- * // manual json
2144
- * request.post('/user')
2145
- * .type('json')
2146
- * .send('{"name":"tj"})
2147
- * .end(callback)
2148
- *
2149
- * // auto json
2150
- * request.post('/user')
2151
- * .send({ name: 'tj' })
2152
- * .end(callback)
2153
- *
2154
- * // manual x-www-form-urlencoded
2155
- * request.post('/user')
2156
- * .type('form')
2157
- * .send('name=tj')
2158
- * .end(callback)
2159
- *
2160
- * // auto x-www-form-urlencoded
2161
- * request.post('/user')
2162
- * .type('form')
2163
- * .send({ name: 'tj' })
2164
- * .end(callback)
2165
- *
2166
- * // defaults to x-www-form-urlencoded
2167
- * request.post('/user')
2168
- * .send('name=tobi')
2169
- * .send('species=ferret')
2170
- * .end(callback)
2171
- *
2172
- * @param {String|Object} data
2173
- * @return {Request} for chaining
2174
- * @api public
2175
- */
2176
-
2177
- Request.prototype.send = function(data){
2178
- var obj = isObject(data);
2179
- var type = this.getHeader('Content-Type');
2180
-
2181
- // merge
2182
- if (obj && isObject(this._data)) {
2183
- for (var key in data) {
2184
- this._data[key] = data[key];
2185
- }
2186
- } else if ('string' == typeof data) {
2187
- if (!type) this.type('form');
2188
- type = this.getHeader('Content-Type');
2189
- if ('application/x-www-form-urlencoded' == type) {
2190
- this._data = this._data
2191
- ? this._data + '&' + data
2192
- : data;
2193
- } else {
2194
- this._data = (this._data || '') + data;
2195
- }
2196
- } else {
2197
- this._data = data;
2198
- }
2199
-
2200
- if (!obj || isHost(data)) return this;
2201
- if (!type) this.type('json');
2202
- return this;
2203
- };
2204
-
2205
- /**
2206
- * Invoke the callback with `err` and `res`
2207
- * and handle arity check.
2208
- *
2209
- * @param {Error} err
2210
- * @param {Response} res
2211
- * @api private
2212
- */
2213
-
2214
- Request.prototype.callback = function(err, res){
2215
- var fn = this._callback;
2216
- this.clearTimeout();
2217
- fn(err, res);
2218
- };
2219
-
2220
- /**
2221
- * Invoke callback with x-domain error.
2222
- *
2223
- * @api private
2224
- */
2225
-
2226
- Request.prototype.crossDomainError = function(){
2227
- var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
2228
- err.crossDomain = true;
2229
- this.callback(err);
2230
- };
2231
-
2232
- /**
2233
- * Invoke callback with timeout error.
2234
- *
2235
- * @api private
2236
- */
2237
-
2238
- Request.prototype.timeoutError = function(){
2239
- var timeout = this._timeout;
2240
- var err = new Error('timeout of ' + timeout + 'ms exceeded');
2241
- err.timeout = timeout;
2242
- this.callback(err);
2243
- };
2244
-
2245
- /**
2246
- * Enable transmission of cookies with x-domain requests.
2247
- *
2248
- * Note that for this to work the origin must not be
2249
- * using "Access-Control-Allow-Origin" with a wildcard,
2250
- * and also must set "Access-Control-Allow-Credentials"
2251
- * to "true".
2252
- *
2253
- * @api public
2254
- */
2255
-
2256
- Request.prototype.withCredentials = function(){
2257
- this._withCredentials = true;
2258
- return this;
2259
- };
2260
-
2261
- /**
2262
- * Initiate request, invoking callback `fn(res)`
2263
- * with an instanceof `Response`.
2264
- *
2265
- * @param {Function} fn
2266
- * @return {Request} for chaining
2267
- * @api public
2268
- */
2269
-
2270
- Request.prototype.end = function(fn){
2271
- var self = this;
2272
- var xhr = this.xhr = request.getXHR();
2273
- var query = this._query.join('&');
2274
- var timeout = this._timeout;
2275
- var data = this._formData || this._data;
2276
-
2277
- // store callback
2278
- this._callback = fn || noop;
2279
-
2280
- // state change
2281
- xhr.onreadystatechange = function(){
2282
- if (4 != xhr.readyState) return;
2283
-
2284
- // In IE9, reads to any property (e.g. status) off of an aborted XHR will
2285
- // result in the error "Could not complete the operation due to error c00c023f"
2286
- var status;
2287
- try { status = xhr.status } catch(e) { status = 0; }
2288
-
2289
- if (0 == status) {
2290
- if (self.timedout) return self.timeoutError();
2291
- if (self.aborted) return;
2292
- return self.crossDomainError();
2293
- }
2294
- self.emit('end');
2295
- };
2296
-
2297
- // progress
2298
- var handleProgress = function(e){
2299
- if (e.total > 0) {
2300
- e.percent = e.loaded / e.total * 100;
2301
- }
2302
- self.emit('progress', e);
2303
- };
2304
- if (this.hasListeners('progress')) {
2305
- xhr.onprogress = handleProgress;
2306
- }
2307
- try {
2308
- if (xhr.upload && this.hasListeners('progress')) {
2309
- xhr.upload.onprogress = handleProgress;
2310
- }
2311
- } catch(e) {
2312
- // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
2313
- // Reported here:
2314
- // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
2315
- }
2316
-
2317
- // timeout
2318
- if (timeout && !this._timer) {
2319
- this._timer = setTimeout(function(){
2320
- self.timedout = true;
2321
- self.abort();
2322
- }, timeout);
2323
- }
2324
-
2325
- // querystring
2326
- if (query) {
2327
- query = request.serializeObject(query);
2328
- this.url += ~this.url.indexOf('?')
2329
- ? '&' + query
2330
- : '?' + query;
2331
- }
2332
-
2333
- // initiate request
2334
- xhr.open(this.method, this.url, true);
2335
-
2336
- // CORS
2337
- if (this._withCredentials) xhr.withCredentials = true;
2338
-
2339
- // body
2340
- if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
2341
- // serialize stuff
2342
- var serialize = request.serialize[this.getHeader('Content-Type')];
2343
- if (serialize) data = serialize(data);
2344
- }
2345
-
2346
- // set header fields
2347
- for (var field in this.header) {
2348
- if (null == this.header[field]) continue;
2349
- xhr.setRequestHeader(field, this.header[field]);
2350
- }
2351
-
2352
- // send stuff
2353
- this.emit('request', this);
2354
- xhr.send(data);
2355
- return this;
2356
- };
2357
-
2358
- /**
2359
- * Expose `Request`.
2360
- */
2361
-
2362
- request.Request = Request;
2363
-
2364
- /**
2365
- * Issue a request:
2366
- *
2367
- * Examples:
2368
- *
2369
- * request('GET', '/users').end(callback)
2370
- * request('/users').end(callback)
2371
- * request('/users', callback)
2372
- *
2373
- * @param {String} method
2374
- * @param {String|Function} url or callback
2375
- * @return {Request}
2376
- * @api public
2377
- */
2378
-
2379
- function request(method, url) {
2380
- // callback
2381
- if ('function' == typeof url) {
2382
- return new Request('GET', method).end(url);
2383
- }
2384
-
2385
- // url first
2386
- if (1 == arguments.length) {
2387
- return new Request('GET', method);
2388
- }
2389
-
2390
- return new Request(method, url);
2391
- }
2392
-
2393
- /**
2394
- * GET `url` with optional callback `fn(res)`.
2395
- *
2396
- * @param {String} url
2397
- * @param {Mixed|Function} data or fn
2398
- * @param {Function} fn
2399
- * @return {Request}
2400
- * @api public
2401
- */
2402
-
2403
- request.get = function(url, data, fn){
2404
- var req = request('GET', url);
2405
- if ('function' == typeof data) fn = data, data = null;
2406
- if (data) req.query(data);
2407
- if (fn) req.end(fn);
2408
- return req;
2409
- };
2410
-
2411
- /**
2412
- * HEAD `url` with optional callback `fn(res)`.
2413
- *
2414
- * @param {String} url
2415
- * @param {Mixed|Function} data or fn
2416
- * @param {Function} fn
2417
- * @return {Request}
2418
- * @api public
2419
- */
2420
-
2421
- request.head = function(url, data, fn){
2422
- var req = request('HEAD', url);
2423
- if ('function' == typeof data) fn = data, data = null;
2424
- if (data) req.send(data);
2425
- if (fn) req.end(fn);
2426
- return req;
2427
- };
2428
-
2429
- /**
2430
- * DELETE `url` with optional callback `fn(res)`.
2431
- *
2432
- * @param {String} url
2433
- * @param {Function} fn
2434
- * @return {Request}
2435
- * @api public
2436
- */
2437
-
2438
- request.del = function(url, fn){
2439
- var req = request('DELETE', url);
2440
- if (fn) req.end(fn);
2441
- return req;
2442
- };
2443
-
2444
- /**
2445
- * PATCH `url` with optional `data` and callback `fn(res)`.
2446
- *
2447
- * @param {String} url
2448
- * @param {Mixed} data
2449
- * @param {Function} fn
2450
- * @return {Request}
2451
- * @api public
2452
- */
2453
-
2454
- request.patch = function(url, data, fn){
2455
- var req = request('PATCH', url);
2456
- if ('function' == typeof data) fn = data, data = null;
2457
- if (data) req.send(data);
2458
- if (fn) req.end(fn);
2459
- return req;
2460
- };
2461
-
2462
- /**
2463
- * POST `url` with optional `data` and callback `fn(res)`.
2464
- *
2465
- * @param {String} url
2466
- * @param {Mixed} data
2467
- * @param {Function} fn
2468
- * @return {Request}
2469
- * @api public
2470
- */
2471
-
2472
- request.post = function(url, data, fn){
2473
- var req = request('POST', url);
2474
- if ('function' == typeof data) fn = data, data = null;
2475
- if (data) req.send(data);
2476
- if (fn) req.end(fn);
2477
- return req;
2478
- };
2479
-
2480
- /**
2481
- * PUT `url` with optional `data` and callback `fn(res)`.
2482
- *
2483
- * @param {String} url
2484
- * @param {Mixed|Function} data or fn
2485
- * @param {Function} fn
2486
- * @return {Request}
2487
- * @api public
2488
- */
2489
-
2490
- request.put = function(url, data, fn){
2491
- var req = request('PUT', url);
2492
- if ('function' == typeof data) fn = data, data = null;
2493
- if (data) req.send(data);
2494
- if (fn) req.end(fn);
2495
- return req;
2496
- };
2497
-
2498
- /**
2499
- * Expose `request`.
2500
- */
2501
-
2502
- module.exports = request;
2503
-
2504
-
2505
- /***/ },
2506
- /* 2 */
2507
- /***/ function(module, exports, __webpack_require__) {
2508
-
2509
-
2510
- /**
2511
- * Expose `Emitter`.
2512
- */
2513
-
2514
- module.exports = Emitter;
2515
-
2516
- /**
2517
- * Initialize a new `Emitter`.
2518
- *
2519
- * @api public
2520
- */
2521
-
2522
- function Emitter(obj) {
2523
- if (obj) return mixin(obj);
2524
- };
2525
-
2526
- /**
2527
- * Mixin the emitter properties.
2528
- *
2529
- * @param {Object} obj
2530
- * @return {Object}
2531
- * @api private
2532
- */
2533
-
2534
- function mixin(obj) {
2535
- for (var key in Emitter.prototype) {
2536
- obj[key] = Emitter.prototype[key];
2537
- }
2538
- return obj;
2539
- }
2540
-
2541
- /**
2542
- * Listen on the given `event` with `fn`.
2543
- *
2544
- * @param {String} event
2545
- * @param {Function} fn
2546
- * @return {Emitter}
2547
- * @api public
2548
- */
2549
-
2550
- Emitter.prototype.on =
2551
- Emitter.prototype.addEventListener = function(event, fn){
2552
- this._callbacks = this._callbacks || {};
2553
- (this._callbacks[event] = this._callbacks[event] || [])
2554
- .push(fn);
2555
- return this;
2556
- };
2557
-
2558
- /**
2559
- * Adds an `event` listener that will be invoked a single
2560
- * time then automatically removed.
2561
- *
2562
- * @param {String} event
2563
- * @param {Function} fn
2564
- * @return {Emitter}
2565
- * @api public
2566
- */
2567
-
2568
- Emitter.prototype.once = function(event, fn){
2569
- var self = this;
2570
- this._callbacks = this._callbacks || {};
2571
-
2572
- function on() {
2573
- self.off(event, on);
2574
- fn.apply(this, arguments);
2575
- }
2576
-
2577
- on.fn = fn;
2578
- this.on(event, on);
2579
- return this;
2580
- };
2581
-
2582
- /**
2583
- * Remove the given callback for `event` or all
2584
- * registered callbacks.
2585
- *
2586
- * @param {String} event
2587
- * @param {Function} fn
2588
- * @return {Emitter}
2589
- * @api public
2590
- */
2591
-
2592
- Emitter.prototype.off =
2593
- Emitter.prototype.removeListener =
2594
- Emitter.prototype.removeAllListeners =
2595
- Emitter.prototype.removeEventListener = function(event, fn){
2596
- this._callbacks = this._callbacks || {};
2597
-
2598
- // all
2599
- if (0 == arguments.length) {
2600
- this._callbacks = {};
2601
- return this;
2602
- }
2603
-
2604
- // specific event
2605
- var callbacks = this._callbacks[event];
2606
- if (!callbacks) return this;
2607
-
2608
- // remove all handlers
2609
- if (1 == arguments.length) {
2610
- delete this._callbacks[event];
2611
- return this;
2612
- }
2613
-
2614
- // remove specific handler
2615
- var cb;
2616
- for (var i = 0; i < callbacks.length; i++) {
2617
- cb = callbacks[i];
2618
- if (cb === fn || cb.fn === fn) {
2619
- callbacks.splice(i, 1);
2620
- break;
2621
- }
2622
- }
2623
- return this;
2624
- };
2625
-
2626
- /**
2627
- * Emit `event` with the given args.
2628
- *
2629
- * @param {String} event
2630
- * @param {Mixed} ...
2631
- * @return {Emitter}
2632
- */
2633
-
2634
- Emitter.prototype.emit = function(event){
2635
- this._callbacks = this._callbacks || {};
2636
- var args = [].slice.call(arguments, 1)
2637
- , callbacks = this._callbacks[event];
2638
-
2639
- if (callbacks) {
2640
- callbacks = callbacks.slice(0);
2641
- for (var i = 0, len = callbacks.length; i < len; ++i) {
2642
- callbacks[i].apply(this, args);
2643
- }
2644
- }
2645
-
2646
- return this;
2647
- };
2648
-
2649
- /**
2650
- * Return array of callbacks for `event`.
2651
- *
2652
- * @param {String} event
2653
- * @return {Array}
2654
- * @api public
2655
- */
2656
-
2657
- Emitter.prototype.listeners = function(event){
2658
- this._callbacks = this._callbacks || {};
2659
- return this._callbacks[event] || [];
2660
- };
2661
-
2662
- /**
2663
- * Check if this emitter has `event` handlers.
2664
- *
2665
- * @param {String} event
2666
- * @return {Boolean}
2667
- * @api public
2668
- */
2669
-
2670
- Emitter.prototype.hasListeners = function(event){
2671
- return !! this.listeners(event).length;
2672
- };
2673
-
2674
-
2675
- /***/ },
2676
- /* 3 */
2677
- /***/ function(module, exports, __webpack_require__) {
2678
-
2679
-
2680
- /**
2681
- * Reduce `arr` with `fn`.
2682
- *
2683
- * @param {Array} arr
2684
- * @param {Function} fn
2685
- * @param {Mixed} initial
2686
- *
2687
- * TODO: combatible error handling?
2688
- */
2689
-
2690
- module.exports = function(arr, fn, initial){
2691
- var idx = 0;
2692
- var len = arr.length;
2693
- var curr = arguments.length == 3
2694
- ? initial
2695
- : arr[idx++];
2696
-
2697
- while (idx < len) {
2698
- curr = fn.call(null, curr, arr[idx], ++idx, arr);
2699
- }
2700
-
2701
- return curr;
2702
- };
2703
-
2704
- /***/ }
2705
- /******/ ])
2706
- });
2707
- ;
2708
- //# sourceMappingURL=clerk.js.map