pouchdb.authentication.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939
  1. (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.PouchAuthentication = 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){
  2. (function (process){
  3. 'use strict';
  4. var Promise = require(13);
  5. var urlJoin = require(16);
  6. function getBaseUrl(db) {
  7. if (typeof db.getUrl === 'function') { // pouchdb pre-6.0.0
  8. return db.getUrl().replace(/\/[^\/]+\/?$/, '');
  9. } else { // pouchdb post-6.0.0
  10. return db.name.replace(/\/[^\/]+\/?$/, '');
  11. }
  12. }
  13. exports.getUsersUrl = function (db) {
  14. return urlJoin(getBaseUrl(db), '/_users');
  15. };
  16. exports.getSessionUrl = function (db) {
  17. return urlJoin(getBaseUrl(db), '/_session');
  18. };
  19. exports.once = function (fun) {
  20. var called = false;
  21. return exports.getArguments(function (args) {
  22. if (called) {
  23. console.trace();
  24. throw new Error('once called more than once');
  25. } else {
  26. called = true;
  27. fun.apply(this, args);
  28. }
  29. });
  30. };
  31. exports.getArguments = function (fun) {
  32. return function () {
  33. var len = arguments.length;
  34. var args = new Array(len);
  35. var i = -1;
  36. while (++i < len) {
  37. args[i] = arguments[i];
  38. }
  39. return fun.call(this, args);
  40. };
  41. };
  42. exports.toPromise = function (func) {
  43. //create the function we will be returning
  44. return exports.getArguments(function (args) {
  45. var self = this;
  46. var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
  47. // if the last argument is a function, assume its a callback
  48. var usedCB;
  49. if (tempCB) {
  50. // if it was a callback, create a new callback which calls it,
  51. // but do so async so we don't trap any errors
  52. usedCB = function (err, resp) {
  53. process.nextTick(function () {
  54. tempCB(err, resp);
  55. });
  56. };
  57. }
  58. var promise = new Promise(function (fulfill, reject) {
  59. try {
  60. var callback = exports.once(function (err, mesg) {
  61. if (err) {
  62. reject(err);
  63. } else {
  64. fulfill(mesg);
  65. }
  66. });
  67. // create a callback for this invocation
  68. // apply the function in the orig context
  69. args.push(callback);
  70. func.apply(self, args);
  71. } catch (e) {
  72. reject(e);
  73. }
  74. });
  75. // if there is a callback, call it back
  76. if (usedCB) {
  77. promise.then(function (result) {
  78. usedCB(null, result);
  79. }, usedCB);
  80. }
  81. promise.cancel = function () {
  82. return this;
  83. };
  84. return promise;
  85. });
  86. };
  87. exports.inherits = require(7);
  88. exports.extend = require(12);
  89. exports.ajax = require(11);
  90. exports.clone = function (obj) {
  91. return exports.extend(true, {}, obj);
  92. };
  93. exports.uuid = require(14).uuid;
  94. exports.Promise = Promise;
  95. }).call(this,require(15))
  96. },{"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"7":7}],2:[function(require,module,exports){
  97. 'use strict';
  98. module.exports = argsArray;
  99. function argsArray(fun) {
  100. return function () {
  101. var len = arguments.length;
  102. if (len) {
  103. var args = [];
  104. var i = -1;
  105. while (++i < len) {
  106. args[i] = arguments[i];
  107. }
  108. return fun.call(this, args);
  109. } else {
  110. return fun.call(this, []);
  111. }
  112. };
  113. }
  114. },{}],3:[function(require,module,exports){
  115. /**
  116. * This is the web browser implementation of `debug()`.
  117. *
  118. * Expose `debug()` as the module.
  119. */
  120. exports = module.exports = require(4);
  121. exports.log = log;
  122. exports.formatArgs = formatArgs;
  123. exports.save = save;
  124. exports.load = load;
  125. exports.useColors = useColors;
  126. exports.storage = 'undefined' != typeof chrome
  127. && 'undefined' != typeof chrome.storage
  128. ? chrome.storage.local
  129. : localstorage();
  130. /**
  131. * Colors.
  132. */
  133. exports.colors = [
  134. 'lightseagreen',
  135. 'forestgreen',
  136. 'goldenrod',
  137. 'dodgerblue',
  138. 'darkorchid',
  139. 'crimson'
  140. ];
  141. /**
  142. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  143. * and the Firebug extension (any Firefox version) are known
  144. * to support "%c" CSS customizations.
  145. *
  146. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  147. */
  148. function useColors() {
  149. // is webkit? http://stackoverflow.com/a/16459606/376773
  150. return ('WebkitAppearance' in document.documentElement.style) ||
  151. // is firebug? http://stackoverflow.com/a/398120/376773
  152. (window.console && (console.firebug || (console.exception && console.table))) ||
  153. // is firefox >= v31?
  154. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  155. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  156. }
  157. /**
  158. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  159. */
  160. exports.formatters.j = function(v) {
  161. return JSON.stringify(v);
  162. };
  163. /**
  164. * Colorize log arguments if enabled.
  165. *
  166. * @api public
  167. */
  168. function formatArgs() {
  169. var args = arguments;
  170. var useColors = this.useColors;
  171. args[0] = (useColors ? '%c' : '')
  172. + this.namespace
  173. + (useColors ? ' %c' : ' ')
  174. + args[0]
  175. + (useColors ? '%c ' : ' ')
  176. + '+' + exports.humanize(this.diff);
  177. if (!useColors) return args;
  178. var c = 'color: ' + this.color;
  179. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  180. // the final "%c" is somewhat tricky, because there could be other
  181. // arguments passed either before or after the %c, so we need to
  182. // figure out the correct index to insert the CSS into
  183. var index = 0;
  184. var lastC = 0;
  185. args[0].replace(/%[a-z%]/g, function(match) {
  186. if ('%%' === match) return;
  187. index++;
  188. if ('%c' === match) {
  189. // we only are interested in the *last* %c
  190. // (the user may have provided their own)
  191. lastC = index;
  192. }
  193. });
  194. args.splice(lastC, 0, c);
  195. return args;
  196. }
  197. /**
  198. * Invokes `console.log()` when available.
  199. * No-op when `console.log` is not a "function".
  200. *
  201. * @api public
  202. */
  203. function log() {
  204. // this hackery is required for IE8/9, where
  205. // the `console.log` function doesn't have 'apply'
  206. return 'object' === typeof console
  207. && console.log
  208. && Function.prototype.apply.call(console.log, console, arguments);
  209. }
  210. /**
  211. * Save `namespaces`.
  212. *
  213. * @param {String} namespaces
  214. * @api private
  215. */
  216. function save(namespaces) {
  217. try {
  218. if (null == namespaces) {
  219. exports.storage.removeItem('debug');
  220. } else {
  221. exports.storage.debug = namespaces;
  222. }
  223. } catch(e) {}
  224. }
  225. /**
  226. * Load `namespaces`.
  227. *
  228. * @return {String} returns the previously persisted debug modes
  229. * @api private
  230. */
  231. function load() {
  232. var r;
  233. try {
  234. r = exports.storage.debug;
  235. } catch(e) {}
  236. return r;
  237. }
  238. /**
  239. * Enable namespaces listed in `localStorage.debug` initially.
  240. */
  241. exports.enable(load());
  242. /**
  243. * Localstorage attempts to return the localstorage.
  244. *
  245. * This is necessary because safari throws
  246. * when a user disables cookies/localstorage
  247. * and you attempt to access it.
  248. *
  249. * @return {LocalStorage}
  250. * @api private
  251. */
  252. function localstorage(){
  253. try {
  254. return window.localStorage;
  255. } catch (e) {}
  256. }
  257. },{"4":4}],4:[function(require,module,exports){
  258. /**
  259. * This is the common logic for both the Node.js and web browser
  260. * implementations of `debug()`.
  261. *
  262. * Expose `debug()` as the module.
  263. */
  264. exports = module.exports = debug;
  265. exports.coerce = coerce;
  266. exports.disable = disable;
  267. exports.enable = enable;
  268. exports.enabled = enabled;
  269. exports.humanize = require(10);
  270. /**
  271. * The currently active debug mode names, and names to skip.
  272. */
  273. exports.names = [];
  274. exports.skips = [];
  275. /**
  276. * Map of special "%n" handling functions, for the debug "format" argument.
  277. *
  278. * Valid key names are a single, lowercased letter, i.e. "n".
  279. */
  280. exports.formatters = {};
  281. /**
  282. * Previously assigned color.
  283. */
  284. var prevColor = 0;
  285. /**
  286. * Previous log timestamp.
  287. */
  288. var prevTime;
  289. /**
  290. * Select a color.
  291. *
  292. * @return {Number}
  293. * @api private
  294. */
  295. function selectColor() {
  296. return exports.colors[prevColor++ % exports.colors.length];
  297. }
  298. /**
  299. * Create a debugger with the given `namespace`.
  300. *
  301. * @param {String} namespace
  302. * @return {Function}
  303. * @api public
  304. */
  305. function debug(namespace) {
  306. // define the `disabled` version
  307. function disabled() {
  308. }
  309. disabled.enabled = false;
  310. // define the `enabled` version
  311. function enabled() {
  312. var self = enabled;
  313. // set `diff` timestamp
  314. var curr = +new Date();
  315. var ms = curr - (prevTime || curr);
  316. self.diff = ms;
  317. self.prev = prevTime;
  318. self.curr = curr;
  319. prevTime = curr;
  320. // add the `color` if not set
  321. if (null == self.useColors) self.useColors = exports.useColors();
  322. if (null == self.color && self.useColors) self.color = selectColor();
  323. var args = Array.prototype.slice.call(arguments);
  324. args[0] = exports.coerce(args[0]);
  325. if ('string' !== typeof args[0]) {
  326. // anything else let's inspect with %o
  327. args = ['%o'].concat(args);
  328. }
  329. // apply any `formatters` transformations
  330. var index = 0;
  331. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  332. // if we encounter an escaped % then don't increase the array index
  333. if (match === '%%') return match;
  334. index++;
  335. var formatter = exports.formatters[format];
  336. if ('function' === typeof formatter) {
  337. var val = args[index];
  338. match = formatter.call(self, val);
  339. // now we need to remove `args[index]` since it's inlined in the `format`
  340. args.splice(index, 1);
  341. index--;
  342. }
  343. return match;
  344. });
  345. if ('function' === typeof exports.formatArgs) {
  346. args = exports.formatArgs.apply(self, args);
  347. }
  348. var logFn = enabled.log || exports.log || console.log.bind(console);
  349. logFn.apply(self, args);
  350. }
  351. enabled.enabled = true;
  352. var fn = exports.enabled(namespace) ? enabled : disabled;
  353. fn.namespace = namespace;
  354. return fn;
  355. }
  356. /**
  357. * Enables a debug mode by namespaces. This can include modes
  358. * separated by a colon and wildcards.
  359. *
  360. * @param {String} namespaces
  361. * @api public
  362. */
  363. function enable(namespaces) {
  364. exports.save(namespaces);
  365. var split = (namespaces || '').split(/[\s,]+/);
  366. var len = split.length;
  367. for (var i = 0; i < len; i++) {
  368. if (!split[i]) continue; // ignore empty strings
  369. namespaces = split[i].replace(/\*/g, '.*?');
  370. if (namespaces[0] === '-') {
  371. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  372. } else {
  373. exports.names.push(new RegExp('^' + namespaces + '$'));
  374. }
  375. }
  376. }
  377. /**
  378. * Disable debug output.
  379. *
  380. * @api public
  381. */
  382. function disable() {
  383. exports.enable('');
  384. }
  385. /**
  386. * Returns true if the given mode name is enabled, false otherwise.
  387. *
  388. * @param {String} name
  389. * @return {Boolean}
  390. * @api public
  391. */
  392. function enabled(name) {
  393. var i, len;
  394. for (i = 0, len = exports.skips.length; i < len; i++) {
  395. if (exports.skips[i].test(name)) {
  396. return false;
  397. }
  398. }
  399. for (i = 0, len = exports.names.length; i < len; i++) {
  400. if (exports.names[i].test(name)) {
  401. return true;
  402. }
  403. }
  404. return false;
  405. }
  406. /**
  407. * Coerce `val`.
  408. *
  409. * @param {Mixed} val
  410. * @return {Mixed}
  411. * @api private
  412. */
  413. function coerce(val) {
  414. if (val instanceof Error) return val.stack || val.message;
  415. return val;
  416. }
  417. },{"10":10}],5:[function(require,module,exports){
  418. // Copyright Joyent, Inc. and other Node contributors.
  419. //
  420. // Permission is hereby granted, free of charge, to any person obtaining a
  421. // copy of this software and associated documentation files (the
  422. // "Software"), to deal in the Software without restriction, including
  423. // without limitation the rights to use, copy, modify, merge, publish,
  424. // distribute, sublicense, and/or sell copies of the Software, and to permit
  425. // persons to whom the Software is furnished to do so, subject to the
  426. // following conditions:
  427. //
  428. // The above copyright notice and this permission notice shall be included
  429. // in all copies or substantial portions of the Software.
  430. //
  431. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  432. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  433. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  434. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  435. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  436. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  437. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  438. function EventEmitter() {
  439. this._events = this._events || {};
  440. this._maxListeners = this._maxListeners || undefined;
  441. }
  442. module.exports = EventEmitter;
  443. // Backwards-compat with node 0.10.x
  444. EventEmitter.EventEmitter = EventEmitter;
  445. EventEmitter.prototype._events = undefined;
  446. EventEmitter.prototype._maxListeners = undefined;
  447. // By default EventEmitters will print a warning if more than 10 listeners are
  448. // added to it. This is a useful default which helps finding memory leaks.
  449. EventEmitter.defaultMaxListeners = 10;
  450. // Obviously not all Emitters should be limited to 10. This function allows
  451. // that to be increased. Set to zero for unlimited.
  452. EventEmitter.prototype.setMaxListeners = function(n) {
  453. if (!isNumber(n) || n < 0 || isNaN(n))
  454. throw TypeError('n must be a positive number');
  455. this._maxListeners = n;
  456. return this;
  457. };
  458. EventEmitter.prototype.emit = function(type) {
  459. var er, handler, len, args, i, listeners;
  460. if (!this._events)
  461. this._events = {};
  462. // If there is no 'error' event listener then throw.
  463. if (type === 'error') {
  464. if (!this._events.error ||
  465. (isObject(this._events.error) && !this._events.error.length)) {
  466. er = arguments[1];
  467. if (er instanceof Error) {
  468. throw er; // Unhandled 'error' event
  469. } else {
  470. // At least give some kind of context to the user
  471. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  472. err.context = er;
  473. throw err;
  474. }
  475. }
  476. }
  477. handler = this._events[type];
  478. if (isUndefined(handler))
  479. return false;
  480. if (isFunction(handler)) {
  481. switch (arguments.length) {
  482. // fast cases
  483. case 1:
  484. handler.call(this);
  485. break;
  486. case 2:
  487. handler.call(this, arguments[1]);
  488. break;
  489. case 3:
  490. handler.call(this, arguments[1], arguments[2]);
  491. break;
  492. // slower
  493. default:
  494. args = Array.prototype.slice.call(arguments, 1);
  495. handler.apply(this, args);
  496. }
  497. } else if (isObject(handler)) {
  498. args = Array.prototype.slice.call(arguments, 1);
  499. listeners = handler.slice();
  500. len = listeners.length;
  501. for (i = 0; i < len; i++)
  502. listeners[i].apply(this, args);
  503. }
  504. return true;
  505. };
  506. EventEmitter.prototype.addListener = function(type, listener) {
  507. var m;
  508. if (!isFunction(listener))
  509. throw TypeError('listener must be a function');
  510. if (!this._events)
  511. this._events = {};
  512. // To avoid recursion in the case that type === "newListener"! Before
  513. // adding it to the listeners, first emit "newListener".
  514. if (this._events.newListener)
  515. this.emit('newListener', type,
  516. isFunction(listener.listener) ?
  517. listener.listener : listener);
  518. if (!this._events[type])
  519. // Optimize the case of one listener. Don't need the extra array object.
  520. this._events[type] = listener;
  521. else if (isObject(this._events[type]))
  522. // If we've already got an array, just append.
  523. this._events[type].push(listener);
  524. else
  525. // Adding the second element, need to change to array.
  526. this._events[type] = [this._events[type], listener];
  527. // Check for listener leak
  528. if (isObject(this._events[type]) && !this._events[type].warned) {
  529. if (!isUndefined(this._maxListeners)) {
  530. m = this._maxListeners;
  531. } else {
  532. m = EventEmitter.defaultMaxListeners;
  533. }
  534. if (m && m > 0 && this._events[type].length > m) {
  535. this._events[type].warned = true;
  536. console.error('(node) warning: possible EventEmitter memory ' +
  537. 'leak detected. %d listeners added. ' +
  538. 'Use emitter.setMaxListeners() to increase limit.',
  539. this._events[type].length);
  540. if (typeof console.trace === 'function') {
  541. // not supported in IE 10
  542. console.trace();
  543. }
  544. }
  545. }
  546. return this;
  547. };
  548. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  549. EventEmitter.prototype.once = function(type, listener) {
  550. if (!isFunction(listener))
  551. throw TypeError('listener must be a function');
  552. var fired = false;
  553. function g() {
  554. this.removeListener(type, g);
  555. if (!fired) {
  556. fired = true;
  557. listener.apply(this, arguments);
  558. }
  559. }
  560. g.listener = listener;
  561. this.on(type, g);
  562. return this;
  563. };
  564. // emits a 'removeListener' event iff the listener was removed
  565. EventEmitter.prototype.removeListener = function(type, listener) {
  566. var list, position, length, i;
  567. if (!isFunction(listener))
  568. throw TypeError('listener must be a function');
  569. if (!this._events || !this._events[type])
  570. return this;
  571. list = this._events[type];
  572. length = list.length;
  573. position = -1;
  574. if (list === listener ||
  575. (isFunction(list.listener) && list.listener === listener)) {
  576. delete this._events[type];
  577. if (this._events.removeListener)
  578. this.emit('removeListener', type, listener);
  579. } else if (isObject(list)) {
  580. for (i = length; i-- > 0;) {
  581. if (list[i] === listener ||
  582. (list[i].listener && list[i].listener === listener)) {
  583. position = i;
  584. break;
  585. }
  586. }
  587. if (position < 0)
  588. return this;
  589. if (list.length === 1) {
  590. list.length = 0;
  591. delete this._events[type];
  592. } else {
  593. list.splice(position, 1);
  594. }
  595. if (this._events.removeListener)
  596. this.emit('removeListener', type, listener);
  597. }
  598. return this;
  599. };
  600. EventEmitter.prototype.removeAllListeners = function(type) {
  601. var key, listeners;
  602. if (!this._events)
  603. return this;
  604. // not listening for removeListener, no need to emit
  605. if (!this._events.removeListener) {
  606. if (arguments.length === 0)
  607. this._events = {};
  608. else if (this._events[type])
  609. delete this._events[type];
  610. return this;
  611. }
  612. // emit removeListener for all listeners on all events
  613. if (arguments.length === 0) {
  614. for (key in this._events) {
  615. if (key === 'removeListener') continue;
  616. this.removeAllListeners(key);
  617. }
  618. this.removeAllListeners('removeListener');
  619. this._events = {};
  620. return this;
  621. }
  622. listeners = this._events[type];
  623. if (isFunction(listeners)) {
  624. this.removeListener(type, listeners);
  625. } else if (listeners) {
  626. // LIFO order
  627. while (listeners.length)
  628. this.removeListener(type, listeners[listeners.length - 1]);
  629. }
  630. delete this._events[type];
  631. return this;
  632. };
  633. EventEmitter.prototype.listeners = function(type) {
  634. var ret;
  635. if (!this._events || !this._events[type])
  636. ret = [];
  637. else if (isFunction(this._events[type]))
  638. ret = [this._events[type]];
  639. else
  640. ret = this._events[type].slice();
  641. return ret;
  642. };
  643. EventEmitter.prototype.listenerCount = function(type) {
  644. if (this._events) {
  645. var evlistener = this._events[type];
  646. if (isFunction(evlistener))
  647. return 1;
  648. else if (evlistener)
  649. return evlistener.length;
  650. }
  651. return 0;
  652. };
  653. EventEmitter.listenerCount = function(emitter, type) {
  654. return emitter.listenerCount(type);
  655. };
  656. function isFunction(arg) {
  657. return typeof arg === 'function';
  658. }
  659. function isNumber(arg) {
  660. return typeof arg === 'number';
  661. }
  662. function isObject(arg) {
  663. return typeof arg === 'object' && arg !== null;
  664. }
  665. function isUndefined(arg) {
  666. return arg === void 0;
  667. }
  668. },{}],6:[function(require,module,exports){
  669. (function (global){
  670. 'use strict';
  671. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  672. var scheduleDrain;
  673. {
  674. if (Mutation) {
  675. var called = 0;
  676. var observer = new Mutation(nextTick);
  677. var element = global.document.createTextNode('');
  678. observer.observe(element, {
  679. characterData: true
  680. });
  681. scheduleDrain = function () {
  682. element.data = (called = ++called % 2);
  683. };
  684. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  685. var channel = new global.MessageChannel();
  686. channel.port1.onmessage = nextTick;
  687. scheduleDrain = function () {
  688. channel.port2.postMessage(0);
  689. };
  690. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  691. scheduleDrain = function () {
  692. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  693. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  694. var scriptEl = global.document.createElement('script');
  695. scriptEl.onreadystatechange = function () {
  696. nextTick();
  697. scriptEl.onreadystatechange = null;
  698. scriptEl.parentNode.removeChild(scriptEl);
  699. scriptEl = null;
  700. };
  701. global.document.documentElement.appendChild(scriptEl);
  702. };
  703. } else {
  704. scheduleDrain = function () {
  705. setTimeout(nextTick, 0);
  706. };
  707. }
  708. }
  709. var draining;
  710. var queue = [];
  711. //named nextTick for less confusing stack traces
  712. function nextTick() {
  713. draining = true;
  714. var i, oldQueue;
  715. var len = queue.length;
  716. while (len) {
  717. oldQueue = queue;
  718. queue = [];
  719. i = -1;
  720. while (++i < len) {
  721. oldQueue[i]();
  722. }
  723. len = queue.length;
  724. }
  725. draining = false;
  726. }
  727. module.exports = immediate;
  728. function immediate(task) {
  729. if (queue.push(task) === 1 && !draining) {
  730. scheduleDrain();
  731. }
  732. }
  733. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  734. },{}],7:[function(require,module,exports){
  735. if (typeof Object.create === 'function') {
  736. // implementation from standard node.js 'util' module
  737. module.exports = function inherits(ctor, superCtor) {
  738. ctor.super_ = superCtor
  739. ctor.prototype = Object.create(superCtor.prototype, {
  740. constructor: {
  741. value: ctor,
  742. enumerable: false,
  743. writable: true,
  744. configurable: true
  745. }
  746. });
  747. };
  748. } else {
  749. // old school shim for old browsers
  750. module.exports = function inherits(ctor, superCtor) {
  751. ctor.super_ = superCtor
  752. var TempCtor = function () {}
  753. TempCtor.prototype = superCtor.prototype
  754. ctor.prototype = new TempCtor()
  755. ctor.prototype.constructor = ctor
  756. }
  757. }
  758. },{}],8:[function(require,module,exports){
  759. (function(factory) {
  760. if(typeof exports === 'object') {
  761. factory(exports);
  762. } else {
  763. factory(this);
  764. }
  765. }).call(this, function(root) {
  766. var slice = Array.prototype.slice,
  767. each = Array.prototype.forEach;
  768. var extend = function(obj) {
  769. if(typeof obj !== 'object') throw obj + ' is not an object' ;
  770. var sources = slice.call(arguments, 1);
  771. each.call(sources, function(source) {
  772. if(source) {
  773. for(var prop in source) {
  774. if(typeof source[prop] === 'object' && obj[prop]) {
  775. extend.call(obj, obj[prop], source[prop]);
  776. } else {
  777. obj[prop] = source[prop];
  778. }
  779. }
  780. }
  781. });
  782. return obj;
  783. }
  784. root.extend = extend;
  785. });
  786. },{}],9:[function(require,module,exports){
  787. 'use strict';
  788. var immediate = require(6);
  789. /* istanbul ignore next */
  790. function INTERNAL() {}
  791. var handlers = {};
  792. var REJECTED = ['REJECTED'];
  793. var FULFILLED = ['FULFILLED'];
  794. var PENDING = ['PENDING'];
  795. module.exports = Promise;
  796. function Promise(resolver) {
  797. if (typeof resolver !== 'function') {
  798. throw new TypeError('resolver must be a function');
  799. }
  800. this.state = PENDING;
  801. this.queue = [];
  802. this.outcome = void 0;
  803. if (resolver !== INTERNAL) {
  804. safelyResolveThenable(this, resolver);
  805. }
  806. }
  807. Promise.prototype["catch"] = function (onRejected) {
  808. return this.then(null, onRejected);
  809. };
  810. Promise.prototype.then = function (onFulfilled, onRejected) {
  811. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  812. typeof onRejected !== 'function' && this.state === REJECTED) {
  813. return this;
  814. }
  815. var promise = new this.constructor(INTERNAL);
  816. if (this.state !== PENDING) {
  817. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  818. unwrap(promise, resolver, this.outcome);
  819. } else {
  820. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  821. }
  822. return promise;
  823. };
  824. function QueueItem(promise, onFulfilled, onRejected) {
  825. this.promise = promise;
  826. if (typeof onFulfilled === 'function') {
  827. this.onFulfilled = onFulfilled;
  828. this.callFulfilled = this.otherCallFulfilled;
  829. }
  830. if (typeof onRejected === 'function') {
  831. this.onRejected = onRejected;
  832. this.callRejected = this.otherCallRejected;
  833. }
  834. }
  835. QueueItem.prototype.callFulfilled = function (value) {
  836. handlers.resolve(this.promise, value);
  837. };
  838. QueueItem.prototype.otherCallFulfilled = function (value) {
  839. unwrap(this.promise, this.onFulfilled, value);
  840. };
  841. QueueItem.prototype.callRejected = function (value) {
  842. handlers.reject(this.promise, value);
  843. };
  844. QueueItem.prototype.otherCallRejected = function (value) {
  845. unwrap(this.promise, this.onRejected, value);
  846. };
  847. function unwrap(promise, func, value) {
  848. immediate(function () {
  849. var returnValue;
  850. try {
  851. returnValue = func(value);
  852. } catch (e) {
  853. return handlers.reject(promise, e);
  854. }
  855. if (returnValue === promise) {
  856. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  857. } else {
  858. handlers.resolve(promise, returnValue);
  859. }
  860. });
  861. }
  862. handlers.resolve = function (self, value) {
  863. var result = tryCatch(getThen, value);
  864. if (result.status === 'error') {
  865. return handlers.reject(self, result.value);
  866. }
  867. var thenable = result.value;
  868. if (thenable) {
  869. safelyResolveThenable(self, thenable);
  870. } else {
  871. self.state = FULFILLED;
  872. self.outcome = value;
  873. var i = -1;
  874. var len = self.queue.length;
  875. while (++i < len) {
  876. self.queue[i].callFulfilled(value);
  877. }
  878. }
  879. return self;
  880. };
  881. handlers.reject = function (self, error) {
  882. self.state = REJECTED;
  883. self.outcome = error;
  884. var i = -1;
  885. var len = self.queue.length;
  886. while (++i < len) {
  887. self.queue[i].callRejected(error);
  888. }
  889. return self;
  890. };
  891. function getThen(obj) {
  892. // Make sure we only access the accessor once as required by the spec
  893. var then = obj && obj.then;
  894. if (obj && typeof obj === 'object' && typeof then === 'function') {
  895. return function appyThen() {
  896. then.apply(obj, arguments);
  897. };
  898. }
  899. }
  900. function safelyResolveThenable(self, thenable) {
  901. // Either fulfill, reject or reject with error
  902. var called = false;
  903. function onError(value) {
  904. if (called) {
  905. return;
  906. }
  907. called = true;
  908. handlers.reject(self, value);
  909. }
  910. function onSuccess(value) {
  911. if (called) {
  912. return;
  913. }
  914. called = true;
  915. handlers.resolve(self, value);
  916. }
  917. function tryToUnwrap() {
  918. thenable(onSuccess, onError);
  919. }
  920. var result = tryCatch(tryToUnwrap);
  921. if (result.status === 'error') {
  922. onError(result.value);
  923. }
  924. }
  925. function tryCatch(func, value) {
  926. var out = {};
  927. try {
  928. out.value = func(value);
  929. out.status = 'success';
  930. } catch (e) {
  931. out.status = 'error';
  932. out.value = e;
  933. }
  934. return out;
  935. }
  936. Promise.resolve = resolve;
  937. function resolve(value) {
  938. if (value instanceof this) {
  939. return value;
  940. }
  941. return handlers.resolve(new this(INTERNAL), value);
  942. }
  943. Promise.reject = reject;
  944. function reject(reason) {
  945. var promise = new this(INTERNAL);
  946. return handlers.reject(promise, reason);
  947. }
  948. Promise.all = all;
  949. function all(iterable) {
  950. var self = this;
  951. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  952. return this.reject(new TypeError('must be an array'));
  953. }
  954. var len = iterable.length;
  955. var called = false;
  956. if (!len) {
  957. return this.resolve([]);
  958. }
  959. var values = new Array(len);
  960. var resolved = 0;
  961. var i = -1;
  962. var promise = new this(INTERNAL);
  963. while (++i < len) {
  964. allResolver(iterable[i], i);
  965. }
  966. return promise;
  967. function allResolver(value, i) {
  968. self.resolve(value).then(resolveFromAll, function (error) {
  969. if (!called) {
  970. called = true;
  971. handlers.reject(promise, error);
  972. }
  973. });
  974. function resolveFromAll(outValue) {
  975. values[i] = outValue;
  976. if (++resolved === len && !called) {
  977. called = true;
  978. handlers.resolve(promise, values);
  979. }
  980. }
  981. }
  982. }
  983. Promise.race = race;
  984. function race(iterable) {
  985. var self = this;
  986. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  987. return this.reject(new TypeError('must be an array'));
  988. }
  989. var len = iterable.length;
  990. var called = false;
  991. if (!len) {
  992. return this.resolve([]);
  993. }
  994. var i = -1;
  995. var promise = new this(INTERNAL);
  996. while (++i < len) {
  997. resolver(iterable[i]);
  998. }
  999. return promise;
  1000. function resolver(value) {
  1001. self.resolve(value).then(function (response) {
  1002. if (!called) {
  1003. called = true;
  1004. handlers.resolve(promise, response);
  1005. }
  1006. }, function (error) {
  1007. if (!called) {
  1008. called = true;
  1009. handlers.reject(promise, error);
  1010. }
  1011. });
  1012. }
  1013. }
  1014. },{"6":6}],10:[function(require,module,exports){
  1015. /**
  1016. * Helpers.
  1017. */
  1018. var s = 1000;
  1019. var m = s * 60;
  1020. var h = m * 60;
  1021. var d = h * 24;
  1022. var y = d * 365.25;
  1023. /**
  1024. * Parse or format the given `val`.
  1025. *
  1026. * Options:
  1027. *
  1028. * - `long` verbose formatting [false]
  1029. *
  1030. * @param {String|Number} val
  1031. * @param {Object} options
  1032. * @return {String|Number}
  1033. * @api public
  1034. */
  1035. module.exports = function(val, options){
  1036. options = options || {};
  1037. if ('string' == typeof val) return parse(val);
  1038. return options.long
  1039. ? long(val)
  1040. : short(val);
  1041. };
  1042. /**
  1043. * Parse the given `str` and return milliseconds.
  1044. *
  1045. * @param {String} str
  1046. * @return {Number}
  1047. * @api private
  1048. */
  1049. function parse(str) {
  1050. str = '' + str;
  1051. if (str.length > 10000) return;
  1052. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  1053. if (!match) return;
  1054. var n = parseFloat(match[1]);
  1055. var type = (match[2] || 'ms').toLowerCase();
  1056. switch (type) {
  1057. case 'years':
  1058. case 'year':
  1059. case 'yrs':
  1060. case 'yr':
  1061. case 'y':
  1062. return n * y;
  1063. case 'days':
  1064. case 'day':
  1065. case 'd':
  1066. return n * d;
  1067. case 'hours':
  1068. case 'hour':
  1069. case 'hrs':
  1070. case 'hr':
  1071. case 'h':
  1072. return n * h;
  1073. case 'minutes':
  1074. case 'minute':
  1075. case 'mins':
  1076. case 'min':
  1077. case 'm':
  1078. return n * m;
  1079. case 'seconds':
  1080. case 'second':
  1081. case 'secs':
  1082. case 'sec':
  1083. case 's':
  1084. return n * s;
  1085. case 'milliseconds':
  1086. case 'millisecond':
  1087. case 'msecs':
  1088. case 'msec':
  1089. case 'ms':
  1090. return n;
  1091. }
  1092. }
  1093. /**
  1094. * Short format for `ms`.
  1095. *
  1096. * @param {Number} ms
  1097. * @return {String}
  1098. * @api private
  1099. */
  1100. function short(ms) {
  1101. if (ms >= d) return Math.round(ms / d) + 'd';
  1102. if (ms >= h) return Math.round(ms / h) + 'h';
  1103. if (ms >= m) return Math.round(ms / m) + 'm';
  1104. if (ms >= s) return Math.round(ms / s) + 's';
  1105. return ms + 'ms';
  1106. }
  1107. /**
  1108. * Long format for `ms`.
  1109. *
  1110. * @param {Number} ms
  1111. * @return {String}
  1112. * @api private
  1113. */
  1114. function long(ms) {
  1115. return plural(ms, d, 'day')
  1116. || plural(ms, h, 'hour')
  1117. || plural(ms, m, 'minute')
  1118. || plural(ms, s, 'second')
  1119. || ms + ' ms';
  1120. }
  1121. /**
  1122. * Pluralization helper.
  1123. */
  1124. function plural(ms, n, name) {
  1125. if (ms < n) return;
  1126. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  1127. return Math.ceil(ms / n) + ' ' + name + 's';
  1128. }
  1129. },{}],11:[function(require,module,exports){
  1130. 'use strict';
  1131. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  1132. var lie = _interopDefault(require(9));
  1133. var jsExtend = require(8);
  1134. var inherits = _interopDefault(require(7));
  1135. var getArguments = _interopDefault(require(2));
  1136. var debug = _interopDefault(require(3));
  1137. var events = require(5);
  1138. // Abstracts constructing a Blob object, so it also works in older
  1139. // browsers that don't support the native Blob constructor (e.g.
  1140. // old QtWebKit versions, Android < 4.4).
  1141. function createBlob(parts, properties) {
  1142. /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  1143. parts = parts || [];
  1144. properties = properties || {};
  1145. try {
  1146. return new Blob(parts, properties);
  1147. } catch (e) {
  1148. if (e.name !== "TypeError") {
  1149. throw e;
  1150. }
  1151. var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
  1152. typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
  1153. typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
  1154. WebKitBlobBuilder;
  1155. var builder = new Builder();
  1156. for (var i = 0; i < parts.length; i += 1) {
  1157. builder.append(parts[i]);
  1158. }
  1159. return builder.getBlob(properties.type);
  1160. }
  1161. }
  1162. // simplified API. universal browser support is assumed
  1163. function readAsArrayBuffer(blob, callback) {
  1164. if (typeof FileReader === 'undefined') {
  1165. // fix for Firefox in a web worker:
  1166. // https://bugzilla.mozilla.org/show_bug.cgi?id=901097
  1167. return callback(new FileReaderSync().readAsArrayBuffer(blob));
  1168. }
  1169. var reader = new FileReader();
  1170. reader.onloadend = function (e) {
  1171. var result = e.target.result || new ArrayBuffer(0);
  1172. callback(result);
  1173. };
  1174. reader.readAsArrayBuffer(blob);
  1175. }
  1176. /* istanbul ignore next */
  1177. var PouchPromise = typeof Promise === 'function' ? Promise : lie;
  1178. /* global fetch */
  1179. /* global Headers */
  1180. function wrappedFetch() {
  1181. var wrappedPromise = {};
  1182. var promise = new PouchPromise(function (resolve, reject) {
  1183. wrappedPromise.resolve = resolve;
  1184. wrappedPromise.reject = reject;
  1185. });
  1186. var args = new Array(arguments.length);
  1187. for (var i = 0; i < args.length; i++) {
  1188. args[i] = arguments[i];
  1189. }
  1190. wrappedPromise.promise = promise;
  1191. PouchPromise.resolve().then(function () {
  1192. return fetch.apply(null, args);
  1193. }).then(function (response) {
  1194. wrappedPromise.resolve(response);
  1195. }).catch(function (error) {
  1196. wrappedPromise.reject(error);
  1197. });
  1198. return wrappedPromise;
  1199. }
  1200. function fetchRequest(options, callback) {
  1201. var wrappedPromise, timer, response;
  1202. var headers = new Headers();
  1203. var fetchOptions = {
  1204. method: options.method,
  1205. credentials: 'include',
  1206. headers: headers
  1207. };
  1208. if (options.json) {
  1209. headers.set('Accept', 'application/json');
  1210. headers.set('Content-Type', options.headers['Content-Type'] ||
  1211. 'application/json');
  1212. }
  1213. if (options.body && (options.body instanceof Blob)) {
  1214. readAsArrayBuffer(options.body, function (arrayBuffer) {
  1215. fetchOptions.body = arrayBuffer;
  1216. });
  1217. } else if (options.body &&
  1218. options.processData &&
  1219. typeof options.body !== 'string') {
  1220. fetchOptions.body = JSON.stringify(options.body);
  1221. } else if ('body' in options) {
  1222. fetchOptions.body = options.body;
  1223. } else {
  1224. fetchOptions.body = null;
  1225. }
  1226. Object.keys(options.headers).forEach(function (key) {
  1227. if (options.headers.hasOwnProperty(key)) {
  1228. headers.set(key, options.headers[key]);
  1229. }
  1230. });
  1231. wrappedPromise = wrappedFetch(options.url, fetchOptions);
  1232. if (options.timeout > 0) {
  1233. timer = setTimeout(function () {
  1234. wrappedPromise.reject(new Error('Load timeout for resource: ' +
  1235. options.url));
  1236. }, options.timeout);
  1237. }
  1238. wrappedPromise.promise.then(function (fetchResponse) {
  1239. response = {
  1240. statusCode: fetchResponse.status
  1241. };
  1242. if (options.timeout > 0) {
  1243. clearTimeout(timer);
  1244. }
  1245. if (response.statusCode >= 200 && response.statusCode < 300) {
  1246. return options.binary ? fetchResponse.blob() : fetchResponse.text();
  1247. }
  1248. return fetchResponse.json();
  1249. }).then(function (result) {
  1250. if (response.statusCode >= 200 && response.statusCode < 300) {
  1251. callback(null, response, result);
  1252. } else {
  1253. callback(result, response);
  1254. }
  1255. }).catch(function (error) {
  1256. callback(error, response);
  1257. });
  1258. return {abort: wrappedPromise.reject};
  1259. }
  1260. function xhRequest(options, callback) {
  1261. var xhr, timer;
  1262. var timedout = false;
  1263. var abortReq = function () {
  1264. xhr.abort();
  1265. cleanUp();
  1266. };
  1267. var timeoutReq = function () {
  1268. timedout = true;
  1269. xhr.abort();
  1270. cleanUp();
  1271. };
  1272. var ret = {abort: abortReq};
  1273. var cleanUp = function () {
  1274. clearTimeout(timer);
  1275. ret.abort = function () {};
  1276. if (xhr) {
  1277. xhr.onprogress = undefined;
  1278. if (xhr.upload) {
  1279. xhr.upload.onprogress = undefined;
  1280. }
  1281. xhr.onreadystatechange = undefined;
  1282. xhr = undefined;
  1283. }
  1284. };
  1285. if (options.xhr) {
  1286. xhr = new options.xhr();
  1287. } else {
  1288. xhr = new XMLHttpRequest();
  1289. }
  1290. try {
  1291. xhr.open(options.method, options.url);
  1292. } catch (exception) {
  1293. return callback(new Error(exception.name || 'Url is invalid'));
  1294. }
  1295. xhr.withCredentials = ('withCredentials' in options) ?
  1296. options.withCredentials : true;
  1297. if (options.method === 'GET') {
  1298. delete options.headers['Content-Type'];
  1299. } else if (options.json) {
  1300. options.headers.Accept = 'application/json';
  1301. options.headers['Content-Type'] = options.headers['Content-Type'] ||
  1302. 'application/json';
  1303. if (options.body &&
  1304. options.processData &&
  1305. typeof options.body !== "string") {
  1306. options.body = JSON.stringify(options.body);
  1307. }
  1308. }
  1309. if (options.binary) {
  1310. xhr.responseType = 'arraybuffer';
  1311. }
  1312. if (!('body' in options)) {
  1313. options.body = null;
  1314. }
  1315. for (var key in options.headers) {
  1316. if (options.headers.hasOwnProperty(key)) {
  1317. xhr.setRequestHeader(key, options.headers[key]);
  1318. }
  1319. }
  1320. if (options.timeout > 0) {
  1321. timer = setTimeout(timeoutReq, options.timeout);
  1322. xhr.onprogress = function () {
  1323. clearTimeout(timer);
  1324. if(xhr.readyState !== 4) {
  1325. timer = setTimeout(timeoutReq, options.timeout);
  1326. }
  1327. };
  1328. if (typeof xhr.upload !== 'undefined') { // does not exist in ie9
  1329. xhr.upload.onprogress = xhr.onprogress;
  1330. }
  1331. }
  1332. xhr.onreadystatechange = function () {
  1333. if (xhr.readyState !== 4) {
  1334. return;
  1335. }
  1336. var response = {
  1337. statusCode: xhr.status
  1338. };
  1339. if (xhr.status >= 200 && xhr.status < 300) {
  1340. var data;
  1341. if (options.binary) {
  1342. data = createBlob([xhr.response || ''], {
  1343. type: xhr.getResponseHeader('Content-Type')
  1344. });
  1345. } else {
  1346. data = xhr.responseText;
  1347. }
  1348. callback(null, response, data);
  1349. } else {
  1350. var err = {};
  1351. if (timedout) {
  1352. err = new Error('ETIMEDOUT');
  1353. err.code = 'ETIMEDOUT';
  1354. } else if (typeof xhr.response === 'string') {
  1355. try {
  1356. err = JSON.parse(xhr.response);
  1357. } catch(e) {}
  1358. }
  1359. err.status = xhr.status;
  1360. callback(err);
  1361. }
  1362. cleanUp();
  1363. };
  1364. if (options.body && (options.body instanceof Blob)) {
  1365. readAsArrayBuffer(options.body, function (arrayBuffer) {
  1366. xhr.send(arrayBuffer);
  1367. });
  1368. } else {
  1369. xhr.send(options.body);
  1370. }
  1371. return ret;
  1372. }
  1373. function testXhr() {
  1374. try {
  1375. new XMLHttpRequest();
  1376. return true;
  1377. } catch (err) {
  1378. return false;
  1379. }
  1380. }
  1381. var hasXhr = testXhr();
  1382. function ajax$1(options, callback) {
  1383. if (hasXhr || options.xhr) {
  1384. return xhRequest(options, callback);
  1385. } else {
  1386. return fetchRequest(options, callback);
  1387. }
  1388. }
  1389. inherits(PouchError, Error);
  1390. function PouchError(opts) {
  1391. Error.call(this, opts.reason);
  1392. this.status = opts.status;
  1393. this.name = opts.error;
  1394. this.message = opts.reason;
  1395. this.error = true;
  1396. }
  1397. PouchError.prototype.toString = function () {
  1398. return JSON.stringify({
  1399. status: this.status,
  1400. name: this.name,
  1401. message: this.message,
  1402. reason: this.reason
  1403. });
  1404. };
  1405. var UNAUTHORIZED = new PouchError({
  1406. status: 401,
  1407. error: 'unauthorized',
  1408. reason: "Name or password is incorrect."
  1409. });
  1410. var MISSING_BULK_DOCS = new PouchError({
  1411. status: 400,
  1412. error: 'bad_request',
  1413. reason: "Missing JSON list of 'docs'"
  1414. });
  1415. var MISSING_DOC = new PouchError({
  1416. status: 404,
  1417. error: 'not_found',
  1418. reason: 'missing'
  1419. });
  1420. var REV_CONFLICT = new PouchError({
  1421. status: 409,
  1422. error: 'conflict',
  1423. reason: 'Document update conflict'
  1424. });
  1425. var INVALID_ID = new PouchError({
  1426. status: 400,
  1427. error: 'bad_request',
  1428. reason: '_id field must contain a string'
  1429. });
  1430. var MISSING_ID = new PouchError({
  1431. status: 412,
  1432. error: 'missing_id',
  1433. reason: '_id is required for puts'
  1434. });
  1435. var RESERVED_ID = new PouchError({
  1436. status: 400,
  1437. error: 'bad_request',
  1438. reason: 'Only reserved document ids may start with underscore.'
  1439. });
  1440. var NOT_OPEN = new PouchError({
  1441. status: 412,
  1442. error: 'precondition_failed',
  1443. reason: 'Database not open'
  1444. });
  1445. var UNKNOWN_ERROR = new PouchError({
  1446. status: 500,
  1447. error: 'unknown_error',
  1448. reason: 'Database encountered an unknown error'
  1449. });
  1450. var BAD_ARG = new PouchError({
  1451. status: 500,
  1452. error: 'badarg',
  1453. reason: 'Some query argument is invalid'
  1454. });
  1455. var INVALID_REQUEST = new PouchError({
  1456. status: 400,
  1457. error: 'invalid_request',
  1458. reason: 'Request was invalid'
  1459. });
  1460. var QUERY_PARSE_ERROR = new PouchError({
  1461. status: 400,
  1462. error: 'query_parse_error',
  1463. reason: 'Some query parameter is invalid'
  1464. });
  1465. var DOC_VALIDATION = new PouchError({
  1466. status: 500,
  1467. error: 'doc_validation',
  1468. reason: 'Bad special document member'
  1469. });
  1470. var BAD_REQUEST = new PouchError({
  1471. status: 400,
  1472. error: 'bad_request',
  1473. reason: 'Something wrong with the request'
  1474. });
  1475. var NOT_AN_OBJECT = new PouchError({
  1476. status: 400,
  1477. error: 'bad_request',
  1478. reason: 'Document must be a JSON object'
  1479. });
  1480. var DB_MISSING = new PouchError({
  1481. status: 404,
  1482. error: 'not_found',
  1483. reason: 'Database not found'
  1484. });
  1485. var IDB_ERROR = new PouchError({
  1486. status: 500,
  1487. error: 'indexed_db_went_bad',
  1488. reason: 'unknown'
  1489. });
  1490. var WSQ_ERROR = new PouchError({
  1491. status: 500,
  1492. error: 'web_sql_went_bad',
  1493. reason: 'unknown'
  1494. });
  1495. var LDB_ERROR = new PouchError({
  1496. status: 500,
  1497. error: 'levelDB_went_went_bad',
  1498. reason: 'unknown'
  1499. });
  1500. var FORBIDDEN = new PouchError({
  1501. status: 403,
  1502. error: 'forbidden',
  1503. reason: 'Forbidden by design doc validate_doc_update function'
  1504. });
  1505. var INVALID_REV = new PouchError({
  1506. status: 400,
  1507. error: 'bad_request',
  1508. reason: 'Invalid rev format'
  1509. });
  1510. var FILE_EXISTS = new PouchError({
  1511. status: 412,
  1512. error: 'file_exists',
  1513. reason: 'The database could not be created, the file already exists.'
  1514. });
  1515. var MISSING_STUB = new PouchError({
  1516. status: 412,
  1517. error: 'missing_stub'
  1518. });
  1519. var INVALID_URL = new PouchError({
  1520. status: 413,
  1521. error: 'invalid_url',
  1522. reason: 'Provided URL is invalid'
  1523. });
  1524. function generateErrorFromResponse(err) {
  1525. if (typeof err !== 'object') {
  1526. var data = err;
  1527. err = UNKNOWN_ERROR;
  1528. err.data = data;
  1529. }
  1530. if ('error' in err && err.error === 'conflict') {
  1531. err.name = 'conflict';
  1532. err.status = 409;
  1533. }
  1534. if (!('name' in err)) {
  1535. err.name = err.error || 'unknown';
  1536. }
  1537. if (!('status' in err)) {
  1538. err.status = 500;
  1539. }
  1540. if (!('message' in err)) {
  1541. err.message = err.message || err.reason;
  1542. }
  1543. return err;
  1544. }
  1545. function isBinaryObject(object) {
  1546. return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
  1547. (typeof Blob !== 'undefined' && object instanceof Blob);
  1548. }
  1549. function cloneArrayBuffer(buff) {
  1550. if (typeof buff.slice === 'function') {
  1551. return buff.slice(0);
  1552. }
  1553. // IE10-11 slice() polyfill
  1554. var target = new ArrayBuffer(buff.byteLength);
  1555. var targetArray = new Uint8Array(target);
  1556. var sourceArray = new Uint8Array(buff);
  1557. targetArray.set(sourceArray);
  1558. return target;
  1559. }
  1560. function cloneBinaryObject(object) {
  1561. if (object instanceof ArrayBuffer) {
  1562. return cloneArrayBuffer(object);
  1563. }
  1564. var size = object.size;
  1565. var type = object.type;
  1566. // Blob
  1567. if (typeof object.slice === 'function') {
  1568. return object.slice(0, size, type);
  1569. }
  1570. // PhantomJS slice() replacement
  1571. return object.webkitSlice(0, size, type);
  1572. }
  1573. // most of this is borrowed from lodash.isPlainObject:
  1574. // https://github.com/fis-components/lodash.isplainobject/
  1575. // blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
  1576. var funcToString = Function.prototype.toString;
  1577. var objectCtorString = funcToString.call(Object);
  1578. function isPlainObject(value) {
  1579. var proto = Object.getPrototypeOf(value);
  1580. /* istanbul ignore if */
  1581. if (proto === null) { // not sure when this happens, but I guess it can
  1582. return true;
  1583. }
  1584. var Ctor = proto.constructor;
  1585. return (typeof Ctor == 'function' &&
  1586. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  1587. }
  1588. function clone(object) {
  1589. var newObject;
  1590. var i;
  1591. var len;
  1592. if (!object || typeof object !== 'object') {
  1593. return object;
  1594. }
  1595. if (Array.isArray(object)) {
  1596. newObject = [];
  1597. for (i = 0, len = object.length; i < len; i++) {
  1598. newObject[i] = clone(object[i]);
  1599. }
  1600. return newObject;
  1601. }
  1602. // special case: to avoid inconsistencies between IndexedDB
  1603. // and other backends, we automatically stringify Dates
  1604. if (object instanceof Date) {
  1605. return object.toISOString();
  1606. }
  1607. if (isBinaryObject(object)) {
  1608. return cloneBinaryObject(object);
  1609. }
  1610. if (!isPlainObject(object)) {
  1611. return object; // don't clone objects like Workers
  1612. }
  1613. newObject = {};
  1614. for (i in object) {
  1615. /* istanbul ignore else */
  1616. if (Object.prototype.hasOwnProperty.call(object, i)) {
  1617. var value = clone(object[i]);
  1618. if (typeof value !== 'undefined') {
  1619. newObject[i] = value;
  1620. }
  1621. }
  1622. }
  1623. return newObject;
  1624. }
  1625. var log = debug('pouchdb:api');
  1626. // like underscore/lodash _.pick()
  1627. function pick(obj, arr) {
  1628. var res = {};
  1629. for (var i = 0, len = arr.length; i < len; i++) {
  1630. var prop = arr[i];
  1631. if (prop in obj) {
  1632. res[prop] = obj[prop];
  1633. }
  1634. }
  1635. return res;
  1636. }
  1637. function isChromeApp() {
  1638. return (typeof chrome !== "undefined" &&
  1639. typeof chrome.storage !== "undefined" &&
  1640. typeof chrome.storage.local !== "undefined");
  1641. }
  1642. var hasLocal;
  1643. if (isChromeApp()) {
  1644. hasLocal = false;
  1645. } else {
  1646. try {
  1647. localStorage.setItem('_pouch_check_localstorage', 1);
  1648. hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
  1649. } catch (e) {
  1650. hasLocal = false;
  1651. }
  1652. }
  1653. function hasLocalStorage() {
  1654. return hasLocal;
  1655. }
  1656. inherits(Changes, events.EventEmitter);
  1657. /* istanbul ignore next */
  1658. function attachBrowserEvents(self) {
  1659. if (isChromeApp()) {
  1660. chrome.storage.onChanged.addListener(function (e) {
  1661. // make sure it's event addressed to us
  1662. if (e.db_name != null) {
  1663. //object only has oldValue, newValue members
  1664. self.emit(e.dbName.newValue);
  1665. }
  1666. });
  1667. } else if (hasLocalStorage()) {
  1668. if (typeof addEventListener !== 'undefined') {
  1669. addEventListener("storage", function (e) {
  1670. self.emit(e.key);
  1671. });
  1672. } else { // old IE
  1673. window.attachEvent("storage", function (e) {
  1674. self.emit(e.key);
  1675. });
  1676. }
  1677. }
  1678. }
  1679. function Changes() {
  1680. events.EventEmitter.call(this);
  1681. this._listeners = {};
  1682. attachBrowserEvents(this);
  1683. }
  1684. Changes.prototype.addListener = function (dbName, id, db, opts) {
  1685. /* istanbul ignore if */
  1686. if (this._listeners[id]) {
  1687. return;
  1688. }
  1689. var self = this;
  1690. var inprogress = false;
  1691. function eventFunction() {
  1692. /* istanbul ignore if */
  1693. if (!self._listeners[id]) {
  1694. return;
  1695. }
  1696. if (inprogress) {
  1697. inprogress = 'waiting';
  1698. return;
  1699. }
  1700. inprogress = true;
  1701. var changesOpts = pick(opts, [
  1702. 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
  1703. 'doc_ids', 'view', 'since', 'query_params', 'binary'
  1704. ]);
  1705. /* istanbul ignore next */
  1706. function onError() {
  1707. inprogress = false;
  1708. }
  1709. db.changes(changesOpts).on('change', function (c) {
  1710. if (c.seq > opts.since && !opts.cancelled) {
  1711. opts.since = c.seq;
  1712. opts.onChange(c);
  1713. }
  1714. }).on('complete', function () {
  1715. if (inprogress === 'waiting') {
  1716. setTimeout(function (){
  1717. eventFunction();
  1718. },0);
  1719. }
  1720. inprogress = false;
  1721. }).on('error', onError);
  1722. }
  1723. this._listeners[id] = eventFunction;
  1724. this.on(dbName, eventFunction);
  1725. };
  1726. Changes.prototype.removeListener = function (dbName, id) {
  1727. /* istanbul ignore if */
  1728. if (!(id in this._listeners)) {
  1729. return;
  1730. }
  1731. events.EventEmitter.prototype.removeListener.call(this, dbName,
  1732. this._listeners[id]);
  1733. delete this._listeners[id];
  1734. };
  1735. /* istanbul ignore next */
  1736. Changes.prototype.notifyLocalWindows = function (dbName) {
  1737. //do a useless change on a storage thing
  1738. //in order to get other windows's listeners to activate
  1739. if (isChromeApp()) {
  1740. chrome.storage.local.set({dbName: dbName});
  1741. } else if (hasLocalStorage()) {
  1742. localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
  1743. }
  1744. };
  1745. Changes.prototype.notify = function (dbName) {
  1746. this.emit(dbName);
  1747. this.notifyLocalWindows(dbName);
  1748. };
  1749. // BEGIN Math.uuid.js
  1750. /*!
  1751. Math.uuid.js (v1.4)
  1752. http://www.broofa.com
  1753. mailto:[email protected]
  1754. Copyright (c) 2010 Robert Kieffer
  1755. Dual licensed under the MIT and GPL licenses.
  1756. */
  1757. /*
  1758. * Generate a random uuid.
  1759. *
  1760. * USAGE: Math.uuid(length, radix)
  1761. * length - the desired number of characters
  1762. * radix - the number of allowable values for each character.
  1763. *
  1764. * EXAMPLES:
  1765. * // No arguments - returns RFC4122, version 4 ID
  1766. * >>> Math.uuid()
  1767. * "92329D39-6F5C-4520-ABFC-AAB64544E172"
  1768. *
  1769. * // One argument - returns ID of the specified length
  1770. * >>> Math.uuid(15) // 15 character ID (default base=62)
  1771. * "VcydxgltxrVZSTV"
  1772. *
  1773. * // Two arguments - returns ID of the specified length, and radix.
  1774. * // (Radix must be <= 62)
  1775. * >>> Math.uuid(8, 2) // 8 character ID (base=2)
  1776. * "01001010"
  1777. * >>> Math.uuid(8, 10) // 8 character ID (base=10)
  1778. * "47473046"
  1779. * >>> Math.uuid(8, 16) // 8 character ID (base=16)
  1780. * "098F4D35"
  1781. */
  1782. var chars = (
  1783. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
  1784. 'abcdefghijklmnopqrstuvwxyz'
  1785. ).split('');
  1786. // the blob already has a type; do nothing
  1787. var res$2 = function () {};
  1788. function defaultBody() {
  1789. return '';
  1790. }
  1791. function ajaxCore(options, callback) {
  1792. options = clone(options);
  1793. var defaultOptions = {
  1794. method : "GET",
  1795. headers: {},
  1796. json: true,
  1797. processData: true,
  1798. timeout: 10000,
  1799. cache: false
  1800. };
  1801. options = jsExtend.extend(defaultOptions, options);
  1802. function onSuccess(obj, resp, cb) {
  1803. if (!options.binary && options.json && typeof obj === 'string') {
  1804. /* istanbul ignore next */
  1805. try {
  1806. obj = JSON.parse(obj);
  1807. } catch (e) {
  1808. // Probably a malformed JSON from server
  1809. return cb(e);
  1810. }
  1811. }
  1812. if (Array.isArray(obj)) {
  1813. obj = obj.map(function (v) {
  1814. if (v.error || v.missing) {
  1815. return generateErrorFromResponse(v);
  1816. } else {
  1817. return v;
  1818. }
  1819. });
  1820. }
  1821. if (options.binary) {
  1822. res$2(obj, resp);
  1823. }
  1824. cb(null, obj, resp);
  1825. }
  1826. if (options.json) {
  1827. if (!options.binary) {
  1828. options.headers.Accept = 'application/json';
  1829. }
  1830. options.headers['Content-Type'] = options.headers['Content-Type'] ||
  1831. 'application/json';
  1832. }
  1833. if (options.binary) {
  1834. options.encoding = null;
  1835. options.json = false;
  1836. }
  1837. if (!options.processData) {
  1838. options.json = false;
  1839. }
  1840. return ajax$1(options, function (err, response, body) {
  1841. if (err) {
  1842. return callback(generateErrorFromResponse(err));
  1843. }
  1844. var error;
  1845. var content_type = response.headers && response.headers['content-type'];
  1846. var data = body || defaultBody();
  1847. // CouchDB doesn't always return the right content-type for JSON data, so
  1848. // we check for ^{ and }$ (ignoring leading/trailing whitespace)
  1849. if (!options.binary && (options.json || !options.processData) &&
  1850. typeof data !== 'object' &&
  1851. (/json/.test(content_type) ||
  1852. (/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) {
  1853. try {
  1854. data = JSON.parse(data.toString());
  1855. } catch (e) {}
  1856. }
  1857. if (response.statusCode >= 200 && response.statusCode < 300) {
  1858. onSuccess(data, response, callback);
  1859. } else {
  1860. error = generateErrorFromResponse(data);
  1861. error.status = response.statusCode;
  1862. callback(error);
  1863. }
  1864. });
  1865. }
  1866. function ajax(opts, callback) {
  1867. // cache-buster, specifically designed to work around IE's aggressive caching
  1868. // see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
  1869. // Also Safari caches POSTs, so we need to cache-bust those too.
  1870. var ua = (navigator && navigator.userAgent) ?
  1871. navigator.userAgent.toLowerCase() : '';
  1872. var isSafari = ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1;
  1873. var isIE = ua.indexOf('msie') !== -1;
  1874. var isEdge = ua.indexOf('edge') !== -1;
  1875. // it appears the new version of safari also caches GETs,
  1876. // see https://github.com/pouchdb/pouchdb/issues/5010
  1877. var shouldCacheBust = (isSafari ||
  1878. ((isIE || isEdge) && opts.method === 'GET'));
  1879. var cache = 'cache' in opts ? opts.cache : true;
  1880. var isBlobUrl = /^blob:/.test(opts.url); // don't append nonces for blob URLs
  1881. if (!isBlobUrl && (shouldCacheBust || !cache)) {
  1882. var hasArgs = opts.url.indexOf('?') !== -1;
  1883. opts.url += (hasArgs ? '&' : '?') + '_nonce=' + Date.now();
  1884. }
  1885. return ajaxCore(opts, callback);
  1886. }
  1887. module.exports = ajax;
  1888. },{"2":2,"3":3,"5":5,"7":7,"8":8,"9":9}],12:[function(require,module,exports){
  1889. "use strict";
  1890. // Extends method
  1891. // (taken from http://code.jquery.com/jquery-1.9.0.js)
  1892. // Populate the class2type map
  1893. var class2type = {};
  1894. var types = [
  1895. "Boolean", "Number", "String", "Function", "Array",
  1896. "Date", "RegExp", "Object", "Error"
  1897. ];
  1898. for (var i = 0; i < types.length; i++) {
  1899. var typename = types[i];
  1900. class2type["[object " + typename + "]"] = typename.toLowerCase();
  1901. }
  1902. var core_toString = class2type.toString;
  1903. var core_hasOwn = class2type.hasOwnProperty;
  1904. function type(obj) {
  1905. if (obj === null) {
  1906. return String(obj);
  1907. }
  1908. return typeof obj === "object" || typeof obj === "function" ?
  1909. class2type[core_toString.call(obj)] || "object" :
  1910. typeof obj;
  1911. }
  1912. function isWindow(obj) {
  1913. return obj !== null && obj === obj.window;
  1914. }
  1915. function isPlainObject(obj) {
  1916. // Must be an Object.
  1917. // Because of IE, we also have to check the presence of
  1918. // the constructor property.
  1919. // Make sure that DOM nodes and window objects don't pass through, as well
  1920. if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
  1921. return false;
  1922. }
  1923. try {
  1924. // Not own constructor property must be Object
  1925. if (obj.constructor &&
  1926. !core_hasOwn.call(obj, "constructor") &&
  1927. !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
  1928. return false;
  1929. }
  1930. } catch ( e ) {
  1931. // IE8,9 Will throw exceptions on certain host objects #9897
  1932. return false;
  1933. }
  1934. // Own properties are enumerated firstly, so to speed up,
  1935. // if last one is own, then all properties are own.
  1936. var key;
  1937. for (key in obj) {}
  1938. return key === undefined || core_hasOwn.call(obj, key);
  1939. }
  1940. function isFunction(obj) {
  1941. return type(obj) === "function";
  1942. }
  1943. var isArray = Array.isArray || function (obj) {
  1944. return type(obj) === "array";
  1945. };
  1946. function extend() {
  1947. // originally extend() was recursive, but this ended up giving us
  1948. // "call stack exceeded", so it's been unrolled to use a literal stack
  1949. // (see https://github.com/pouchdb/pouchdb/issues/2543)
  1950. var stack = [];
  1951. var i = -1;
  1952. var len = arguments.length;
  1953. var args = new Array(len);
  1954. while (++i < len) {
  1955. args[i] = arguments[i];
  1956. }
  1957. var container = {};
  1958. stack.push({args: args, result: {container: container, key: 'key'}});
  1959. var next;
  1960. while ((next = stack.pop())) {
  1961. extendInner(stack, next.args, next.result);
  1962. }
  1963. return container.key;
  1964. }
  1965. function extendInner(stack, args, result) {
  1966. var options, name, src, copy, copyIsArray, clone,
  1967. target = args[0] || {},
  1968. i = 1,
  1969. length = args.length,
  1970. deep = false,
  1971. numericStringRegex = /\d+/,
  1972. optionsIsArray;
  1973. // Handle a deep copy situation
  1974. if (typeof target === "boolean") {
  1975. deep = target;
  1976. target = args[1] || {};
  1977. // skip the boolean and the target
  1978. i = 2;
  1979. }
  1980. // Handle case when target is a string or something (possible in deep copy)
  1981. if (typeof target !== "object" && !isFunction(target)) {
  1982. target = {};
  1983. }
  1984. // extend jQuery itself if only one argument is passed
  1985. if (length === i) {
  1986. /* jshint validthis: true */
  1987. target = this;
  1988. --i;
  1989. }
  1990. for (; i < length; i++) {
  1991. // Only deal with non-null/undefined values
  1992. if ((options = args[i]) != null) {
  1993. optionsIsArray = isArray(options);
  1994. // Extend the base object
  1995. for (name in options) {
  1996. //if (options.hasOwnProperty(name)) {
  1997. if (!(name in Object.prototype)) {
  1998. if (optionsIsArray && !numericStringRegex.test(name)) {
  1999. continue;
  2000. }
  2001. src = target[name];
  2002. copy = options[name];
  2003. // Prevent never-ending loop
  2004. if (target === copy) {
  2005. continue;
  2006. }
  2007. // Recurse if we're merging plain objects or arrays
  2008. if (deep && copy && (isPlainObject(copy) ||
  2009. (copyIsArray = isArray(copy)))) {
  2010. if (copyIsArray) {
  2011. copyIsArray = false;
  2012. clone = src && isArray(src) ? src : [];
  2013. } else {
  2014. clone = src && isPlainObject(src) ? src : {};
  2015. }
  2016. // Never move original objects, clone them
  2017. stack.push({
  2018. args: [deep, clone, copy],
  2019. result: {
  2020. container: target,
  2021. key: name
  2022. }
  2023. });
  2024. // Don't bring in undefined values
  2025. } else if (copy !== undefined) {
  2026. if (!(isArray(options) && isFunction(copy))) {
  2027. target[name] = copy;
  2028. }
  2029. }
  2030. }
  2031. }
  2032. }
  2033. }
  2034. // "Return" the modified object by setting the key
  2035. // on the given container
  2036. result.container[result.key] = target;
  2037. }
  2038. module.exports = extend;
  2039. },{}],13:[function(require,module,exports){
  2040. 'use strict';
  2041. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  2042. var lie = _interopDefault(require(9));
  2043. /* istanbul ignore next */
  2044. var PouchPromise = typeof Promise === 'function' ? Promise : lie;
  2045. module.exports = PouchPromise;
  2046. },{"9":9}],14:[function(require,module,exports){
  2047. (function (process){
  2048. 'use strict';
  2049. Object.defineProperty(exports, '__esModule', { value: true });
  2050. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  2051. var lie = _interopDefault(require(9));
  2052. var getArguments = _interopDefault(require(2));
  2053. var debug = _interopDefault(require(3));
  2054. var events = require(5);
  2055. var inherits = _interopDefault(require(7));
  2056. /* istanbul ignore next */
  2057. var PouchPromise = typeof Promise === 'function' ? Promise : lie;
  2058. function isBinaryObject(object) {
  2059. return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
  2060. (typeof Blob !== 'undefined' && object instanceof Blob);
  2061. }
  2062. function cloneArrayBuffer(buff) {
  2063. if (typeof buff.slice === 'function') {
  2064. return buff.slice(0);
  2065. }
  2066. // IE10-11 slice() polyfill
  2067. var target = new ArrayBuffer(buff.byteLength);
  2068. var targetArray = new Uint8Array(target);
  2069. var sourceArray = new Uint8Array(buff);
  2070. targetArray.set(sourceArray);
  2071. return target;
  2072. }
  2073. function cloneBinaryObject(object) {
  2074. if (object instanceof ArrayBuffer) {
  2075. return cloneArrayBuffer(object);
  2076. }
  2077. var size = object.size;
  2078. var type = object.type;
  2079. // Blob
  2080. if (typeof object.slice === 'function') {
  2081. return object.slice(0, size, type);
  2082. }
  2083. // PhantomJS slice() replacement
  2084. return object.webkitSlice(0, size, type);
  2085. }
  2086. // most of this is borrowed from lodash.isPlainObject:
  2087. // https://github.com/fis-components/lodash.isplainobject/
  2088. // blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
  2089. var funcToString = Function.prototype.toString;
  2090. var objectCtorString = funcToString.call(Object);
  2091. function isPlainObject(value) {
  2092. var proto = Object.getPrototypeOf(value);
  2093. /* istanbul ignore if */
  2094. if (proto === null) { // not sure when this happens, but I guess it can
  2095. return true;
  2096. }
  2097. var Ctor = proto.constructor;
  2098. return (typeof Ctor == 'function' &&
  2099. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  2100. }
  2101. function clone(object) {
  2102. var newObject;
  2103. var i;
  2104. var len;
  2105. if (!object || typeof object !== 'object') {
  2106. return object;
  2107. }
  2108. if (Array.isArray(object)) {
  2109. newObject = [];
  2110. for (i = 0, len = object.length; i < len; i++) {
  2111. newObject[i] = clone(object[i]);
  2112. }
  2113. return newObject;
  2114. }
  2115. // special case: to avoid inconsistencies between IndexedDB
  2116. // and other backends, we automatically stringify Dates
  2117. if (object instanceof Date) {
  2118. return object.toISOString();
  2119. }
  2120. if (isBinaryObject(object)) {
  2121. return cloneBinaryObject(object);
  2122. }
  2123. if (!isPlainObject(object)) {
  2124. return object; // don't clone objects like Workers
  2125. }
  2126. newObject = {};
  2127. for (i in object) {
  2128. /* istanbul ignore else */
  2129. if (Object.prototype.hasOwnProperty.call(object, i)) {
  2130. var value = clone(object[i]);
  2131. if (typeof value !== 'undefined') {
  2132. newObject[i] = value;
  2133. }
  2134. }
  2135. }
  2136. return newObject;
  2137. }
  2138. function once(fun) {
  2139. var called = false;
  2140. return getArguments(function (args) {
  2141. /* istanbul ignore if */
  2142. if (called) {
  2143. // this is a smoke test and should never actually happen
  2144. throw new Error('once called more than once');
  2145. } else {
  2146. called = true;
  2147. fun.apply(this, args);
  2148. }
  2149. });
  2150. }
  2151. function toPromise(func) {
  2152. //create the function we will be returning
  2153. return getArguments(function (args) {
  2154. // Clone arguments
  2155. args = clone(args);
  2156. var self = this;
  2157. var tempCB =
  2158. (typeof args[args.length - 1] === 'function') ? args.pop() : false;
  2159. // if the last argument is a function, assume its a callback
  2160. var usedCB;
  2161. if (tempCB) {
  2162. // if it was a callback, create a new callback which calls it,
  2163. // but do so async so we don't trap any errors
  2164. usedCB = function (err, resp) {
  2165. process.nextTick(function () {
  2166. tempCB(err, resp);
  2167. });
  2168. };
  2169. }
  2170. var promise = new PouchPromise(function (fulfill, reject) {
  2171. var resp;
  2172. try {
  2173. var callback = once(function (err, mesg) {
  2174. if (err) {
  2175. reject(err);
  2176. } else {
  2177. fulfill(mesg);
  2178. }
  2179. });
  2180. // create a callback for this invocation
  2181. // apply the function in the orig context
  2182. args.push(callback);
  2183. resp = func.apply(self, args);
  2184. if (resp && typeof resp.then === 'function') {
  2185. fulfill(resp);
  2186. }
  2187. } catch (e) {
  2188. reject(e);
  2189. }
  2190. });
  2191. // if there is a callback, call it back
  2192. if (usedCB) {
  2193. promise.then(function (result) {
  2194. usedCB(null, result);
  2195. }, usedCB);
  2196. }
  2197. return promise;
  2198. });
  2199. }
  2200. var log = debug('pouchdb:api');
  2201. function adapterFun(name, callback) {
  2202. function logApiCall(self, name, args) {
  2203. /* istanbul ignore if */
  2204. if (log.enabled) {
  2205. var logArgs = [self.name, name];
  2206. for (var i = 0; i < args.length - 1; i++) {
  2207. logArgs.push(args[i]);
  2208. }
  2209. log.apply(null, logArgs);
  2210. // override the callback itself to log the response
  2211. var origCallback = args[args.length - 1];
  2212. args[args.length - 1] = function (err, res) {
  2213. var responseArgs = [self.name, name];
  2214. responseArgs = responseArgs.concat(
  2215. err ? ['error', err] : ['success', res]
  2216. );
  2217. log.apply(null, responseArgs);
  2218. origCallback(err, res);
  2219. };
  2220. }
  2221. }
  2222. return toPromise(getArguments(function (args) {
  2223. if (this._closed) {
  2224. return PouchPromise.reject(new Error('database is closed'));
  2225. }
  2226. if (this._destroyed) {
  2227. return PouchPromise.reject(new Error('database is destroyed'));
  2228. }
  2229. var self = this;
  2230. logApiCall(self, name, args);
  2231. if (!this.taskqueue.isReady) {
  2232. return new PouchPromise(function (fulfill, reject) {
  2233. self.taskqueue.addTask(function (failed) {
  2234. if (failed) {
  2235. reject(failed);
  2236. } else {
  2237. fulfill(self[name].apply(self, args));
  2238. }
  2239. });
  2240. });
  2241. }
  2242. return callback.apply(this, args);
  2243. }));
  2244. }
  2245. // like underscore/lodash _.pick()
  2246. function pick(obj, arr) {
  2247. var res = {};
  2248. for (var i = 0, len = arr.length; i < len; i++) {
  2249. var prop = arr[i];
  2250. if (prop in obj) {
  2251. res[prop] = obj[prop];
  2252. }
  2253. }
  2254. return res;
  2255. }
  2256. // Most browsers throttle concurrent requests at 6, so it's silly
  2257. // to shim _bulk_get by trying to launch potentially hundreds of requests
  2258. // and then letting the majority time out. We can handle this ourselves.
  2259. var MAX_NUM_CONCURRENT_REQUESTS = 6;
  2260. function identityFunction(x) {
  2261. return x;
  2262. }
  2263. function formatResultForOpenRevsGet(result) {
  2264. return [{
  2265. ok: result
  2266. }];
  2267. }
  2268. // shim for P/CouchDB adapters that don't directly implement _bulk_get
  2269. function bulkGet(db, opts, callback) {
  2270. var requests = opts.docs;
  2271. // consolidate into one request per doc if possible
  2272. var requestsById = {};
  2273. requests.forEach(function (request) {
  2274. if (request.id in requestsById) {
  2275. requestsById[request.id].push(request);
  2276. } else {
  2277. requestsById[request.id] = [request];
  2278. }
  2279. });
  2280. var numDocs = Object.keys(requestsById).length;
  2281. var numDone = 0;
  2282. var perDocResults = new Array(numDocs);
  2283. function collapseResultsAndFinish() {
  2284. var results = [];
  2285. perDocResults.forEach(function (res) {
  2286. res.docs.forEach(function (info) {
  2287. results.push({
  2288. id: res.id,
  2289. docs: [info]
  2290. });
  2291. });
  2292. });
  2293. callback(null, {results: results});
  2294. }
  2295. function checkDone() {
  2296. if (++numDone === numDocs) {
  2297. collapseResultsAndFinish();
  2298. }
  2299. }
  2300. function gotResult(docIndex, id, docs) {
  2301. perDocResults[docIndex] = {id: id, docs: docs};
  2302. checkDone();
  2303. }
  2304. var allRequests = Object.keys(requestsById);
  2305. var i = 0;
  2306. function nextBatch() {
  2307. if (i >= allRequests.length) {
  2308. return;
  2309. }
  2310. var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
  2311. var batch = allRequests.slice(i, upTo);
  2312. processBatch(batch, i);
  2313. i += batch.length;
  2314. }
  2315. function processBatch(batch, offset) {
  2316. batch.forEach(function (docId, j) {
  2317. var docIdx = offset + j;
  2318. var docRequests = requestsById[docId];
  2319. // just use the first request as the "template"
  2320. // TODO: The _bulk_get API allows for more subtle use cases than this,
  2321. // but for now it is unlikely that there will be a mix of different
  2322. // "atts_since" or "attachments" in the same request, since it's just
  2323. // replicate.js that is using this for the moment.
  2324. // Also, atts_since is aspirational, since we don't support it yet.
  2325. var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
  2326. docOpts.open_revs = docRequests.map(function (request) {
  2327. // rev is optional, open_revs disallowed
  2328. return request.rev;
  2329. });
  2330. // remove falsey / undefined revisions
  2331. docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
  2332. var formatResult = identityFunction;
  2333. if (docOpts.open_revs.length === 0) {
  2334. delete docOpts.open_revs;
  2335. // when fetching only the "winning" leaf,
  2336. // transform the result so it looks like an open_revs
  2337. // request
  2338. formatResult = formatResultForOpenRevsGet;
  2339. }
  2340. // globally-supplied options
  2341. ['revs', 'attachments', 'binary', 'ajax'].forEach(function (param) {
  2342. if (param in opts) {
  2343. docOpts[param] = opts[param];
  2344. }
  2345. });
  2346. db.get(docId, docOpts, function (err, res) {
  2347. var result;
  2348. /* istanbul ignore if */
  2349. if (err) {
  2350. result = [{error: err}];
  2351. } else {
  2352. result = formatResult(res);
  2353. }
  2354. gotResult(docIdx, docId, result);
  2355. nextBatch();
  2356. });
  2357. });
  2358. }
  2359. nextBatch();
  2360. }
  2361. function isChromeApp() {
  2362. return (typeof chrome !== "undefined" &&
  2363. typeof chrome.storage !== "undefined" &&
  2364. typeof chrome.storage.local !== "undefined");
  2365. }
  2366. var hasLocal;
  2367. if (isChromeApp()) {
  2368. hasLocal = false;
  2369. } else {
  2370. try {
  2371. localStorage.setItem('_pouch_check_localstorage', 1);
  2372. hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
  2373. } catch (e) {
  2374. hasLocal = false;
  2375. }
  2376. }
  2377. function hasLocalStorage() {
  2378. return hasLocal;
  2379. }
  2380. inherits(Changes, events.EventEmitter);
  2381. /* istanbul ignore next */
  2382. function attachBrowserEvents(self) {
  2383. if (isChromeApp()) {
  2384. chrome.storage.onChanged.addListener(function (e) {
  2385. // make sure it's event addressed to us
  2386. if (e.db_name != null) {
  2387. //object only has oldValue, newValue members
  2388. self.emit(e.dbName.newValue);
  2389. }
  2390. });
  2391. } else if (hasLocalStorage()) {
  2392. if (typeof addEventListener !== 'undefined') {
  2393. addEventListener("storage", function (e) {
  2394. self.emit(e.key);
  2395. });
  2396. } else { // old IE
  2397. window.attachEvent("storage", function (e) {
  2398. self.emit(e.key);
  2399. });
  2400. }
  2401. }
  2402. }
  2403. function Changes() {
  2404. events.EventEmitter.call(this);
  2405. this._listeners = {};
  2406. attachBrowserEvents(this);
  2407. }
  2408. Changes.prototype.addListener = function (dbName, id, db, opts) {
  2409. /* istanbul ignore if */
  2410. if (this._listeners[id]) {
  2411. return;
  2412. }
  2413. var self = this;
  2414. var inprogress = false;
  2415. function eventFunction() {
  2416. /* istanbul ignore if */
  2417. if (!self._listeners[id]) {
  2418. return;
  2419. }
  2420. if (inprogress) {
  2421. inprogress = 'waiting';
  2422. return;
  2423. }
  2424. inprogress = true;
  2425. var changesOpts = pick(opts, [
  2426. 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
  2427. 'doc_ids', 'view', 'since', 'query_params', 'binary'
  2428. ]);
  2429. /* istanbul ignore next */
  2430. function onError() {
  2431. inprogress = false;
  2432. }
  2433. db.changes(changesOpts).on('change', function (c) {
  2434. if (c.seq > opts.since && !opts.cancelled) {
  2435. opts.since = c.seq;
  2436. opts.onChange(c);
  2437. }
  2438. }).on('complete', function () {
  2439. if (inprogress === 'waiting') {
  2440. setTimeout(function (){
  2441. eventFunction();
  2442. },0);
  2443. }
  2444. inprogress = false;
  2445. }).on('error', onError);
  2446. }
  2447. this._listeners[id] = eventFunction;
  2448. this.on(dbName, eventFunction);
  2449. };
  2450. Changes.prototype.removeListener = function (dbName, id) {
  2451. /* istanbul ignore if */
  2452. if (!(id in this._listeners)) {
  2453. return;
  2454. }
  2455. events.EventEmitter.prototype.removeListener.call(this, dbName,
  2456. this._listeners[id]);
  2457. delete this._listeners[id];
  2458. };
  2459. /* istanbul ignore next */
  2460. Changes.prototype.notifyLocalWindows = function (dbName) {
  2461. //do a useless change on a storage thing
  2462. //in order to get other windows's listeners to activate
  2463. if (isChromeApp()) {
  2464. chrome.storage.local.set({dbName: dbName});
  2465. } else if (hasLocalStorage()) {
  2466. localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
  2467. }
  2468. };
  2469. Changes.prototype.notify = function (dbName) {
  2470. this.emit(dbName);
  2471. this.notifyLocalWindows(dbName);
  2472. };
  2473. function guardedConsole(method) {
  2474. /* istanbul ignore else */
  2475. if (console !== 'undefined' && method in console) {
  2476. var args = Array.prototype.slice.call(arguments, 1);
  2477. console[method].apply(console, args);
  2478. }
  2479. }
  2480. function randomNumber(min, max) {
  2481. var maxTimeout = 600000; // Hard-coded default of 10 minutes
  2482. min = parseInt(min, 10) || 0;
  2483. max = parseInt(max, 10);
  2484. if (max !== max || max <= min) {
  2485. max = (min || 1) << 1; //doubling
  2486. } else {
  2487. max = max + 1;
  2488. }
  2489. // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
  2490. if(max > maxTimeout) {
  2491. min = maxTimeout >> 1; // divide by two
  2492. max = maxTimeout;
  2493. }
  2494. var ratio = Math.random();
  2495. var range = max - min;
  2496. return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
  2497. }
  2498. function defaultBackOff(min) {
  2499. var max = 0;
  2500. if (!min) {
  2501. max = 2000;
  2502. }
  2503. return randomNumber(min, max);
  2504. }
  2505. // designed to give info to browser users, who are disturbed
  2506. // when they see http errors in the console
  2507. function explainError(status, str) {
  2508. guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
  2509. }
  2510. function extendInner(obj, otherObj) {
  2511. for (var key in otherObj) {
  2512. if (otherObj.hasOwnProperty(key)) {
  2513. var value = clone(otherObj[key]);
  2514. if (typeof value !== 'undefined') {
  2515. obj[key] = value;
  2516. }
  2517. }
  2518. }
  2519. }
  2520. function extend(obj, obj2, obj3) {
  2521. extendInner(obj, obj2);
  2522. if (obj3) {
  2523. extendInner(obj, obj3);
  2524. }
  2525. return obj;
  2526. }
  2527. inherits(PouchError, Error);
  2528. function PouchError(opts) {
  2529. Error.call(this, opts.reason);
  2530. this.status = opts.status;
  2531. this.name = opts.error;
  2532. this.message = opts.reason;
  2533. this.error = true;
  2534. }
  2535. PouchError.prototype.toString = function () {
  2536. return JSON.stringify({
  2537. status: this.status,
  2538. name: this.name,
  2539. message: this.message,
  2540. reason: this.reason
  2541. });
  2542. };
  2543. var UNAUTHORIZED = new PouchError({
  2544. status: 401,
  2545. error: 'unauthorized',
  2546. reason: "Name or password is incorrect."
  2547. });
  2548. var MISSING_BULK_DOCS = new PouchError({
  2549. status: 400,
  2550. error: 'bad_request',
  2551. reason: "Missing JSON list of 'docs'"
  2552. });
  2553. var MISSING_DOC = new PouchError({
  2554. status: 404,
  2555. error: 'not_found',
  2556. reason: 'missing'
  2557. });
  2558. var REV_CONFLICT = new PouchError({
  2559. status: 409,
  2560. error: 'conflict',
  2561. reason: 'Document update conflict'
  2562. });
  2563. var INVALID_ID = new PouchError({
  2564. status: 400,
  2565. error: 'bad_request',
  2566. reason: '_id field must contain a string'
  2567. });
  2568. var MISSING_ID = new PouchError({
  2569. status: 412,
  2570. error: 'missing_id',
  2571. reason: '_id is required for puts'
  2572. });
  2573. var RESERVED_ID = new PouchError({
  2574. status: 400,
  2575. error: 'bad_request',
  2576. reason: 'Only reserved document ids may start with underscore.'
  2577. });
  2578. var NOT_OPEN = new PouchError({
  2579. status: 412,
  2580. error: 'precondition_failed',
  2581. reason: 'Database not open'
  2582. });
  2583. var UNKNOWN_ERROR = new PouchError({
  2584. status: 500,
  2585. error: 'unknown_error',
  2586. reason: 'Database encountered an unknown error'
  2587. });
  2588. var BAD_ARG = new PouchError({
  2589. status: 500,
  2590. error: 'badarg',
  2591. reason: 'Some query argument is invalid'
  2592. });
  2593. var INVALID_REQUEST = new PouchError({
  2594. status: 400,
  2595. error: 'invalid_request',
  2596. reason: 'Request was invalid'
  2597. });
  2598. var QUERY_PARSE_ERROR = new PouchError({
  2599. status: 400,
  2600. error: 'query_parse_error',
  2601. reason: 'Some query parameter is invalid'
  2602. });
  2603. var DOC_VALIDATION = new PouchError({
  2604. status: 500,
  2605. error: 'doc_validation',
  2606. reason: 'Bad special document member'
  2607. });
  2608. var BAD_REQUEST = new PouchError({
  2609. status: 400,
  2610. error: 'bad_request',
  2611. reason: 'Something wrong with the request'
  2612. });
  2613. var NOT_AN_OBJECT = new PouchError({
  2614. status: 400,
  2615. error: 'bad_request',
  2616. reason: 'Document must be a JSON object'
  2617. });
  2618. var DB_MISSING = new PouchError({
  2619. status: 404,
  2620. error: 'not_found',
  2621. reason: 'Database not found'
  2622. });
  2623. var IDB_ERROR = new PouchError({
  2624. status: 500,
  2625. error: 'indexed_db_went_bad',
  2626. reason: 'unknown'
  2627. });
  2628. var WSQ_ERROR = new PouchError({
  2629. status: 500,
  2630. error: 'web_sql_went_bad',
  2631. reason: 'unknown'
  2632. });
  2633. var LDB_ERROR = new PouchError({
  2634. status: 500,
  2635. error: 'levelDB_went_went_bad',
  2636. reason: 'unknown'
  2637. });
  2638. var FORBIDDEN = new PouchError({
  2639. status: 403,
  2640. error: 'forbidden',
  2641. reason: 'Forbidden by design doc validate_doc_update function'
  2642. });
  2643. var INVALID_REV = new PouchError({
  2644. status: 400,
  2645. error: 'bad_request',
  2646. reason: 'Invalid rev format'
  2647. });
  2648. var FILE_EXISTS = new PouchError({
  2649. status: 412,
  2650. error: 'file_exists',
  2651. reason: 'The database could not be created, the file already exists.'
  2652. });
  2653. var MISSING_STUB = new PouchError({
  2654. status: 412,
  2655. error: 'missing_stub'
  2656. });
  2657. var INVALID_URL = new PouchError({
  2658. status: 413,
  2659. error: 'invalid_url',
  2660. reason: 'Provided URL is invalid'
  2661. });
  2662. function createError(error, reason) {
  2663. function CustomPouchError(reason) {
  2664. // inherit error properties from our parent error manually
  2665. // so as to allow proper JSON parsing.
  2666. /* jshint ignore:start */
  2667. for (var p in error) {
  2668. if (typeof error[p] !== 'function') {
  2669. this[p] = error[p];
  2670. }
  2671. }
  2672. /* jshint ignore:end */
  2673. if (reason !== undefined) {
  2674. this.reason = reason;
  2675. }
  2676. }
  2677. CustomPouchError.prototype = PouchError.prototype;
  2678. return new CustomPouchError(reason);
  2679. }
  2680. function tryFilter(filter, doc, req) {
  2681. try {
  2682. return !filter(doc, req);
  2683. } catch (err) {
  2684. var msg = 'Filter function threw: ' + err.toString();
  2685. return createError(BAD_REQUEST, msg);
  2686. }
  2687. }
  2688. function filterChange(opts) {
  2689. var req = {};
  2690. var hasFilter = opts.filter && typeof opts.filter === 'function';
  2691. req.query = opts.query_params;
  2692. return function filter(change) {
  2693. if (!change.doc) {
  2694. // CSG sends events on the changes feed that don't have documents,
  2695. // this hack makes a whole lot of existing code robust.
  2696. change.doc = {};
  2697. }
  2698. var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
  2699. if (typeof filterReturn === 'object') {
  2700. return filterReturn;
  2701. }
  2702. if (filterReturn) {
  2703. return false;
  2704. }
  2705. if (!opts.include_docs) {
  2706. delete change.doc;
  2707. } else if (!opts.attachments) {
  2708. for (var att in change.doc._attachments) {
  2709. /* istanbul ignore else */
  2710. if (change.doc._attachments.hasOwnProperty(att)) {
  2711. change.doc._attachments[att].stub = true;
  2712. }
  2713. }
  2714. }
  2715. return true;
  2716. };
  2717. }
  2718. function flatten(arrs) {
  2719. var res = [];
  2720. for (var i = 0, len = arrs.length; i < len; i++) {
  2721. res = res.concat(arrs[i]);
  2722. }
  2723. return res;
  2724. }
  2725. // shim for Function.prototype.name,
  2726. // for browsers that don't support it like IE
  2727. /* istanbul ignore next */
  2728. function f() {}
  2729. var hasName = f.name;
  2730. var res;
  2731. // We dont run coverage in IE
  2732. /* istanbul ignore else */
  2733. if (hasName) {
  2734. res = function (fun) {
  2735. return fun.name;
  2736. };
  2737. } else {
  2738. res = function (fun) {
  2739. return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];
  2740. };
  2741. }
  2742. var functionName = res;
  2743. // Determine id an ID is valid
  2744. // - invalid IDs begin with an underescore that does not begin '_design' or
  2745. // '_local'
  2746. // - any other string value is a valid id
  2747. // Returns the specific error object for each case
  2748. function invalidIdError(id) {
  2749. var err;
  2750. if (!id) {
  2751. err = createError(MISSING_ID);
  2752. } else if (typeof id !== 'string') {
  2753. err = createError(INVALID_ID);
  2754. } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
  2755. err = createError(RESERVED_ID);
  2756. }
  2757. if (err) {
  2758. throw err;
  2759. }
  2760. }
  2761. function isCordova() {
  2762. return (typeof cordova !== "undefined" ||
  2763. typeof PhoneGap !== "undefined" ||
  2764. typeof phonegap !== "undefined");
  2765. }
  2766. function listenerCount(ee, type) {
  2767. return 'listenerCount' in ee ? ee.listenerCount(type) :
  2768. events.EventEmitter.listenerCount(ee, type);
  2769. }
  2770. function parseDesignDocFunctionName(s) {
  2771. if (!s) {
  2772. return null;
  2773. }
  2774. var parts = s.split('/');
  2775. if (parts.length === 2) {
  2776. return parts;
  2777. }
  2778. if (parts.length === 1) {
  2779. return [s, s];
  2780. }
  2781. return null;
  2782. }
  2783. function normalizeDesignDocFunctionName(s) {
  2784. var normalized = parseDesignDocFunctionName(s);
  2785. return normalized ? normalized.join('/') : null;
  2786. }
  2787. // originally parseUri 1.2.2, now patched by us
  2788. // (c) Steven Levithan <stevenlevithan.com>
  2789. // MIT License
  2790. var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
  2791. "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
  2792. var qName ="queryKey";
  2793. var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
  2794. // use the "loose" parser
  2795. /* jshint maxlen: false */
  2796. var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  2797. function parseUri(str) {
  2798. var m = parser.exec(str);
  2799. var uri = {};
  2800. var i = 14;
  2801. while (i--) {
  2802. var key = keys[i];
  2803. var value = m[i] || "";
  2804. var encoded = ['user', 'password'].indexOf(key) !== -1;
  2805. uri[key] = encoded ? decodeURIComponent(value) : value;
  2806. }
  2807. uri[qName] = {};
  2808. uri[keys[12]].replace(qParser, function ($0, $1, $2) {
  2809. if ($1) {
  2810. uri[qName][$1] = $2;
  2811. }
  2812. });
  2813. return uri;
  2814. }
  2815. // this is essentially the "update sugar" function from daleharvey/pouchdb#1388
  2816. // the diffFun tells us what delta to apply to the doc. it either returns
  2817. // the doc, or false if it doesn't need to do an update after all
  2818. function upsert(db, docId, diffFun) {
  2819. return new PouchPromise(function (fulfill, reject) {
  2820. db.get(docId, function (err, doc) {
  2821. if (err) {
  2822. /* istanbul ignore next */
  2823. if (err.status !== 404) {
  2824. return reject(err);
  2825. }
  2826. doc = {};
  2827. }
  2828. // the user might change the _rev, so save it for posterity
  2829. var docRev = doc._rev;
  2830. var newDoc = diffFun(doc);
  2831. if (!newDoc) {
  2832. // if the diffFun returns falsy, we short-circuit as
  2833. // an optimization
  2834. return fulfill({updated: false, rev: docRev});
  2835. }
  2836. // users aren't allowed to modify these values,
  2837. // so reset them here
  2838. newDoc._id = docId;
  2839. newDoc._rev = docRev;
  2840. fulfill(tryAndPut(db, newDoc, diffFun));
  2841. });
  2842. });
  2843. }
  2844. function tryAndPut(db, doc, diffFun) {
  2845. return db.put(doc).then(function (res) {
  2846. return {
  2847. updated: true,
  2848. rev: res.rev
  2849. };
  2850. }, function (err) {
  2851. /* istanbul ignore next */
  2852. if (err.status !== 409) {
  2853. throw err;
  2854. }
  2855. return upsert(db, doc._id, diffFun);
  2856. });
  2857. }
  2858. // BEGIN Math.uuid.js
  2859. /*!
  2860. Math.uuid.js (v1.4)
  2861. http://www.broofa.com
  2862. mailto:[email protected]
  2863. Copyright (c) 2010 Robert Kieffer
  2864. Dual licensed under the MIT and GPL licenses.
  2865. */
  2866. /*
  2867. * Generate a random uuid.
  2868. *
  2869. * USAGE: Math.uuid(length, radix)
  2870. * length - the desired number of characters
  2871. * radix - the number of allowable values for each character.
  2872. *
  2873. * EXAMPLES:
  2874. * // No arguments - returns RFC4122, version 4 ID
  2875. * >>> Math.uuid()
  2876. * "92329D39-6F5C-4520-ABFC-AAB64544E172"
  2877. *
  2878. * // One argument - returns ID of the specified length
  2879. * >>> Math.uuid(15) // 15 character ID (default base=62)
  2880. * "VcydxgltxrVZSTV"
  2881. *
  2882. * // Two arguments - returns ID of the specified length, and radix.
  2883. * // (Radix must be <= 62)
  2884. * >>> Math.uuid(8, 2) // 8 character ID (base=2)
  2885. * "01001010"
  2886. * >>> Math.uuid(8, 10) // 8 character ID (base=10)
  2887. * "47473046"
  2888. * >>> Math.uuid(8, 16) // 8 character ID (base=16)
  2889. * "098F4D35"
  2890. */
  2891. var chars = (
  2892. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
  2893. 'abcdefghijklmnopqrstuvwxyz'
  2894. ).split('');
  2895. function getValue(radix) {
  2896. return 0 | Math.random() * radix;
  2897. }
  2898. function uuid(len, radix) {
  2899. radix = radix || chars.length;
  2900. var out = '';
  2901. var i = -1;
  2902. if (len) {
  2903. // Compact form
  2904. while (++i < len) {
  2905. out += chars[getValue(radix)];
  2906. }
  2907. return out;
  2908. }
  2909. // rfc4122, version 4 form
  2910. // Fill in random data. At i==19 set the high bits of clock sequence as
  2911. // per rfc4122, sec. 4.1.5
  2912. while (++i < 36) {
  2913. switch (i) {
  2914. case 8:
  2915. case 13:
  2916. case 18:
  2917. case 23:
  2918. out += '-';
  2919. break;
  2920. case 19:
  2921. out += chars[(getValue(16) & 0x3) | 0x8];
  2922. break;
  2923. default:
  2924. out += chars[getValue(16)];
  2925. }
  2926. }
  2927. return out;
  2928. }
  2929. exports.adapterFun = adapterFun;
  2930. exports.bulkGetShim = bulkGet;
  2931. exports.changesHandler = Changes;
  2932. exports.clone = clone;
  2933. exports.defaultBackOff = defaultBackOff;
  2934. exports.explainError = explainError;
  2935. exports.extend = extend;
  2936. exports.filterChange = filterChange;
  2937. exports.flatten = flatten;
  2938. exports.functionName = functionName;
  2939. exports.guardedConsole = guardedConsole;
  2940. exports.hasLocalStorage = hasLocalStorage;
  2941. exports.invalidIdError = invalidIdError;
  2942. exports.isChromeApp = isChromeApp;
  2943. exports.isCordova = isCordova;
  2944. exports.listenerCount = listenerCount;
  2945. exports.normalizeDdocFunctionName = normalizeDesignDocFunctionName;
  2946. exports.once = once;
  2947. exports.parseDdocFunctionName = parseDesignDocFunctionName;
  2948. exports.parseUri = parseUri;
  2949. exports.pick = pick;
  2950. exports.toPromise = toPromise;
  2951. exports.upsert = upsert;
  2952. exports.uuid = uuid;
  2953. }).call(this,require(15))
  2954. },{"15":15,"2":2,"3":3,"5":5,"7":7,"9":9}],15:[function(require,module,exports){
  2955. // shim for using process in browser
  2956. var process = module.exports = {};
  2957. // cached from whatever global is present so that test runners that stub it
  2958. // don't break things. But we need to wrap it in a try catch in case it is
  2959. // wrapped in strict mode code which doesn't define any globals. It's inside a
  2960. // function because try/catches deoptimize in certain engines.
  2961. var cachedSetTimeout;
  2962. var cachedClearTimeout;
  2963. function defaultSetTimout() {
  2964. throw new Error('setTimeout has not been defined');
  2965. }
  2966. function defaultClearTimeout () {
  2967. throw new Error('clearTimeout has not been defined');
  2968. }
  2969. (function () {
  2970. try {
  2971. if (typeof setTimeout === 'function') {
  2972. cachedSetTimeout = setTimeout;
  2973. } else {
  2974. cachedSetTimeout = defaultSetTimout;
  2975. }
  2976. } catch (e) {
  2977. cachedSetTimeout = defaultSetTimout;
  2978. }
  2979. try {
  2980. if (typeof clearTimeout === 'function') {
  2981. cachedClearTimeout = clearTimeout;
  2982. } else {
  2983. cachedClearTimeout = defaultClearTimeout;
  2984. }
  2985. } catch (e) {
  2986. cachedClearTimeout = defaultClearTimeout;
  2987. }
  2988. } ())
  2989. function runTimeout(fun) {
  2990. if (cachedSetTimeout === setTimeout) {
  2991. //normal enviroments in sane situations
  2992. return setTimeout(fun, 0);
  2993. }
  2994. // if setTimeout wasn't available but was latter defined
  2995. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2996. cachedSetTimeout = setTimeout;
  2997. return setTimeout(fun, 0);
  2998. }
  2999. try {
  3000. // when when somebody has screwed with setTimeout but no I.E. maddness
  3001. return cachedSetTimeout(fun, 0);
  3002. } catch(e){
  3003. try {
  3004. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3005. return cachedSetTimeout.call(null, fun, 0);
  3006. } catch(e){
  3007. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  3008. return cachedSetTimeout.call(this, fun, 0);
  3009. }
  3010. }
  3011. }
  3012. function runClearTimeout(marker) {
  3013. if (cachedClearTimeout === clearTimeout) {
  3014. //normal enviroments in sane situations
  3015. return clearTimeout(marker);
  3016. }
  3017. // if clearTimeout wasn't available but was latter defined
  3018. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3019. cachedClearTimeout = clearTimeout;
  3020. return clearTimeout(marker);
  3021. }
  3022. try {
  3023. // when when somebody has screwed with setTimeout but no I.E. maddness
  3024. return cachedClearTimeout(marker);
  3025. } catch (e){
  3026. try {
  3027. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3028. return cachedClearTimeout.call(null, marker);
  3029. } catch (e){
  3030. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  3031. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3032. return cachedClearTimeout.call(this, marker);
  3033. }
  3034. }
  3035. }
  3036. var queue = [];
  3037. var draining = false;
  3038. var currentQueue;
  3039. var queueIndex = -1;
  3040. function cleanUpNextTick() {
  3041. if (!draining || !currentQueue) {
  3042. return;
  3043. }
  3044. draining = false;
  3045. if (currentQueue.length) {
  3046. queue = currentQueue.concat(queue);
  3047. } else {
  3048. queueIndex = -1;
  3049. }
  3050. if (queue.length) {
  3051. drainQueue();
  3052. }
  3053. }
  3054. function drainQueue() {
  3055. if (draining) {
  3056. return;
  3057. }
  3058. var timeout = runTimeout(cleanUpNextTick);
  3059. draining = true;
  3060. var len = queue.length;
  3061. while(len) {
  3062. currentQueue = queue;
  3063. queue = [];
  3064. while (++queueIndex < len) {
  3065. if (currentQueue) {
  3066. currentQueue[queueIndex].run();
  3067. }
  3068. }
  3069. queueIndex = -1;
  3070. len = queue.length;
  3071. }
  3072. currentQueue = null;
  3073. draining = false;
  3074. runClearTimeout(timeout);
  3075. }
  3076. process.nextTick = function (fun) {
  3077. var args = new Array(arguments.length - 1);
  3078. if (arguments.length > 1) {
  3079. for (var i = 1; i < arguments.length; i++) {
  3080. args[i - 1] = arguments[i];
  3081. }
  3082. }
  3083. queue.push(new Item(fun, args));
  3084. if (queue.length === 1 && !draining) {
  3085. runTimeout(drainQueue);
  3086. }
  3087. };
  3088. // v8 likes predictible objects
  3089. function Item(fun, array) {
  3090. this.fun = fun;
  3091. this.array = array;
  3092. }
  3093. Item.prototype.run = function () {
  3094. this.fun.apply(null, this.array);
  3095. };
  3096. process.title = 'browser';
  3097. process.browser = true;
  3098. process.env = {};
  3099. process.argv = [];
  3100. process.version = ''; // empty string to avoid regexp issues
  3101. process.versions = {};
  3102. function noop() {}
  3103. process.on = noop;
  3104. process.addListener = noop;
  3105. process.once = noop;
  3106. process.off = noop;
  3107. process.removeListener = noop;
  3108. process.removeAllListeners = noop;
  3109. process.emit = noop;
  3110. process.binding = function (name) {
  3111. throw new Error('process.binding is not supported');
  3112. };
  3113. process.cwd = function () { return '/' };
  3114. process.chdir = function (dir) {
  3115. throw new Error('process.chdir is not supported');
  3116. };
  3117. process.umask = function() { return 0; };
  3118. },{}],16:[function(require,module,exports){
  3119. (function (name, context, definition) {
  3120. if (typeof module !== 'undefined' && module.exports) module.exports = definition();
  3121. else if (typeof define === 'function' && define.amd) define(definition);
  3122. else context[name] = definition();
  3123. })('urljoin', this, function () {
  3124. function normalize (str, options) {
  3125. // make sure protocol is followed by two slashes
  3126. str = str.replace(/:\//g, '://');
  3127. // remove consecutive slashes
  3128. str = str.replace(/([^:\s])\/+/g, '$1/');
  3129. // remove trailing slash before parameters or hash
  3130. str = str.replace(/\/(\?|&|#[^!])/g, '$1');
  3131. // replace ? in parameters with &
  3132. str = str.replace(/(\?.+)\?/g, '$1&');
  3133. return str;
  3134. }
  3135. return function () {
  3136. var input = arguments;
  3137. var options = {};
  3138. if (typeof arguments[0] === 'object') {
  3139. // new syntax with array and options
  3140. input = arguments[0];
  3141. options = arguments[1] || {};
  3142. }
  3143. var joined = [].slice.call(input, 0).join('/');
  3144. return normalize(joined, options);
  3145. };
  3146. });
  3147. },{}],17:[function(require,module,exports){
  3148. 'use strict';
  3149. var utils = require(1);
  3150. function wrapError(callback) {
  3151. // provide more helpful error message
  3152. return function (err, res) {
  3153. if (err) {
  3154. if (err.name === 'unknown_error') {
  3155. err.message = (err.message || '') +
  3156. ' Unknown error! Did you remember to enable CORS?';
  3157. }
  3158. }
  3159. return callback(err, res);
  3160. };
  3161. }
  3162. function putUser(db, user, opts, callback) {
  3163. var reservedWords = ['name', 'password', 'roles', 'type', 'salt', 'metadata'];
  3164. if (opts.metadata) {
  3165. for (var key in opts.metadata) {
  3166. if (opts.hasOwnProperty(key)) {
  3167. if (reservedWords.indexOf(key) !== -1 || key.startsWith('_')) {
  3168. return callback(new AuthError('cannot use reserved word in metadata: "' + key + '"'));
  3169. }
  3170. }
  3171. }
  3172. user = utils.extend(true, user, opts.metadata);
  3173. }
  3174. var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
  3175. var ajaxOpts = utils.extend(true, {
  3176. method : 'PUT',
  3177. url : url,
  3178. body : user
  3179. }, opts.ajax || {});
  3180. utils.ajax(ajaxOpts, wrapError(callback));
  3181. }
  3182. exports.signup = utils.toPromise(function (username, password, opts, callback) {
  3183. var db = this;
  3184. if (typeof callback === 'undefined') {
  3185. callback = typeof opts === 'undefined' ? (typeof password === 'undefined' ?
  3186. username : password) : opts;
  3187. opts = {};
  3188. }
  3189. if (['http', 'https'].indexOf(db.type()) === -1) {
  3190. return callback(new AuthError('This plugin only works for the http/https adapter. ' +
  3191. 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
  3192. } else if (!username) {
  3193. return callback(new AuthError('You must provide a username'));
  3194. } else if (!password) {
  3195. return callback(new AuthError('You must provide a password'));
  3196. }
  3197. var userId = 'org.couchdb.user:' + username;
  3198. var user = {
  3199. name : username,
  3200. password : password,
  3201. roles : opts.roles || [],
  3202. type : 'user',
  3203. _id : userId
  3204. };
  3205. putUser(db, user, opts, callback);
  3206. });
  3207. exports.signUp = exports.signup;
  3208. exports.login = utils.toPromise(function (username, password, opts, callback) {
  3209. var db = this;
  3210. if (typeof callback === 'undefined') {
  3211. callback = opts;
  3212. opts = {};
  3213. }
  3214. if (['http', 'https'].indexOf(db.type()) === -1) {
  3215. return callback(new AuthError('this plugin only works for the http/https adapter'));
  3216. }
  3217. if (!username) {
  3218. return callback(new AuthError('you must provide a username'));
  3219. } else if (!password) {
  3220. return callback(new AuthError('you must provide a password'));
  3221. }
  3222. var ajaxOpts = utils.extend(true, {
  3223. method : 'POST',
  3224. url : utils.getSessionUrl(db),
  3225. headers : {'Content-Type': 'application/json'},
  3226. body : JSON.stringify({name: username, password: password})
  3227. }, opts.ajax || {});
  3228. utils.ajax(ajaxOpts, wrapError(callback));
  3229. });
  3230. exports.logIn = exports.login;
  3231. exports.logout = utils.toPromise(function (opts, callback) {
  3232. var db = this;
  3233. if (typeof callback === 'undefined') {
  3234. callback = opts;
  3235. opts = {};
  3236. }
  3237. var ajaxOpts = utils.extend(true, {
  3238. method : 'DELETE',
  3239. url : utils.getSessionUrl(db)
  3240. }, opts.ajax || {});
  3241. utils.ajax(ajaxOpts, wrapError(callback));
  3242. });
  3243. exports.logOut = exports.logout;
  3244. exports.getSession = utils.toPromise(function (opts, callback) {
  3245. var db = this;
  3246. if (typeof callback === 'undefined') {
  3247. callback = opts;
  3248. opts = {};
  3249. }
  3250. var url = utils.getSessionUrl(db);
  3251. var ajaxOpts = utils.extend(true, {
  3252. method : 'GET',
  3253. url : url
  3254. }, opts.ajax || {});
  3255. utils.ajax(ajaxOpts, wrapError(callback));
  3256. });
  3257. exports.getUser = utils.toPromise(function (username, opts, callback) {
  3258. var db = this;
  3259. if (typeof callback === 'undefined') {
  3260. callback = typeof opts === 'undefined' ? username : opts;
  3261. opts = {};
  3262. }
  3263. if (!username) {
  3264. return callback(new AuthError('you must provide a username'));
  3265. }
  3266. var url = utils.getUsersUrl(db);
  3267. var ajaxOpts = utils.extend(true, {
  3268. method : 'GET',
  3269. url : url + '/' + encodeURIComponent('org.couchdb.user:' + username)
  3270. }, opts.ajax || {});
  3271. utils.ajax(ajaxOpts, wrapError(callback));
  3272. });
  3273. exports.putUser = utils.toPromise(function (username, opts, callback) {
  3274. var db = this;
  3275. if (typeof callback === 'undefined') {
  3276. callback = typeof opts === 'undefined' ? username : opts;
  3277. opts = {};
  3278. }
  3279. if (['http', 'https'].indexOf(db.type()) === -1) {
  3280. return callback(new AuthError('This plugin only works for the http/https adapter. ' +
  3281. 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
  3282. } else if (!username) {
  3283. return callback(new AuthError('You must provide a username'));
  3284. }
  3285. return db.getUser(username, opts, function (error, user) {
  3286. if (error) {
  3287. return callback(error);
  3288. }
  3289. putUser(db, user, opts, callback);
  3290. });
  3291. });
  3292. exports.changePassword = utils.toPromise(function (username, password, opts, callback) {
  3293. var db = this;
  3294. if (typeof callback === 'undefined') {
  3295. callback = typeof opts === 'undefined' ? (typeof password === 'undefined' ?
  3296. username : password) : opts;
  3297. opts = {};
  3298. }
  3299. if (['http', 'https'].indexOf(db.type()) === -1) {
  3300. return callback(new AuthError('This plugin only works for the http/https adapter. ' +
  3301. 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
  3302. } else if (!username) {
  3303. return callback(new AuthError('You must provide a username'));
  3304. } else if (!password) {
  3305. return callback(new AuthError('You must provide a password'));
  3306. }
  3307. return db.getUser(username, opts, function (error, user) {
  3308. if (error) {
  3309. return callback(error);
  3310. }
  3311. user.password = password;
  3312. var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
  3313. var ajaxOpts = utils.extend(true, {
  3314. method : 'PUT',
  3315. url : url,
  3316. body : user
  3317. }, opts.ajax || {});
  3318. utils.ajax(ajaxOpts, wrapError(callback));
  3319. });
  3320. });
  3321. exports.changeUsername = utils.toPromise(function (oldUsername, newUsername, opts, callback) {
  3322. var db = this;
  3323. var USERNAME_PREFIX = 'org.couchdb.user:';
  3324. var ajax = function (opts) {
  3325. return new utils.Promise(function (resolve, reject) {
  3326. utils.ajax(opts, wrapError(function (err, res) {
  3327. if (err) {
  3328. return reject(err);
  3329. }
  3330. resolve(res);
  3331. }));
  3332. });
  3333. };
  3334. var updateUser = function (user, opts) {
  3335. var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
  3336. var updateOpts = utils.extend(true, {
  3337. method : 'PUT',
  3338. url : url,
  3339. body: user
  3340. }, opts.ajax);
  3341. return ajax(updateOpts);
  3342. };
  3343. if (typeof callback === 'undefined') {
  3344. callback = opts;
  3345. opts = {};
  3346. }
  3347. opts.ajax = opts.ajax || {};
  3348. if (['http', 'https'].indexOf(db.type()) === -1) {
  3349. return callback(new AuthError('This plugin only works for the http/https adapter. ' +
  3350. 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
  3351. }
  3352. if (!newUsername) {
  3353. return callback(new AuthError('You must provide a new username'));
  3354. }
  3355. if (!oldUsername) {
  3356. return callback(new AuthError('You must provide a username to rename'));
  3357. }
  3358. return db.getUser(newUsername, opts)
  3359. .then(function () {
  3360. var error = new AuthError('user already exists');
  3361. error.taken = true;
  3362. throw error;
  3363. }, function () {
  3364. return db.getUser(oldUsername, opts);
  3365. })
  3366. .then(function (user) {
  3367. var newUser = utils.clone(user);
  3368. delete newUser._rev;
  3369. newUser._id = USERNAME_PREFIX + newUsername;
  3370. newUser.name = newUsername;
  3371. newUser.roles = opts.roles || user.roles || {};
  3372. return updateUser(newUser, opts).then(function () {
  3373. user._deleted = true;
  3374. return updateUser(user, opts);
  3375. });
  3376. }).then(function (res) {
  3377. callback(null, res);
  3378. }).catch(callback);
  3379. });
  3380. function AuthError(message) {
  3381. this.status = 400;
  3382. this.name = 'authentication_error';
  3383. this.message = message;
  3384. this.error = true;
  3385. try {
  3386. Error.captureStackTrace(this, AuthError);
  3387. } catch (e) {}
  3388. }
  3389. utils.inherits(AuthError, Error);
  3390. if (typeof window !== 'undefined' && window.PouchDB) {
  3391. window.PouchDB.plugin(exports);
  3392. }
  3393. },{"1":1}]},{},[17])(17)
  3394. });