diff --git a/README.md b/README.md index b810343c..df2f7806 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# polymer-cdn v1.6.1 +# polymer-cdn v1.7.0 **A mirror of Polymer's components so that they can be used directly from CDN** ![Polymer CDN is powered by MaxCDN](http://i.imgur.com/9obTXpk.png) @@ -6,7 +6,7 @@ ## How to use In general, given an element named `my-cool-element`, the CDN url for it will be: ``` -https://cdn.rawgit.com/download/polymer-cdn/1.6.1/lib/my-cool-element/my-cool-element.html +https://cdn.rawgit.com/download/polymer-cdn/1.7.0/lib/my-cool-element/my-cool-element.html ``` To be sure, browse this repo and copy-paste the url to the raw version into [RawGit](https://rawgit.com). @@ -45,7 +45,7 @@ which explains it in more detail. ## Contents -All the libraries available in polymer-cdn can be found side-by-side in the [lib](https://github.com/Download/polymer-cdn/tree/1.6.1/lib) subfolder. +All the libraries available in polymer-cdn can be found side-by-side in the [lib](https://github.com/Download/polymer-cdn/tree/1.7.0/lib) subfolder. Some of the libraries depend on other libraries. We call those other libraries the dependencies of the library. These dependencies will also be pulled into your page when you include such a library. @@ -58,1347 +58,1372 @@ These dependencies are themselves also listed at the top-level, so you can work tree for a library by carefully examining this diagram. ```sh -polymer-cdn#1.6.1 +polymer-cdn#1.7.0 ├─┬ app-elements#0.10.0 │ ├─┬ app-layout#0.10.4 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-media-query#1.0.8 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-scroll-target-behavior#1.0.8 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├── iron-scroll-target-behavior#1.1.0 +│ │ └── polymer#1.7.0 │ ├─┬ app-localize-behavior#0.9.2 (latest is 0.10.0) │ │ ├── intl-messageformat#1.3.0 │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ app-pouchdb#0.9.2 -│ │ ├─┬ app-storage#0.9.5 -│ │ │ ├── polymer#1.6.1 +│ │ ├─┬ app-storage#0.9.7 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── polymer#1.6.1 -│ │ ├── pouchdb#6.0.4 +│ │ │ └── polymer#1.7.0 +│ │ ├── polymer#1.7.0 +│ │ ├── pouchdb#6.0.6 │ │ ├── pouchdb-find#0.10.3 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ app-route#0.9.2 -│ │ ├── iron-location#0.8.8 -│ │ └── polymer#1.6.1 -│ └── app-storage#0.9.5 +│ │ ├── iron-location#0.8.9 +│ │ └── polymer#1.7.0 +│ └── app-storage#0.9.7 ├── firebase-sdk extraneous ├─┬ gold-elements#1.0.1 │ ├─┬ gold-cc-cvc-input#1.0.9 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ gold-cc-expiration-input#1.1.2 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validator-behavior#1.0.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ gold-cc-input#1.0.7 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validator-behavior#1.0.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ gold-email-input#1.0.7 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ gold-phone-input#1.1.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-input#1.0.10 │ │ │ ├─┬ iron-a11y-announcer#1.0.5 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ └─┬ gold-zip-input#1.0.6 │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-icon#1.0.10 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-icon#1.0.11 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-validator-behavior#1.0.1 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├── paper-input#1.1.19 -│ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├── paper-input#1.1.20 +│ ├─┬ paper-styles#1.1.5 │ │ ├── font-roboto#1.0.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ └── polymer#1.6.1 -├─┬ google-web-components#1.1.0 -│ ├─┬ firebase-element#1.0.15 -│ │ ├── firebase#3.4.0 incompatible with ^2.3.1 (2.4.2 available, latest is 3.4.0) -│ │ └── polymer#1.6.1 -│ ├─┬ google-analytics#1.2.2 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ └── polymer#1.7.0 +├─┬ google-web-components#1.1.1 +│ ├─┬ firebase-element#1.0.16 +│ │ ├── firebase#3.4.1 incompatible with ^2.3.1 (2.4.2 available, latest is 3.4.1) +│ │ └── polymer#1.7.0 +│ ├─┬ google-analytics#1.2.3 │ │ ├── ga-api-utils#0.2.0 (latest is 0.6.0) -│ │ ├─┬ google-chart#1.1.0 -│ │ │ ├─┬ google-apis#1.1.6 +│ │ ├─┬ google-chart#1.1.1 +│ │ │ ├─┬ google-apis#1.1.7 │ │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ │ ├── polymer#1.6.1 +│ │ │ │ ├── polymer#1.7.0 │ │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ google-signin#1.3.6 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ google-signin#1.3.7 │ │ │ ├── font-roboto#1.0.1 -│ │ │ ├─┬ google-apis#1.1.6 +│ │ │ ├─┬ google-apis#1.1.7 │ │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├── iron-flex-layout#1.3.1 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ paper-material#1.0.6 -│ │ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── polymer#1.7.0 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-apis#1.1.6 +│ │ └── polymer#1.7.0 +│ ├─┬ google-apis#1.1.7 │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-calendar#1.0.2 -│ │ ├── google-apis#1.1.6 -│ │ ├── google-signin#1.3.6 -│ │ └── polymer#1.6.1 -│ ├─┬ google-castable-video#1.0.2 -│ │ └── polymer#1.6.1 -│ ├─┬ google-chart#1.1.0 -│ │ ├─┬ google-apis#1.1.6 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ google-calendar#1.0.3 +│ │ ├── google-apis#1.1.7 +│ │ ├── google-signin#1.3.7 +│ │ └── polymer#1.7.0 +│ ├─┬ google-castable-video#1.0.3 +│ │ └── polymer#1.7.0 +│ ├─┬ google-chart#1.1.1 +│ │ ├─┬ google-apis#1.1.7 │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├── polymer#1.7.0 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ google-feeds#1.0.2 -│ │ ├── google-apis#1.1.6 +│ │ ├── google-apis#1.1.7 │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-hangout-button#1.0.1 -│ │ ├─┬ google-apis#1.1.6 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ google-hangout-button#1.0.2 +│ │ ├─┬ google-apis#1.1.7 │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-map#1.1.11 -│ │ ├── google-apis#1.1.6 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ google-map#1.1.13 +│ │ ├── google-apis#1.1.7 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├── iron-selector#1.5.2 -│ │ └── polymer#1.6.1 -│ ├─┬ google-sheets#1.0.5 -│ │ ├── google-apis#1.1.6 -│ │ ├── google-signin#1.3.6 +│ │ └── polymer#1.7.0 +│ ├─┬ google-sheets#1.0.6 +│ │ ├── google-apis#1.1.7 +│ │ ├── google-signin#1.3.7 │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-signin#1.3.6 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ google-signin#1.3.7 │ │ ├── font-roboto#1.0.1 -│ │ ├─┬ google-apis#1.1.6 +│ │ ├─┬ google-apis#1.1.7 │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├── iron-flex-layout#1.3.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-material#1.0.6 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-ripple#1.0.10 │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ google-streetview-pano#1.0.3 -│ │ ├── google-apis#1.1.6 -│ │ └── polymer#1.6.1 -│ ├─┬ google-url-shortener#1.0.1 -│ │ ├─┬ google-apis#1.1.6 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ google-streetview-pano#1.0.4 +│ │ ├── google-apis#1.1.7 +│ │ ├── iron-resizable-behavior#1.0.5 +│ │ └── polymer#1.7.0 +│ ├─┬ google-url-shortener#1.0.2 +│ │ ├─┬ google-apis#1.1.7 │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ google-youtube#1.2.1 -│ │ ├─┬ google-apis#1.1.6 +│ │ ├─┬ google-apis#1.1.7 │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-localstorage#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ google-youtube-upload#1.1.2 (latest is 2.0.0) │ │ ├── cors-upload-sample#37c97848a2 -│ │ ├─┬ google-signin#1.3.6 +│ │ ├─┬ google-signin#1.3.7 │ │ │ ├── font-roboto#1.0.1 -│ │ │ ├─┬ google-apis#1.1.6 +│ │ │ ├─┬ google-apis#1.1.7 │ │ │ │ ├─┬ iron-jsonp-library#1.0.4 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├── iron-flex-layout#1.3.1 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ paper-material#1.0.6 -│ │ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ └─┬ polymerfire#0.9.7 -│ ├── app-storage#0.9.5 -│ ├── firebase#3.4.0 -│ └── polymer#1.6.1 +│ ├── app-storage#0.9.7 +│ ├── firebase#3.4.1 +│ └── polymer#1.7.0 ├─┬ iron-elements#1.0.10 │ ├─┬ iron-a11y-announcer#1.0.5 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-a11y-keys#1.0.6 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-ajax#1.4.3 -│ │ ├── polymer#1.6.1 +│ │ ├── polymer#1.7.0 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-autogrow-textarea#1.0.13 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-autogrow-textarea#1.0.14 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-behaviors#1.0.17 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-collapse#1.2.1 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-component-page#1.1.7 -│ │ ├── hydrolysis#1.24.1 +│ │ ├── hydrolysis#1.24.1 (latest is 2.0.0-alpha.10) │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-doc-viewer#1.0.15 │ │ │ ├─┬ marked-element#1.2.0 │ │ │ │ ├── marked#0.3.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ paper-button#1.0.13 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ paper-material#1.0.6 -│ │ │ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ prism-element#1.1.1 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └── prism#1.5.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-icons#1.1.3 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-selector#1.5.2 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-header-panel#1.1.6 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-header-panel#1.1.7 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-toolbar#1.1.6 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-toolbar#1.1.7 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── paper-styles#1.1.4 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── paper-styles#1.1.5 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-demo-helpers#1.2.5 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-icons#1.1.3 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-location#0.8.8 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-location#0.8.9 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ marked-element#1.2.0 │ │ │ ├── marked#0.3.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-icon-button#1.1.2 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-icon-button#1.1.3 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── polymer#1.7.0 │ │ └── prism-element#1.1.1 │ ├── iron-doc-viewer#1.0.15 │ ├─┬ iron-dropdown#1.5.2 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── iron-overlay-behavior#1.8.6 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── iron-overlay-behavior#1.9.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ neon-animation#1.2.4 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── polymer#1.7.0 │ │ │ └── web-animations-js#2.2.2 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-fit-behavior#1.2.5 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-flex-layout#1.3.1 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-form#1.1.4 │ │ ├─┬ iron-ajax#1.4.3 -│ │ │ ├── polymer#1.6.1 +│ │ │ ├── polymer#1.7.0 │ │ │ └─┬ promise-polyfill#1.0.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-icon#1.0.10 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-icon#1.0.11 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-icons#1.1.3 -│ │ ├─┬ iron-icon#1.0.10 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-iconset#1.0.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-iconset#1.0.5 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-iconset-svg#1.0.11 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├── iron-image#1.2.5 │ ├─┬ iron-input#1.0.10 │ │ ├─┬ iron-a11y-announcer#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-jsonp-library#1.0.4 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-label#1.0.2 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-list#1.3.9 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-list#1.3.11 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-scroll-target-behavior#1.0.8 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-scroll-target-behavior#1.1.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-localstorage#1.0.6 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-location#0.8.8 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-location#0.8.9 +│ │ └── polymer#1.7.0 │ ├─┬ iron-media-query#1.0.8 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-menu-behavior#1.1.10 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-menu-behavior#1.2.0 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-selector#1.5.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-meta#1.1.2 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-overlay-behavior#1.8.6 +│ │ └── polymer#1.7.0 +│ ├─┬ iron-overlay-behavior#1.9.0 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-fit-behavior#1.2.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-pages#1.0.8 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-selector#1.5.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-range-behavior#1.0.6 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ └── polymer#1.6.1 -│ ├─┬ iron-scroll-target-behavior#1.0.8 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 +│ ├── iron-scroll-target-behavior#1.1.0 │ ├─┬ iron-scroll-threshold#1.0.2 -│ │ ├─┬ iron-scroll-target-behavior#1.0.8 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ ├── iron-scroll-target-behavior#1.1.0 +│ │ └── polymer#1.7.0 │ ├─┬ iron-selector#1.5.2 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-signals#1.0.3 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-swipeable-container#1.0.3 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-test-helpers#1.2.5 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-validatable-behavior#1.1.1 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ └─┬ iron-validator-behavior#1.0.1 │ ├─┬ iron-meta#1.1.2 -│ │ └── polymer#1.6.1 -│ └── polymer#1.6.1 -├─┬ iron-page-url#0.7.3 extraneous (latest is 0.8.8) -│ └─┬ polymer#1.6.1 +│ │ └── polymer#1.7.0 +│ └── polymer#1.7.0 +├─┬ iron-page-url#0.7.3 extraneous (latest is 0.8.9) +│ └─┬ polymer#1.7.0 │ └── webcomponentsjs#0.7.22 ├─┬ molecules#1.0.0 │ └─┬ marked-element#1.2.0 │ ├── marked#0.3.6 -│ └── polymer#1.6.1 +│ └── polymer#1.7.0 ├─┬ neon-elements#1.0.0 │ └─┬ neon-animation#1.2.4 │ ├─┬ iron-meta#1.1.2 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ iron-selector#1.5.2 -│ │ └── polymer#1.6.1 -│ ├── polymer#1.6.1 +│ │ └── polymer#1.7.0 +│ ├── polymer#1.7.0 │ └── web-animations-js#2.2.2 ├─┬ paper-elements#1.0.7 -│ ├─┬ paper-badge#1.1.3 +│ ├─┬ paper-badge#1.1.4 +│ │ ├─┬ iron-flex-layout#1.3.1 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 +│ │ │ ├─┬ iron-flex-layout#1.3.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-meta#1.1.2 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-behaviors#1.0.12 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-ripple#1.0.10 │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-button#1.0.13 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-material#1.0.6 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-card#1.1.2 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-card#1.1.4 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-image#1.2.5 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-material#1.0.6 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-checkbox#1.4.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-checkbox#1.4.1 │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-ripple#1.0.10 │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 │ ├─┬ paper-dialog#1.1.0 -│ │ ├── iron-overlay-behavior#1.8.6 +│ │ ├── iron-overlay-behavior#1.9.0 │ │ ├─┬ neon-animation#1.2.4 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── polymer#1.7.0 │ │ │ └── web-animations-js#2.2.2 │ │ ├─┬ paper-dialog-behavior#1.2.7 -│ │ │ ├─┬ iron-overlay-behavior#1.8.6 +│ │ │ ├─┬ iron-overlay-behavior#1.9.0 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-fit-behavior#1.2.5 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── paper-styles#1.1.4 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── paper-styles#1.1.5 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-dialog-behavior#1.2.7 -│ │ ├─┬ iron-overlay-behavior#1.8.6 +│ │ ├─┬ iron-overlay-behavior#1.9.0 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-fit-behavior#1.2.5 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 │ ├─┬ paper-dialog-scrollable#1.1.5 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-dialog-behavior#1.2.7 -│ │ │ ├─┬ iron-overlay-behavior#1.8.6 +│ │ │ ├─┬ iron-overlay-behavior#1.9.0 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-fit-behavior#1.2.5 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── paper-styles#1.1.4 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── paper-styles#1.1.5 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-drawer-panel#1.0.10 │ │ ├─┬ iron-media-query#1.0.8 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-selector#1.5.2 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-dropdown-menu#1.4.1 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-input#1.1.19 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-input#1.1.20 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-autogrow-textarea#1.0.13 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ iron-autogrow-textarea#1.0.14 │ │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-input#1.0.10 │ │ │ │ ├─┬ iron-a11y-announcer#1.0.5 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├── paper-styles#1.1.4 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── paper-styles#1.1.5 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-menu-button#1.5.2 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-dropdown#1.5.2 │ │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ ├── iron-overlay-behavior#1.8.6 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├── iron-overlay-behavior#1.9.0 │ │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ neon-animation#1.2.4 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ ├── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ ├── polymer#1.7.0 │ │ │ │ │ └── web-animations-js#2.2.2 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├── iron-fit-behavior#1.2.5 │ │ │ ├─┬ neon-animation#1.2.4 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ ├── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├── polymer#1.7.0 │ │ │ │ └── web-animations-js#2.2.2 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-ripple#1.0.10 │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-fab#1.2.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-fab#1.2.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icons#1.1.3 -│ │ │ ├─┬ iron-icon#1.0.10 -│ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ iron-iconset-svg#1.0.9 -│ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├── paper-material#1.0.6 -│ │ ├─┬ paper-styles#1.1.4 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-header-panel#1.1.6 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-header-panel#1.1.7 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-icon-button#1.1.2 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-icon-button#1.1.3 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├── paper-input#1.1.19 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├── paper-input#1.1.20 │ ├─┬ paper-item#1.2.1 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-listbox#1.1.2 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-collapse#1.2.1 │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-menu-behavior#1.1.10 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-menu-behavior#1.2.0 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-material#1.0.6 -│ │ ├─┬ paper-styles#1.1.4 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-menu#1.2.2 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-collapse#1.2.1 │ │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-menu-behavior#1.1.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-menu-behavior#1.2.0 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-selector#1.5.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├── paper-menu-button#1.5.2 -│ ├─┬ paper-progress#1.0.10 +│ ├─┬ paper-progress#1.0.11 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-range-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-radio-button#1.2.1 │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├── iron-flex-layout#1.3.1 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-radio-group#1.2.0 -│ │ ├── iron-menu-behavior#1.1.10 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-ripple#1.0.8 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-radio-group#1.2.1 +│ │ ├─┬ iron-a11y-keys-behavior#1.1.9 +│ │ │ └── polymer#1.7.0 +│ │ ├── iron-menu-behavior#1.2.0 +│ │ ├─┬ paper-radio-button#1.2.1 +│ │ │ ├─┬ iron-checked-element-behavior#1.0.5 +│ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 +│ │ │ │ │ ├─┬ iron-meta#1.1.2 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── iron-flex-layout#1.3.1 +│ │ │ ├─┬ paper-behaviors#1.0.12 +│ │ │ │ ├─┬ iron-behaviors#1.0.17 +│ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 +│ │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 +│ │ │ │ │ │ ├─┬ iron-meta#1.1.2 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├─┬ paper-ripple#1.0.10 +│ │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├── paper-styles#1.1.5 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-ripple#1.0.10 │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ paper-scroll-header-panel#1.0.16 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-slider#1.0.11 │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-input#1.1.19 -│ │ ├─┬ paper-progress#1.0.10 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-input#1.1.20 +│ │ ├─┬ paper-progress#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-range-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-spinner#1.2.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-spinner#1.2.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-styles#1.1.4 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-styles#1.1.5 │ │ ├── font-roboto#1.0.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-tabs#1.6.2 │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-icon#1.0.10 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-icon#1.0.11 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ iron-iconset-svg#1.0.9 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ iron-iconset-svg#1.0.11 │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── iron-menu-behavior#1.1.10 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── iron-menu-behavior#1.2.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-icon-button#1.1.2 -│ │ │ ├─┬ iron-icon#1.0.10 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-icon-button#1.1.3 +│ │ │ ├─┬ iron-icon#1.0.11 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ │ └── polymer#1.7.0 │ │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-styles#1.1.5 │ │ │ │ ├── font-roboto#1.0.1 │ │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├─┬ paper-styles#1.1.4 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├─┬ paper-styles#1.1.5 │ │ │ ├── font-roboto#1.0.1 │ │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 │ ├─┬ paper-toast#1.3.0 │ │ ├─┬ iron-a11y-announcer#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├── iron-fit-behavior#1.2.5 -│ │ ├── iron-overlay-behavior#1.8.6 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-toggle-button#1.2.0 +│ │ ├── iron-overlay-behavior#1.9.0 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-toggle-button#1.2.1 │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ paper-behaviors#1.0.12 │ │ │ ├─┬ iron-behaviors#1.0.17 │ │ │ │ ├─┬ iron-a11y-keys-behavior#1.1.9 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 │ │ │ ├─┬ iron-checked-element-behavior#1.0.5 │ │ │ │ ├─┬ iron-form-element-behavior#1.0.6 -│ │ │ │ │ └── polymer#1.6.1 +│ │ │ │ │ └── polymer#1.7.0 │ │ │ │ ├─┬ iron-validatable-behavior#1.1.1 │ │ │ │ │ ├─┬ iron-meta#1.1.2 -│ │ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ │ └── polymer#1.6.1 -│ │ │ │ └── polymer#1.6.1 -│ │ │ ├─┬ paper-ripple#1.0.8 +│ │ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ │ └── polymer#1.7.0 +│ │ │ │ └── polymer#1.7.0 +│ │ │ ├─┬ paper-ripple#1.0.10 │ │ │ │ ├── iron-a11y-keys-behavior#1.1.9 -│ │ │ │ └── polymer#1.6.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 -│ ├─┬ paper-toolbar#1.1.6 +│ │ │ │ └── polymer#1.7.0 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 +│ ├─┬ paper-toolbar#1.1.7 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ ├── paper-styles#1.1.4 -│ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├── paper-styles#1.1.5 +│ │ └── polymer#1.7.0 │ └─┬ paper-tooltip#1.1.3 │ ├─┬ neon-animation#1.2.4 │ │ ├─┬ iron-meta#1.1.2 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-resizable-behavior#1.0.5 -│ │ │ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 │ │ ├─┬ iron-selector#1.5.2 -│ │ │ └── polymer#1.6.1 -│ │ ├── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ ├── polymer#1.7.0 │ │ └── web-animations-js#2.2.2 -│ ├─┬ paper-styles#1.1.4 +│ ├─┬ paper-styles#1.1.5 │ │ ├── font-roboto#1.0.1 │ │ ├─┬ iron-flex-layout#1.3.1 -│ │ │ └── polymer#1.6.1 -│ │ └── polymer#1.6.1 -│ └── polymer#1.6.1 +│ │ │ └── polymer#1.7.0 +│ │ └── polymer#1.7.0 +│ └── polymer#1.7.0 ├─┬ platinum-elements#2.0.0 -│ ├─┬ platinum-bluetooth#2.1.1 -│ │ ├── polymer#1.6.1 +│ ├─┬ platinum-bluetooth#2.1.2 +│ │ ├── polymer#1.7.0 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ platinum-https-redirect#1.0.2 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ ├─┬ platinum-push-messaging#1.0.5 -│ │ ├── polymer#1.6.1 +│ │ ├── polymer#1.7.0 │ │ └─┬ promise-polyfill#1.0.1 -│ │ └── polymer#1.6.1 +│ │ └── polymer#1.7.0 │ └─┬ platinum-sw#1.3.0 -│ ├── polymer#1.6.1 -│ └── sw-toolbox#3.2.1 -└─┬ polymer#1.6.1 +│ ├── polymer#1.7.0 +│ └── sw-toolbox#3.3.0 +└─┬ polymer#1.7.0 └── webcomponentsjs#0.7.22 ``` \ No newline at end of file diff --git a/bower.json b/bower.json index fc358a00..789de6a7 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "polymer-cdn", - "version": "1.6.1", + "version": "1.7.0", "main": "polymer.js", "homepage": "https://github.com/Download/polymer-cdn", "authors": [ diff --git a/lib/app-storage/.bower.json b/lib/app-storage/.bower.json index 772bcafd..17edca3c 100644 --- a/lib/app-storage/.bower.json +++ b/lib/app-storage/.bower.json @@ -3,7 +3,7 @@ "authors": [ "The Polymer Authors" ], - "version": "0.9.5", + "version": "0.9.7", "description": "Web Components for managing user data in web apps", "main": [ "app-storage-behavior.html", @@ -12,7 +12,7 @@ "app-indexeddb-mirror/app-indexeddb-mirror.html" ], "moduleType": [], - "license": "MIT", + "license": "http://polymer.github.io/LICENSE.txt", "homepage": "https://github.com/PolymerElements/app-storage", "private": true, "dependencies": { @@ -33,11 +33,11 @@ "platinum-sw": "polymerelements/platinum-sw#^1.3.0" }, "ignore": [], - "_release": "0.9.5", + "_release": "0.9.7", "_resolution": { "type": "version", - "tag": "v0.9.5", - "commit": "498a32135fc661102e30f345498268c2efd303ae" + "tag": "v0.9.7", + "commit": "3a2284d09f6abb40832b8f8c4847ec27456e056b" }, "_source": "git://github.com/PolymerElements/app-storage.git", "_target": "^0.9.0", diff --git a/lib/app-storage/app-indexeddb-mirror/app-indexeddb-mirror-client.html b/lib/app-storage/app-indexeddb-mirror/app-indexeddb-mirror-client.html index 5fec36b8..5f6d8e7a 100644 --- a/lib/app-storage/app-indexeddb-mirror/app-indexeddb-mirror-client.html +++ b/lib/app-storage/app-indexeddb-mirror/app-indexeddb-mirror-client.html @@ -57,6 +57,12 @@ * the session has been validated. */ validateSession: function(session) { + if (session === undefined) { + // Ignore session `undefined` conventionally, as it means the session + // (such as the user ID) has not been initialized yet. + return; + } + return this.post({ type: 'app-mirror-validate-session', session: session diff --git a/lib/app-storage/app-indexeddb-mirror/common-worker.html b/lib/app-storage/app-indexeddb-mirror/common-worker.html index 52703e4f..8b5b1488 100644 --- a/lib/app-storage/app-indexeddb-mirror/common-worker.html +++ b/lib/app-storage/app-indexeddb-mirror/common-worker.html @@ -14,7 +14,13 @@ var WEB_WORKERS = {}; var HAS_SHARED_WORKER = typeof SharedWorker !== 'undefined'; var HAS_WEB_WORKER = typeof Worker !== 'undefined'; - var BASE_URI = document._currentScript.ownerDocument.baseURI; + // NOTE(cdata): see http://www.2ality.com/2014/05/current-script.html + var currentScript = document._currentScript || document.currentScript || + (function() { + var scripts = document.getElementsByTagName('script'); + return scripts[scripts.length - 1]; + })(); + var BASE_URI = currentScript.ownerDocument.baseURI; var WORKER_SCOPE_URL = Polymer.ResolveUrl.resolveUrl('common-worker-scope.js', BASE_URI); diff --git a/lib/app-storage/bower.json b/lib/app-storage/bower.json index 3cb375a2..1cf97a9b 100644 --- a/lib/app-storage/bower.json +++ b/lib/app-storage/bower.json @@ -3,7 +3,7 @@ "authors": [ "The Polymer Authors" ], - "version": "0.9.5", + "version": "0.9.7", "description": "Web Components for managing user data in web apps", "main": [ "app-storage-behavior.html", @@ -12,7 +12,7 @@ "app-indexeddb-mirror/app-indexeddb-mirror.html" ], "moduleType": [], - "license": "MIT", + "license": "http://polymer.github.io/LICENSE.txt", "homepage": "", "private": true, "dependencies": { diff --git a/lib/app-storage/test/app-indexeddb-mirror/app-indexeddb-mirror.html b/lib/app-storage/test/app-indexeddb-mirror/app-indexeddb-mirror.html index 3b9d8d03..58a0ecc4 100644 --- a/lib/app-storage/test/app-indexeddb-mirror/app-indexeddb-mirror.html +++ b/lib/app-storage/test/app-indexeddb-mirror/app-indexeddb-mirror.html @@ -35,7 +35,15 @@ + + + + @@ -113,6 +121,32 @@ }); }); + suite('when session is set lazily', function() { + var secondMirror; + + setup(function() { + mirror.data = { + foo: 'bar' + }; + secondMirror = fixture('NoSessionMirror'); + return Promise.all([ + mirror.transactionsComplete, + secondMirror.transactionsComplete + ]); + }); + + test('the data is preserved', function() { + if (!mirror.client.supportsMirroring) { + return; + } + + secondMirror.session = 'test'; + return secondMirror.transactionsComplete.then(function() { + return expectPersistedValue('basic-mirror', mirror.data); + }); + }); + }); + suite('when offline', function() { test('boots up with persisted value', function() { if (!mirror.client.supportsMirroring) { diff --git a/lib/firebase-element/.bower.json b/lib/firebase-element/.bower.json index d0d07192..d92a7776 100644 --- a/lib/firebase-element/.bower.json +++ b/lib/firebase-element/.bower.json @@ -1,7 +1,7 @@ { "name": "firebase-element", "description": "An element that makes it easy to declaratively use the powerful firebase backend", - "version": "1.0.15", + "version": "1.0.16", "private": true, "main": [ "firebase-collection.html", @@ -9,6 +9,7 @@ "firebase-auth.html", "firebase-query-behavior.html" ], + "license": "http://polymer.github.io/LICENSE.txt", "dependencies": { "polymer": "polymer/polymer#^1.0.0", "firebase": "^2.3.1" @@ -29,11 +30,11 @@ "web-component-tester": "*" }, "homepage": "https://github.com/GoogleWebComponents/firebase-element", - "_release": "1.0.15", + "_release": "1.0.16", "_resolution": { "type": "version", - "tag": "1.0.15", - "commit": "210a8bbce8ed80fc71a2f57b9ae1fffdd2a12bae" + "tag": "v1.0.16", + "commit": "3d2495b40868108ca70993b202e899492ae619fb" }, "_source": "git://github.com/GoogleWebComponents/firebase-element.git", "_target": "^1.0.0", diff --git a/lib/firebase-element/bower.json b/lib/firebase-element/bower.json index 7da0920e..dd589f13 100644 --- a/lib/firebase-element/bower.json +++ b/lib/firebase-element/bower.json @@ -1,9 +1,10 @@ { "name": "firebase-element", "description": "An element that makes it easy to declaratively use the powerful firebase backend", - "version": "1.0.15", + "version": "1.0.16", "private": true, "main": ["firebase-collection.html","firebase-document.html","firebase-auth.html","firebase-query-behavior.html"], + "license": "http://polymer.github.io/LICENSE.txt", "dependencies": { "polymer": "polymer/polymer#^1.0.0", "firebase": "^2.3.1" diff --git a/lib/firebase/.bower.json b/lib/firebase/.bower.json index eb2c3e90..9cf31772 100644 --- a/lib/firebase/.bower.json +++ b/lib/firebase/.bower.json @@ -1,6 +1,6 @@ { "name": "firebase", - "version": "3.4.0", + "version": "3.4.1", "homepage": "https://firebase.google.com", "authors": [ "Firebase " @@ -23,11 +23,11 @@ "test", "tests" ], - "_release": "3.4.0", + "_release": "3.4.1", "_resolution": { "type": "version", - "tag": "v3.4.0", - "commit": "255097a09f8f2ab9a1e6f903ebf68a6b9eb8c3cf" + "tag": "v3.4.1", + "commit": "82b24fbe04b115ac21348302ed323fbb19644056" }, "_source": "https://github.com/firebase/firebase-bower.git", "_target": "^3.0", diff --git a/lib/firebase/bower.json b/lib/firebase/bower.json index ef697262..00f37ade 100644 --- a/lib/firebase/bower.json +++ b/lib/firebase/bower.json @@ -1,6 +1,6 @@ { "name": "firebase", - "version": "3.4.0", + "version": "3.4.1", "homepage": "https://firebase.google.com", "authors": [ "Firebase " diff --git a/lib/firebase/firebase.js b/lib/firebase/firebase.js index 4f18b3ff..4a50e5cb 100644 --- a/lib/firebase/firebase.js +++ b/lib/firebase/firebase.js @@ -1,36 +1,36 @@ -/*! @license Firebase v3.4.0 - Build: 3.4.0-rc.3 +/*! @license Firebase v3.4.1 + Build: 3.4.1-rc.2 Terms: https://developers.google.com/terms */ -var firebase = null; (function() { var aa="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(c.get||c.set)throw new TypeError("ES3 does not support getters and setters.");a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)},h="undefined"!=typeof window&&window===this?this:"undefined"!=typeof global?global:this,k=function(){k=function(){};h.Symbol||(h.Symbol=ba)},ca=0,ba=function(a){return"jscomp_symbol_"+(a||"")+ca++},n=function(){k();var a=h.Symbol.iterator;a||(a=h.Symbol.iterator=h.Symbol("iterator")); -"function"!=typeof Array.prototype[a]&&aa(Array.prototype,a,{configurable:!0,writable:!0,value:function(){return m(this)}});n=function(){}},m=function(a){var b=0;return da(function(){return be?b:null===d?d=Object.getOwnPropertyDescriptor(b,c):d,g;g=z.Reflect;if("object"===typeof g&&"function"===typeof g.decorate)f=g.decorate(a,b,c,d);else for(var l=a.length-1;0<=l;l--)if(g=a[l])f=(3>e?g(f):3e?b:null===d?d=Object.getOwnPropertyDescriptor(b,c):d,g;g=z.Reflect;if("object"===typeof g&&"function"===typeof g.decorate)f=g.decorate(a,b,c,d);else for(var k=a.length-1;0<=k;k--)if(g=a[k])f=(3>e?g(f):3"}),c=this.W+": "+c+" ("+a+").",c=new R(a,c),d;for(d in b)b.hasOwnProperty(d)&&"_"!==d.slice(-1)&&(c[d]=b[d]);return c};O.all=function(a){return new O(function(b,c){var d=a.length,e=[];if(d)for(var f=function(a,c){d--;e[a]=c;0==d&&b(e)},g=function(a){c(a)},l=0,p;l"}),c=this.W+": "+c+" ("+a+").",c=new V(a,c),d;for(d in b)b.hasOwnProperty(d)&&"_"!==d.slice(-1)&&(c[d]=b[d]);return c};var W=Q,X=function(a,b,c){var d=this;this.H=c;this.I=!1;this.i={};this.C=b;this.T=P(void 0,a);Object.keys(c.INTERNAL.factories).forEach(function(a){var b=c.INTERNAL.useAsService(d,a);null!==b&&(b=d.R.bind(d,b),d[a]=b)})};X.prototype.delete=function(){var a=this;return(new W(function(b){Y(a);b()})).then(function(){a.H.INTERNAL.removeApp(a.C);return W.all(Object.keys(a.i).map(function(b){return a.i[b].INTERNAL.delete()}))}).then(function(){a.I=!0;a.i={}})}; X.prototype.R=function(a){Y(this);void 0===this.i[a]&&(this.i[a]=this.H.INTERNAL.factories[a](this,this.P.bind(this)));return this.i[a]};X.prototype.P=function(a){P(this,a)};var Y=function(a){a.I&&Z(Ia("deleted",{name:a.C}))};h.Object.defineProperties(X.prototype,{name:{configurable:!0,enumerable:!0,get:function(){Y(this);return this.C}},options:{configurable:!0,enumerable:!0,get:function(){Y(this);return this.T}}});X.prototype.name&&X.prototype.options||X.prototype.delete||console.log("dc"); function Ja(){function a(a){a=a||"[DEFAULT]";var b=d[a];void 0===b&&Z("noApp",{name:a});return b}function b(a,b){Object.keys(e).forEach(function(d){d=c(a,d);if(null!==d&&f[d])f[d](b,a)})}function c(a,b){if("serverAuth"===b)return null;var c=b;a=a.options;"auth"===b&&(a.serviceAccount||a.credential)&&(c="serverAuth","serverAuth"in e||Z("serverAuthMissing"));return c}var d={},e={},f={},g={__esModule:!0,initializeApp:function(a,c){void 0===c?c="[DEFAULT]":"string"===typeof c&&""!==c||Z("bad-app-name", {name:c+""});void 0!==d[c]&&Z("dupApp",{name:c});a=new X(a,c,g);d[c]=a;b(a,"create");void 0!=a.INTERNAL&&void 0!=a.INTERNAL.getToken||P(a,{INTERNAL:{getToken:function(){return W.resolve(null)},addAuthTokenListener:function(){},removeAuthTokenListener:function(){}}});return a},app:a,apps:null,Promise:W,SDK_VERSION:"0.0.0",INTERNAL:{registerService:function(b,c,d,u){e[b]&&Z("dupService",{name:b});e[b]=c;u&&(f[b]=u);c=function(c){void 0===c&&(c=a());return c[b]()};void 0!==d&&P(c,d);return g[b]=c},createFirebaseNamespace:Ja, -extendNamespace:function(a){P(g,a)},createSubscribe:Fa,ErrorFactory:Q,removeApp:function(a){b(d[a],"delete");delete d[a]},factories:e,useAsService:c,Promise:O,deepExtend:P}};g["default"]=g;Object.defineProperty(g,"apps",{get:function(){return Object.keys(d).map(function(a){return d[a]})}});a.App=X;return g}function Z(a,b){throw Error(Ia(a,b));} +extendNamespace:function(a){P(g,a)},createSubscribe:Ea,ErrorFactory:U,removeApp:function(a){b(d[a],"delete");delete d[a]},factories:e,useAsService:c,Promise:O,deepExtend:P}};g["default"]=g;Object.defineProperty(g,"apps",{get:function(){return Object.keys(d).map(function(a){return d[a]})}});a.App=X;return g}function Z(a,b){throw Error(Ia(a,b));} function Ia(a,b){b=b||{};b={noApp:"No Firebase App '"+b.name+"' has been created - call Firebase App.initializeApp().","bad-app-name":"Illegal App name: '"+b.name+"'.",dupApp:"Firebase App named '"+b.name+"' already exists.",deleted:"Firebase App named '"+b.name+"' already deleted.",dupService:"Firebase Service named '"+b.name+"' already registered.",serverAuthMissing:"Initializing the Firebase SDK with a service account is only allowed in a Node.js environment. On client devices, you should instead initialize the SDK with an api key and auth domain."}[a]; return void 0===b?"Application Error: ("+a+")":b};"undefined"!==typeof firebase&&(firebase=Ja()); })(); -firebase.SDK_VERSION = "3.4.0"; +firebase.SDK_VERSION = "3.4.1"; (function(){var h,aa=aa||{},l=this,ba=function(){},ca=function(){throw Error("unimplemented abstract method");},m=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!= typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b},da=function(a){return null===a},ea=function(a){return"array"==m(a)},fa=function(a){var b=m(a);return"array"==b||"object"==b&&"number"==typeof a.length},n=function(a){return"string"==typeof a},ga=function(a){return"number"==typeof a},p=function(a){return"function"==m(a)},ha=function(a){var b=typeof a; -return"object"==b&&null!=a||"function"==b},ia=function(a,b,c){return a.call.apply(a.bind,arguments)},ja=function(a,b,c){if(!a)throw Error();if(2/g,sa=/"/g,ta=/'/g,ua=/\x00/g,va=/[\x00&<>"']/,v=function(a,b){return-1!=a.indexOf(b)},wa=function(a,b){return ab?1:0};var xa=function(a,b){b.unshift(a);u.call(this,ma.apply(null,b));b.shift()};t(xa,u);xa.prototype.name="AssertionError"; +return"object"==b&&null!=a||"function"==b},ia=function(a,b,c){return a.call.apply(a.bind,arguments)},ja=function(a,b,c){if(!a)throw Error();if(2/g,ra=/"/g,ta=/'/g,ua=/\x00/g,va=/[\x00&<>"']/,v=function(a,b){return-1!=a.indexOf(b)},wa=function(a,b){return ab?1:0};var xa=function(a,b){b.unshift(a);u.call(this,ma.apply(null,b));b.shift()};t(xa,u);xa.prototype.name="AssertionError"; var ya=function(a,b,c,d){var e="Assertion failed";if(c)var e=e+(": "+c),f=d;else a&&(e+=": "+a,f=b);throw new xa(""+e,f||[]);},w=function(a,b,c){a||ya("",null,b,Array.prototype.slice.call(arguments,2))},za=function(a,b){throw new xa("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));},Aa=function(a,b,c){ga(a)||ya("Expected number but got %s: %s.",[m(a),a],b,Array.prototype.slice.call(arguments,2));return a},Ba=function(a,b,c){n(a)||ya("Expected string but got %s: %s.",[m(a),a],b,Array.prototype.slice.call(arguments, 2))},Ca=function(a,b,c){p(a)||ya("Expected function but got %s: %s.",[m(a),a],b,Array.prototype.slice.call(arguments,2))};var Da=Array.prototype.indexOf?function(a,b,c){w(null!=a.length);return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(n(a))return n(b)&&1==b.length?a.indexOf(b,c):-1;for(;cparseFloat(lb)){kb=String(nb);break a}}kb=lb} -var ob=kb,cb={},A=function(a){return db(a,function(){for(var b=0,c=na(String(ob)).split("."),d=na(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f>4);64!=g&&(b(f<<4&240|g>>2),64!=k&&b(g<<6&192|k))}},vb=function(){if(!rb){rb={};sb={};for(var a=0;65>a;a++)rb[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a), -sb[rb[a]]=a,62<=a&&(sb["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a)]=a)}};var wb=!z||9<=Number(qb),xb=z&&!A("9");!ib||A("528");hb&&A("1.9b")||z&&A("8")||eb&&A("9.5")||ib&&A("528");hb&&!A("8")||z&&A("9");var yb=function(){this.ya=this.ya;this.Tb=this.Tb};yb.prototype.ya=!1;yb.prototype.isDisposed=function(){return this.ya};yb.prototype.Oa=function(){if(this.Tb)for(;this.Tb.length;)this.Tb.shift()()};var zb=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.Va=!1;this.ud=!0};zb.prototype.preventDefault=function(){this.defaultPrevented=!0;this.ud=!1};var Ab=function(a,b){zb.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;this.charCode=this.keyCode=this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.lb=this.state=null;a&&this.init(a,b)};t(Ab,zb); +var ob=kb,cb={},A=function(a){return db(a,function(){for(var b=0,c=na(String(ob)).split("."),d=na(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f>4);64!=g&&(b(f<<4&240|g>>2),64!=k&&b(g<<6&192|k))}},vb=function(){if(!rb){rb={};sb={};for(var a=0;65>a;a++)rb[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a), +sb[rb[a]]=a,62<=a&&(sb["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a)]=a)}};var wb=!z||9<=Number(pb),xb=z&&!A("9");!ib||A("528");hb&&A("1.9b")||z&&A("8")||eb&&A("9.5")||ib&&A("528");hb&&!A("8")||z&&A("9");var yb=function(){this.za=this.za;this.Vb=this.Vb};yb.prototype.za=!1;yb.prototype.isDisposed=function(){return this.za};yb.prototype.Pa=function(){if(this.Vb)for(;this.Vb.length;)this.Vb.shift()()};var zb=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.Wa=!1;this.wd=!0};zb.prototype.preventDefault=function(){this.defaultPrevented=!0;this.wd=!1};var Ab=function(a,b){zb.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;this.charCode=this.keyCode=this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.mb=this.state=null;a&&this.init(a,b)};t(Ab,zb); Ab.prototype.init=function(a,b){var c=this.type=a.type,d=a.changedTouches?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.currentTarget=b;if(b=a.relatedTarget){if(hb){var e;a:{try{bb(b.nodeName);e=!0;break a}catch(f){}e=!1}e||(b=null)}}else"mouseover"==c?b=a.fromElement:"mouseout"==c&&(b=a.toElement);this.relatedTarget=b;null===d?(this.offsetX=ib||void 0!==a.offsetX?a.offsetX:a.layerX,this.offsetY=ib||void 0!==a.offsetY?a.offsetY:a.layerY,this.clientX=void 0!==a.clientX?a.clientX: -a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0):(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0);this.button=a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||("keypress"==c?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.state=a.state;this.lb=a;a.defaultPrevented&& -this.preventDefault()};Ab.prototype.preventDefault=function(){Ab.Pc.preventDefault.call(this);var a=this.lb;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,xb)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};Ab.prototype.ce=function(){return this.lb};var Bb="closure_listenable_"+(1E6*Math.random()|0),Cb=0;var Db=function(a,b,c,d,e){this.listener=a;this.Xb=null;this.src=b;this.type=c;this.Cb=!!d;this.Kb=e;this.key=++Cb;this.$a=this.Bb=!1},Eb=function(a){a.$a=!0;a.listener=null;a.Xb=null;a.src=null;a.Kb=null};var Fb=function(a){this.src=a;this.w={};this.yb=0};Fb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.w[f];a||(a=this.w[f]=[],this.yb++);var g=Gb(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(g){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.currentTarget;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;!b.Va&&0<=e;e--){b.currentTarget=d[e];var f=Xb(d[e],a,!0,b),c=c&&f}for(e=0;!b.Va&&e>>0),Mb=function(a){w(a,"Listener can not be null.");if(p(a))return a;w(a.handleEvent,"An object listener must have handleEvent method.");a[Yb]||(a[Yb]=function(b){return a.handleEvent(b)});return a[Yb]};var Zb=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;var ac=function(){this.fc="";this.Md=$b};ac.prototype.Nb=!0;ac.prototype.Ib=function(){return this.fc};ac.prototype.toString=function(){return"Const{"+this.fc+"}"};var bc=function(a){if(a instanceof ac&&a.constructor===ac&&a.Md===$b)return a.fc;za("expected object of type Const, got '"+a+"'");return"type_error:Const"},$b={};var B=function(){this.ja="";this.Ld=cc};B.prototype.Nb=!0;B.prototype.Ib=function(){return this.ja};B.prototype.toString=function(){return"SafeUrl{"+this.ja+"}"}; -var dc=function(a){if(a instanceof B&&a.constructor===B&&a.Ld===cc)return a.ja;za("expected object of type SafeUrl, got '"+a+"' of type "+m(a));return"type_error:SafeUrl"},ec=/^(?:(?:https?|mailto|ftp):|[^&:/?#]*(?:[/?#]|$))/i,gc=function(a){if(a instanceof B)return a;a=a.Nb?a.Ib():String(a);ec.test(a)||(a="about:invalid#zClosurez");return fc(a)},cc={},fc=function(a){var b=new B;b.ja=a;return b};fc("about:blank");var hc=function(a){return/^\s*$/.test(a)?!1:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,""))},ic=function(a){a=String(a);if(hc(a))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);},lc=function(a){var b=[];jc(new kc,a,b);return b.join("")},kc=function(){this.ac=void 0}, -jc=function(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(ea(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f=a.keyCode)a.keyCode=-1}catch(b){}};Ab.prototype.fe=function(){return this.mb};var Bb="closure_listenable_"+(1E6*Math.random()|0),Cb=0;var Db=function(a,b,c,d,e){this.listener=a;this.Zb=null;this.src=b;this.type=c;this.Eb=!!d;this.Mb=e;this.key=++Cb;this.ab=this.Db=!1},Eb=function(a){a.ab=!0;a.listener=null;a.Zb=null;a.src=null;a.Mb=null};var Fb=function(a){this.src=a;this.w={};this.Ab=0};Fb.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.w[f];a||(a=this.w[f]=[],this.Ab++);var g=Gb(a,b,d,e);-1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(g){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.currentTarget;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;!b.Wa&&0<=e;e--){b.currentTarget=d[e];var f=Xb(d[e],a,!0,b),c=c&&f}for(e=0;!b.Wa&&e>>0),Mb=function(a){w(a,"Listener can not be null.");if(p(a))return a;w(a.handleEvent,"An object listener must have handleEvent method.");a[Yb]||(a[Yb]=function(b){return a.handleEvent(b)});return a[Yb]};var Zb=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;var ac=function(){this.hc="";this.Od=$b};ac.prototype.Pb=!0;ac.prototype.Kb=function(){return this.hc};ac.prototype.toString=function(){return"Const{"+this.hc+"}"};var bc=function(a){if(a instanceof ac&&a.constructor===ac&&a.Od===$b)return a.hc;za("expected object of type Const, got '"+a+"'");return"type_error:Const"},$b={};var B=function(){this.ja="";this.Nd=cc};B.prototype.Pb=!0;B.prototype.Kb=function(){return this.ja};B.prototype.toString=function(){return"SafeUrl{"+this.ja+"}"}; +var dc=function(a){if(a instanceof B&&a.constructor===B&&a.Nd===cc)return a.ja;za("expected object of type SafeUrl, got '"+a+"' of type "+m(a));return"type_error:SafeUrl"},ec=/^(?:(?:https?|mailto|ftp):|[^&:/?#]*(?:[/?#]|$))/i,gc=function(a){if(a instanceof B)return a;a=a.Pb?a.Kb():String(a);ec.test(a)||(a="about:invalid#zClosurez");return fc(a)},cc={},fc=function(a){var b=new B;b.ja=a;return b};fc("about:blank");var hc=function(a){return/^\s*$/.test(a)?!1:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,""))},ic=function(a){a=String(a);if(hc(a))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);},lc=function(a){var b=[];jc(new kc,a,b);return b.join("")},kc=function(){this.cc=void 0}, +jc=function(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(ea(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;fa){var b=xc[a];if(b)return b}b=new C([a|0],0>a?-1:0);-128<=a&&128>a&&(xc[a]=b);return b},F=function(a){if(isNaN(a)||!isFinite(a))return D;if(0>a)return E(F(-a));for(var b=[],c=1,d=0;a>=c;d++)b[d]=a/c|0,c*=4294967296;return new C(b,0)},zc=function(a,b){if(0==a.length)throw Error("number format error: empty string");b=b||10;if(2>b||36a){var b=xc[a];if(b)return b}b=new C([a|0],0>a?-1:0);-128<=a&&128>a&&(xc[a]=b);return b},F=function(a){if(isNaN(a)||!isFinite(a))return D;if(0>a)return E(F(-a));for(var b=[],c=1,d=0;a>=c;d++)b[d]=a/c|0,c*=4294967296;return new C(b,0)},zc=function(a,b){if(0==a.length)throw Error("number format error: empty string");b=b||10;if(2>b||36f?(f=F(Math.pow(b,f)),d=d.multiply(f).add(F(g))):(d=d.multiply(c),d=d.add(F(g)))}return d},D=yc(0),Ac=yc(1),Bc=yc(16777216),Cc=function(a){if(-1==a.g)return-Cc(E(a));for(var b=0,c=1,d=0;da||36>>0).toString(a),c=e;if(G(c))return f+d;for(;6>f.length;)f="0"+f;d=""+f+d}}; -var H=function(a,b){return 0>b?0:bb?0:b>>16)+(H(this,e)>>>16)+(H(a,e)>>>16),d=g>>>16,f=f&65535,g=g&65535;c[e]=g<<16|f}return new C(c,c[c.length-1]&-2147483648?-1:0)};var Fc=function(a,b){return a.add(E(b))}; -C.prototype.multiply=function(a){if(G(this)||G(a))return D;if(-1==this.g)return-1==a.g?E(this).multiply(E(a)):E(E(this).multiply(a));if(-1==a.g)return E(this.multiply(E(a)));if(0>this.compare(Bc)&&0>a.compare(Bc))return F(Cc(this)*Cc(a));for(var b=this.h.length+a.h.length,c=[],d=0;d<2*b;d++)c[d]=0;for(d=0;d>>16,g=H(this,d)&65535,k=H(a,e)>>>16,q=H(a,e)&65535;c[2*d+2*e]+=g*q;Gc(c,2*d+2*e);c[2*d+2*e+1]+=f*q;Gc(c,2*d+2*e+1);c[2*d+2*e+1]+= +C.prototype.multiply=function(a){if(G(this)||G(a))return D;if(-1==this.g)return-1==a.g?E(this).multiply(E(a)):E(E(this).multiply(a));if(-1==a.g)return E(this.multiply(E(a)));if(0>this.compare(Bc)&&0>a.compare(Bc))return F(Cc(this)*Cc(a));for(var b=this.h.length+a.h.length,c=[],d=0;d<2*b;d++)c[d]=0;for(d=0;d>>16,g=H(this,d)&65535,k=H(a,e)>>>16,r=H(a,e)&65535;c[2*d+2*e]+=g*r;Gc(c,2*d+2*e);c[2*d+2*e+1]+=f*r;Gc(c,2*d+2*e+1);c[2*d+2*e+1]+= g*k;Gc(c,2*d+2*e+1);c[2*d+2*e+2]+=f*k;Gc(c,2*d+2*e+2)}for(d=0;d>>16,a[b]&=65535,b++},Ec=function(a,b){if(G(b))throw Error("division by zero");if(G(a))return D;if(-1==a.g)return-1==b.g?Ec(E(a),E(b)):E(Ec(E(a),b));if(-1==b.g)return E(Ec(a,E(b)));if(30=b.compare(a);)c=c.shiftLeft(1),b=b.shiftLeft(1);var d=Hc(c,1),e=Hc(b,1),f;b=Hc(b,2);for(c=Hc(c,2);!G(b);)f=e.add(b),0>=f.compare(a)&&(d=d.add(c), e=f),b=Hc(b,1),c=Hc(c,1);return d}for(c=D;0<=a.compare(b);){d=Math.max(1,Math.floor(Cc(a)/Cc(b)));e=Math.ceil(Math.log(d)/Math.LN2);e=48>=e?1:Math.pow(2,e-48);f=F(d);for(var g=f.multiply(b);-1==g.g||0>5;a%=32;for(var c=this.h.length+b+(0>>32-a:H(this,e-b);return new C(d,this.g)};var Hc=function(a,b){var c=b>>5;b%=32;for(var d=a.h.length-c,e=[],f=0;f>>b|H(a,f+c+1)<<32-b:H(a,f+c);return new C(e,a.g)};var Jc=function(a,b){this.pb=a;this.na=b};Jc.prototype.Eb=function(a){return this.na==a.na&&this.pb.Eb(Wa(a.pb))};Jc.prototype.toString=ca; +C.prototype.shiftLeft=function(a){var b=a>>5;a%=32;for(var c=this.h.length+b+(0>>32-a:H(this,e-b);return new C(d,this.g)};var Hc=function(a,b){var c=b>>5;b%=32;for(var d=a.h.length-c,e=[],f=0;f>>b|H(a,f+c+1)<<32-b:H(a,f+c);return new C(e,a.g)};var Jc=function(a,b){this.qb=a;this.na=b};Jc.prototype.Gb=function(a){return this.na==a.na&&this.qb.Gb(Wa(a.qb))};Jc.prototype.toString=ca; var Mc=function(a){try{var b;if(b=0==a.lastIndexOf("[",0)){var c=a.length-1;b=0<=c&&a.indexOf("]",c)==c}return b?new Kc(a.substring(1,a.length-1)):new Lc(a)}catch(d){return null}},Lc=function(a){var b=D;if(a instanceof C){if(0!=a.g||0>a.compare(D)||0e||255>>=8;return this.Ca=b.join(".")}; -var Kc=function(a){var b=D;if(a instanceof C){if(0!=a.g||0>a.compare(D)||0>>16&65535).toString(16));d.push((a&65535).toString(16));Ka(c,c.length-1);Qa(c,d);a=c.join(":")}d=a.split("::");if(2e||255>>=8;return this.Da=b.join(".")}; +var Kc=function(a){var b=D;if(a instanceof C){if(0!=a.g||0>a.compare(D)||0>>16&65535).toString(16));d.push((a&65535).toString(16));Ka(c,c.length-1);Qa(c,d);a=c.join(":")}d=a.split("::");if(2e)c=[];else{for(var f=[],g=0;ge.compare(D)||0>>16).toString(16));a.push(d.toString(16))}for(var c=b=-1,e=d=0,f=0;fd&&(d=e,b=c)):(c=-1,e=0);0>>16).toString(16));a.push(d.toString(16))}for(var c=b=-1,e=d=0,f=0;fd&&(d=e,b=c)):(c=-1,e=0);0=b.oc&&b.cancel())}this.nd?this.nd.call(this.Zc,this):this.Nc=!0;this.Qa||Hd(this,new Id)}};Gd.prototype.Yc=function(a,b){this.nc=!1;Jd(this,a,b)}; -var Jd=function(a,b,c){a.Qa=!0;a.ka=c;a.nb=!b;Kd(a)},Md=function(a){if(a.Qa){if(!a.Nc)throw new Ld;a.Nc=!1}};Gd.prototype.callback=function(a){Md(this);Nd(a);Jd(this,!0,a)}; -var Hd=function(a,b){Md(a);Nd(b);Jd(a,!1,b)},Nd=function(a){w(!(a instanceof Gd),"An execution sequence may not be initiated with a blocking Deferred.")},Rd=function(a){var b=Od("https://apis.google.com/js/client.js?onload="+Pd);Qd(b,null,a,void 0)},Qd=function(a,b,c,d){w(!a.Sc,"Blocking Deferreds can not be re-used");a.bc.push([b,c,d]);a.Qa&&Kd(a)};Gd.prototype.then=function(a,b,c){var d,e,f=new I(function(a,b){d=a;e=b});Qd(this,d,function(a){a instanceof Id?f.cancel():e(a)});return f.then(a,b,c)}; +var Gd=function(a,b){this.dc=[];this.pd=a;this.ad=b||null;this.ob=this.Ra=!1;this.ka=void 0;this.Pc=this.Uc=this.qc=!1;this.kc=0;this.o=null;this.rc=0};Gd.prototype.cancel=function(a){if(this.Ra)this.ka instanceof Gd&&this.ka.cancel();else{if(this.o){var b=this.o;delete this.o;a?b.cancel(a):(b.rc--,0>=b.rc&&b.cancel())}this.pd?this.pd.call(this.ad,this):this.Pc=!0;this.Ra||Hd(this,new Id)}};Gd.prototype.$c=function(a,b){this.qc=!1;Jd(this,a,b)}; +var Jd=function(a,b,c){a.Ra=!0;a.ka=c;a.ob=!b;Kd(a)},Md=function(a){if(a.Ra){if(!a.Pc)throw new Ld;a.Pc=!1}};Gd.prototype.callback=function(a){Md(this);Nd(a);Jd(this,!0,a)}; +var Hd=function(a,b){Md(a);Nd(b);Jd(a,!1,b)},Nd=function(a){w(!(a instanceof Gd),"An execution sequence may not be initiated with a blocking Deferred.")},Rd=function(a){var b=Od("https://apis.google.com/js/client.js?onload="+Pd);Qd(b,null,a,void 0)},Qd=function(a,b,c,d){w(!a.Uc,"Blocking Deferreds can not be re-used");a.dc.push([b,c,d]);a.Ra&&Kd(a)};Gd.prototype.then=function(a,b,c){var d,e,f=new I(function(a,b){d=a;e=b});Qd(this,d,function(a){a instanceof Id?f.cancel():e(a)});return f.then(a,b,c)}; ld(Gd); -var Sd=function(a){return Ga(a.bc,function(a){return p(a[1])})},Kd=function(a){if(a.ic&&a.Qa&&Sd(a)){var b=a.ic,c=Td[b];c&&(l.clearTimeout(c.ob),delete Td[b]);a.ic=0}a.o&&(a.o.oc--,delete a.o);for(var b=a.ka,d=c=!1;a.bc.length&&!a.nc;){var e=a.bc.shift(),f=e[0],g=e[1],e=e[2];if(f=a.nb?g:f)try{var k=f.call(e||a.Zc,b);void 0!==k&&(a.nb=a.nb&&(k==b||k instanceof Error),a.ka=b=k);if(md(b)||"function"===typeof l.Promise&&b instanceof l.Promise)d=!0,a.nc=!0}catch(q){b=q,a.nb=!0,Sd(a)||(c=!0)}}a.ka=b;d&& -(k=r(a.Yc,a,!0),d=r(a.Yc,a,!1),b instanceof Gd?(Qd(b,k,d),b.Sc=!0):b.then(k,d));c&&(b=new Ud(b),Td[b.ob]=b,a.ic=b.ob)},Ld=function(){u.call(this)};t(Ld,u);Ld.prototype.message="Deferred has already fired";Ld.prototype.name="AlreadyCalledError";var Id=function(){u.call(this)};t(Id,u);Id.prototype.message="Deferred was canceled";Id.prototype.name="CanceledError";var Ud=function(a){this.ob=l.setTimeout(r(this.Ge,this),0);this.J=a}; -Ud.prototype.Ge=function(){w(Td[this.ob],"Cannot throw an error that is not scheduled.");delete Td[this.ob];throw this.J;};var Td={};var Od=function(a){var b=new Tc;b.Wb=a;return Vd(b)},Vd=function(a){var b={},c=b.document||document,d;a instanceof Tc&&a.constructor===Tc&&a.Nd===Sc?d=a.Wb:(za("expected object of type TrustedResourceUrl, got '"+a+"' of type "+m(a)),d="type_error:TrustedResourceUrl");var e=document.createElement("SCRIPT");a={vd:e,xb:void 0};var f=new Gd(Wd,a),g=null,k=null!=b.timeout?b.timeout:5E3;0++d,"infinite loop")}c=this.Qd;d=a.type||a;if(n(a))a=new zb(a,c);else if(a instanceof zb)a.target=a.target||c;else{var e=a;a=new zb(d,c);Ya(a,e)}var e=!0,f;if(b)for(var g=b.length-1;!a.Va&&0<=g;g--)f=a.currentTarget=b[g],e=be(f,d,!0,a)&&e;a.Va||(f=a.currentTarget=c,e=be(f,d,!0,a)&&e,a.Va||(e=be(f,d,!1,a)&&e));if(b)for(g=0;!a.Va&&g2*this.i&&fe(this),!0):!1}; +var Sd=function(a){return Ga(a.dc,function(a){return p(a[1])})},Kd=function(a){if(a.kc&&a.Ra&&Sd(a)){var b=a.kc,c=Td[b];c&&(l.clearTimeout(c.pb),delete Td[b]);a.kc=0}a.o&&(a.o.rc--,delete a.o);for(var b=a.ka,d=c=!1;a.dc.length&&!a.qc;){var e=a.dc.shift(),f=e[0],g=e[1],e=e[2];if(f=a.ob?g:f)try{var k=f.call(e||a.ad,b);void 0!==k&&(a.ob=a.ob&&(k==b||k instanceof Error),a.ka=b=k);if(md(b)||"function"===typeof l.Promise&&b instanceof l.Promise)d=!0,a.qc=!0}catch(r){b=r,a.ob=!0,Sd(a)||(c=!0)}}a.ka=b;d&& +(k=q(a.$c,a,!0),d=q(a.$c,a,!1),b instanceof Gd?(Qd(b,k,d),b.Uc=!0):b.then(k,d));c&&(b=new Ud(b),Td[b.pb]=b,a.kc=b.pb)},Ld=function(){u.call(this)};t(Ld,u);Ld.prototype.message="Deferred has already fired";Ld.prototype.name="AlreadyCalledError";var Id=function(){u.call(this)};t(Id,u);Id.prototype.message="Deferred was canceled";Id.prototype.name="CanceledError";var Ud=function(a){this.pb=l.setTimeout(q(this.Le,this),0);this.J=a}; +Ud.prototype.Le=function(){w(Td[this.pb],"Cannot throw an error that is not scheduled.");delete Td[this.pb];throw this.J;};var Td={};var Od=function(a){var b=new Tc;b.Yb=a;return Vd(b)},Vd=function(a){var b={},c=b.document||document,d;a instanceof Tc&&a.constructor===Tc&&a.Pd===Sc?d=a.Yb:(za("expected object of type TrustedResourceUrl, got '"+a+"' of type "+m(a)),d="type_error:TrustedResourceUrl");var e=document.createElement("SCRIPT");a={xd:e,zb:void 0};var f=new Gd(Wd,a),g=null,k=null!=b.timeout?b.timeout:5E3;0++d,"infinite loop")}c=this.Sd;d=a.type||a;if(n(a))a=new zb(a,c);else if(a instanceof zb)a.target=a.target||c;else{var e=a;a=new zb(d,c);Ya(a,e)}var e=!0,f;if(b)for(var g=b.length-1;!a.Wa&&0<=g;g--)f=a.currentTarget=b[g],e=be(f,d,!0,a)&&e;a.Wa||(f=a.currentTarget=c,e=be(f,d,!0,a)&&e,a.Wa||(e=be(f,d,!1,a)&&e));if(b)for(g=0;!a.Wa&&g2*this.i&&fe(this),!0):!1}; var fe=function(a){if(a.i!=a.s.length){for(var b=0,c=0;b=d.s.length)throw ce;var e=d.s[b++];return a?e:d.Z[e]};return e}; +h.addAll=function(a){var b;a instanceof ee?(b=a.ha(),a=a.T()):(b=Ta(a),a=Sa(a));for(var c=0;c=d.s.length)throw ce;var e=d.s[b++];return a?e:d.Z[e]};return e}; var ge=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var ie=function(a){if(a.T&&"function"==typeof a.T)return a.T();if(n(a))return a.split("");if(fa(a)){for(var b=[],c=a.length,d=0;d=se(this).value)for(p(b)&&(b=b()),a=new le(a,String(b),this.se),c&&(a.ad=c),c="log:"+a.re,l.console&&(l.console.timeStamp?l.console.timeStamp(c):l.console.markTimeline&&l.console.markTimeline(c)),l.msWriteProfilerMark&&l.msWriteProfilerMark(c),c=this;c;){b=c;var d=a;if(b.fd)for(var e=0,f;f=b.fd[e];e++)f(d);c=c.getParent()}}; -var te={},ue=null,ve=function(a){ue||(ue=new ne(""),te[""]=ue,ue.yd(qe));var b;if(!(b=te[a])){b=new ne(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=ve(a.substr(0,c));c.pc||(c.pc={});c.pc[d]=b;b.o=c;te[a]=b}return b};var L=function(a,b){a&&a.log(re,b,void 0)};var we=function(a,b,c){if(p(a))c&&(a=r(a,c));else if(a&&"function"==typeof a.handleEvent)a=r(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647b)throw Error("Bad port number "+b);a.Ua=b}else a.Ua=null},Se=function(a,b,c){N(a);a.ra=c?Ue(b,!0):b},Te=function(a,b,c){N(a);b instanceof O?(a.aa=b,a.aa.Mc(a.M)):(c||(b=Ve(b,$e)),a.aa=new O(b,0,a.M))},P=function(a,b,c){N(a);a.aa.set(b,c)},N=function(a){if(a.oe)throw Error("Tried to modify a read-only Uri");}; -Oe.prototype.Mc=function(a){this.M=a;this.aa&&this.aa.Mc(a);return this}; +d.length,f=0;f=se(this).value)for(p(b)&&(b=b()),a=new le(a,String(b),this.xe),c&&(a.cd=c),c="log:"+a.we,l.console&&(l.console.timeStamp?l.console.timeStamp(c):l.console.markTimeline&&l.console.markTimeline(c)),l.msWriteProfilerMark&&l.msWriteProfilerMark(c),c=this;c;){b=c;var d=a;if(b.hd)for(var e=0,f;f=b.hd[e];e++)f(d);c=c.getParent()}}; +var te={},ue=null,ve=function(a){ue||(ue=new ne(""),te[""]=ue,ue.Ad(qe));var b;if(!(b=te[a])){b=new ne(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=ve(a.substr(0,c));c.sc||(c.sc={});c.sc[d]=b;b.o=c;te[a]=b}return b};var L=function(a,b){a&&a.log(re,b,void 0)};var we=function(a,b,c){if(p(a))c&&(a=q(a,c));else if(a&&"function"==typeof a.handleEvent)a=q(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647b)throw Error("Bad port number "+b);a.Va=b}else a.Va=null},Se=function(a,b,c){N(a);a.ra=c?Ue(b,!0):b},Te=function(a,b,c){N(a);b instanceof O?(a.aa=b,a.aa.Oc(a.M)):(c||(b=Ve(b,$e)),a.aa=new O(b,0,a.M))},P=function(a,b,c){N(a);a.aa.set(b,c)},N=function(a){if(a.re)throw Error("Tried to modify a read-only Uri");}; +Oe.prototype.Oc=function(a){this.M=a;this.aa&&this.aa.Oc(a);return this}; var af=function(a){return a instanceof Oe?a.clone():new Oe(a,void 0)},bf=function(a,b){var c=new Oe(null,void 0);Pe(c,"https");a&&Qe(c,a);b&&Se(c,b);return c},Ue=function(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""},Ve=function(a,b,c){return n(a)?(a=encodeURI(a).replace(b,cf),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null},cf=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)},We=/[#\/\?@]/g,Ye=/[\#\?:]/g,Xe=/[\#\?]/g,$e=/[\#\?@]/g, -Ze=/#/g,O=function(a,b,c){this.i=this.j=null;this.I=a||null;this.M=!!c},df=function(a){a.j||(a.j=new ee,a.i=0,a.I&&ze(a.I,function(b,c){a.add(decodeURIComponent(b.replace(/\+/g," ")),c)}))},ff=function(a){var b=je(a);if("undefined"==typeof b)throw Error("Keys are undefined");var c=new O(null,0,void 0);a=ie(a);for(var d=0;da?!1:!z||!qb||9")&&(d=d.replace(qa,">")),-1!=d.indexOf('"')&&(d=d.replace(sa,""")),-1!=d.indexOf("'")&&(d=d.replace(ta,"'")),-1!=d.indexOf("\x00")&&(d=d.replace(ua,"�"))),d='',Ba(bc(a),"must provide justification"), -w(!/^[\s\xa0]*$/.test(bc(a)),"must provide non-empty justification"),g.document.write(Wc((new Vc).ne(d))),g.document.close())):g=a.open(dc(b),c,g);if(g)try{g.focus()}catch(k){}return g},pf=function(a){return new I(function(b){var c=function(){xe(2E3).then(function(){if(!a||a.closed)b();else return c()})};return c()})},qf=function(){var a=null;return(new I(function(b){"complete"==l.document.readyState?b():(a=function(){b()},Sb(window,"load",a))})).l(function(b){Ub(window,"load",a);throw b;})},rf=function(a){switch(a|| -l.navigator&&l.navigator.product||""){case "ReactNative":return"ReactNative";default:return"undefined"!==typeof l.process?"Node":"Browser"}},sf=function(){var a=rf();return"ReactNative"===a||"Node"===a},lf=function(a){var b=a.toLowerCase();if(v(b,"opera/")||v(b,"opr/")||v(b,"opios/"))return"Opera";if(v(b,"iemobile"))return"IEMobile";if(v(b,"msie")||v(b,"trident/"))return"IE";if(v(b,"edge/"))return"Edge";if(v(b,"firefox/"))return"Firefox";if(v(b,"silk/"))return"Silk";if(v(b,"blackberry"))return"Blackberry"; -if(v(b,"webos"))return"Webos";if(!v(b,"safari/")||v(b,"chrome/")||v(b,"crios/")||v(b,"android"))if(!v(b,"chrome/")&&!v(b,"crios/")||v(b,"edge/")){if(v(b,"android"))return"Android";if((a=a.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==a.length)return a[1]}else return"Chrome";else return"Safari";return"Other"},tf=function(a){var b=rf(void 0);return("Browser"===b?lf(gf()):b)+"/JsCore/"+a},gf=function(){return l.navigator&&l.navigator.userAgent||""},uf=function(a){a=a.split(".");for(var b=l,c=0;ca?!1:!z||!pb||9")&&(d=d.replace(qa,">")),-1!=d.indexOf('"')&&(d=d.replace(ra,""")),-1!=d.indexOf("'")&&(d=d.replace(ta,"'")),-1!=d.indexOf("\x00")&&(d=d.replace(ua,"�"))),d='',Ba(bc(a), +"must provide justification"),w(!/^[\s\xa0]*$/.test(bc(a)),"must provide non-empty justification"),g.document.write(Wc((new Vc).qe(d))),g.document.close())):g=a.open(dc(b),c,g);if(g)try{g.focus()}catch(k){}return g},pf=function(a){return new I(function(b){var c=function(){xe(2E3).then(function(){if(!a||a.closed)b();else return c()})};return c()})},qf=function(){var a=null;return(new I(function(b){"complete"==l.document.readyState?b():(a=function(){b()},Sb(window,"load",a))})).l(function(b){Ub(window, +"load",a);throw b;})},rf=function(a){switch(a||l.navigator&&l.navigator.product||""){case "ReactNative":return"ReactNative";default:return"undefined"!==typeof l.process?"Node":"Browser"}},sf=function(){var a=rf();return"ReactNative"===a||"Node"===a},lf=function(a){var b=a.toLowerCase();if(v(b,"opera/")||v(b,"opr/")||v(b,"opios/"))return"Opera";if(v(b,"iemobile"))return"IEMobile";if(v(b,"msie")||v(b,"trident/"))return"IE";if(v(b,"edge/"))return"Edge";if(v(b,"firefox/"))return"Firefox";if(v(b,"silk/"))return"Silk"; +if(v(b,"blackberry"))return"Blackberry";if(v(b,"webos"))return"Webos";if(!v(b,"safari/")||v(b,"chrome/")||v(b,"crios/")||v(b,"android"))if(!v(b,"chrome/")&&!v(b,"crios/")||v(b,"edge/")){if(v(b,"android"))return"Android";if((a=a.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==a.length)return a[1]}else return"Chrome";else return"Safari";return"Other"},tf=function(a){var b=rf(void 0);return("Browser"===b?lf(gf()):b)+"/JsCore/"+a},gf=function(){return l.navigator&&l.navigator.userAgent||""},uf=function(a){a= +a.split(".");for(var b=l,c=0;c Auth section -> Sign in method tab.",a);R.call(this,b,c)};t(Kf,R);var Lf=function(a){this.qe=a.sub;la();this.Db=a.email||null};var Mf=function(a,b,c,d){var e={};ha(c)?e=c:b&&n(c)&&n(d)?e={oauthToken:c,oauthTokenSecret:d}:!b&&n(c)&&(e={accessToken:c});if(b||!e.idToken&&!e.accessToken)if(b&&e.oauthToken&&e.oauthTokenSecret)Q(this,"accessToken",e.oauthToken),Q(this,"secret",e.oauthTokenSecret);else{if(b)throw new R("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");throw new R("argument-error","credential failed: expected 1 argument (the OAuth access token).");}else e.idToken&&Q(this, -"idToken",e.idToken),e.accessToken&&Q(this,"accessToken",e.accessToken);Q(this,"provider",a)};Mf.prototype.Gb=function(a){return Nf(a,Of(this))};Mf.prototype.md=function(a,b){var c=Of(this);c.idToken=b;return Pf(a,c)};var Of=function(a){var b={};a.idToken&&(b.id_token=a.idToken);a.accessToken&&(b.access_token=a.accessToken);a.secret&&(b.oauth_token_secret=a.secret);b.providerId=a.provider;return{postBody:ff(b).toString(),requestUri:wf()?jf():"http://localhost"}}; -Mf.prototype.G=function(){var a={provider:this.provider};this.idToken&&(a.oauthIdToken=this.idToken);this.accessToken&&(a.oauthAccessToken=this.accessToken);this.secret&&(a.oauthTokenSecret=this.secret);return a}; -var Qf=function(a,b){var c=!!b;b=function(){Df(this,{providerId:a,isOAuthProvider:!0});this.Lc=[];"google.com"==a&&this.addScope("profile")};c||(b.prototype.addScope=function(a){Ja(this.Lc,a)||this.Lc.push(a)});b.prototype.Hb=function(){return Pa(this.Lc)};b.credential=function(b,e){return new Mf(a,c,b,e)};Df(b,{PROVIDER_ID:a});return b},Rf=Qf("facebook.com");Rf.prototype.addScope=Rf.prototype.addScope||void 0;var Sf=Qf("github.com");Sf.prototype.addScope=Sf.prototype.addScope||void 0;var Tf=Qf("google.com"); -Tf.prototype.addScope=Tf.prototype.addScope||void 0;Tf.credential=function(a,b){if(!a&&!b)throw new R("argument-error","credential failed: must provide the ID token and/or the access token.");return new Mf("google.com",!1,ha(a)?a:{idToken:a||null,accessToken:b||null})};var Uf=Qf("twitter.com",!0),Vf=function(a,b){this.Db=a;this.Dc=b;Q(this,"provider","password")};Vf.prototype.Gb=function(a){return S(a,Wf,{email:this.Db,password:this.Dc})}; -Vf.prototype.md=function(a,b){return S(a,Xf,{idToken:b,email:this.Db,password:this.Dc})};Vf.prototype.G=function(){return{email:this.Db,password:this.Dc}};var Yf=function(){Df(this,{providerId:"password",isOAuthProvider:!1})};Df(Yf,{PROVIDER_ID:"password"}); -var Zf={Me:Yf,Hd:Rf,Jd:Tf,Id:Sf,Od:Uf},$f=function(a){var b=a&&a.providerId;if(!b)return null;var c=a&&a.oauthAccessToken,d=a&&a.oauthTokenSecret;a=a&&a.oauthIdToken;for(var e in Zf)if(Zf[e].PROVIDER_ID==b)try{return Zf[e].credential({accessToken:c,idToken:a,oauthToken:c,oauthTokenSecret:d})}catch(f){break}return null};var ag=function(a,b,c,d){R.call(this,a,d);Q(this,"email",b);Q(this,"credential",c)};t(ag,R);ag.prototype.G=function(){var a={code:this.code,message:this.message,email:this.email},b=this.credential&&this.credential.G();b&&(Ya(a,b),a.providerId=b.provider,delete a.provider);return a};var bg=function(a){if(a.code){var b=a.code||"";0==b.indexOf("auth/")&&(b=b.substring(5));return a.email?new ag(b,a.email,$f(a),a.message):new R(b,a.message||void 0)}return null};var cg=function(a){this.Le=a};t(cg,pc);cg.prototype.kb=function(){return new this.Le};cg.prototype.Qb=function(){return{}}; -var T=function(a,b,c){var d;d="Node"==rf();d=l.XMLHttpRequest||d&&firebase.INTERNAL.node&&firebase.INTERNAL.node.XMLHttpRequest;if(!d)throw new R("internal-error","The XMLHttpRequest compatibility library was not found.");this.v=a;a=b||{};this.Ae=a.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token";this.Be=a.secureTokenTimeout||1E4;this.wd=Wa(a.secureTokenHeaders||dg);this.$d=a.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/";this.ae=a.firebaseTimeout|| -1E4;this.cd=Wa(a.firebaseHeaders||eg);c&&(this.cd["X-Client-Version"]=c,this.wd["X-Client-Version"]=c);this.Sd=new uc;this.Ke=new cg(d)},fg,dg={"Content-Type":"application/x-www-form-urlencoded"},eg={"Content-Type":"application/json"},hg=function(a,b,c,d,e,f,g){mf()?a=r(a.De,a):(fg||(fg=new I(function(a,b){gg(a,b)})),a=r(a.Ce,a));a(b,c,d,e,f,g)}; -T.prototype.De=function(a,b,c,d,e,f){var g="Node"==rf(),k=sf()?g?new M(this.Ke):new M:new M(this.Sd),q;f&&(k.fb=Math.max(0,f),q=setTimeout(function(){k.dispatchEvent("timeout")},f));k.listen("complete",function(){q&&clearTimeout(q);var a=null;try{var c;c=this.a?ic(this.a.responseText):void 0;a=c||null}catch(Pi){try{a=JSON.parse(Ne(this))||null}catch(Qi){a=null}}b&&b(a)});Tb(k,"ready",function(){q&&clearTimeout(q);this.ya||(this.ya=!0,this.Oa())});Tb(k,"timeout",function(){q&&clearTimeout(q);this.ya|| -(this.ya=!0,this.Oa());b&&b(null)});k.send(a,c,d,e)};var Pd="__fcb"+Math.floor(1E6*Math.random()).toString(),gg=function(a,b){((window.gapi||{}).client||{}).request?a():(l[Pd]=function(){((window.gapi||{}).client||{}).request?a():b(Error("CORS_UNSUPPORTED"))},Rd(function(){b(Error("CORS_UNSUPPORTED"))}))}; -T.prototype.Ce=function(a,b,c,d,e){var f=this;fg.then(function(){window.gapi.client.setApiKey(f.v);var g=window.gapi.auth.getToken();window.gapi.auth.setToken(null);window.gapi.client.request({path:a,method:c,body:d,headers:e,authType:"none",callback:function(a){window.gapi.auth.setToken(g);b&&b(a)}})}).l(function(a){b&&b({error:{message:a&&a.message||"CORS_UNSUPPORTED"}})})}; -var jg=function(a,b){return new I(function(c,d){"refresh_token"==b.grant_type&&b.refresh_token||"authorization_code"==b.grant_type&&b.code?hg(a,a.Ae+"?key="+encodeURIComponent(a.v),function(a){a?a.error?d(ig(a)):a.access_token&&a.refresh_token?c(a):d(new R("internal-error")):d(new R("network-request-failed"))},"POST",ff(b).toString(),a.wd,a.Be):d(new R("internal-error"))})},kg=function(a){var b={},c;for(c in a)null!==a[c]&&void 0!==a[c]&&(b[c]=a[c]);return lc(b)},lg=function(a,b,c,d,e){var f=a.$d+ -b+"?key="+encodeURIComponent(a.v);e&&(f+="&cb="+la().toString());return new I(function(b,e){hg(a,f,function(a){a?a.error?e(ig(a)):b(a):e(new R("network-request-failed"))},c,kg(d),a.cd,a.ae)})},mg=function(a){if(!Zb.test(a.email))throw new R("invalid-email");},ng=function(a){"email"in a&&mg(a)},pg=function(a,b){var c=wf()?jf():"http://localhost";return S(a,og,{identifier:b,continueUri:c}).then(function(a){return a.allProviders||[]})},rg=function(a){return S(a,qg,{}).then(function(a){return a.authorizedDomains|| -[]})},sg=function(a){if(!a.idToken)throw new R("internal-error");};T.prototype.signInAnonymously=function(){return S(this,tg,{})};T.prototype.updateEmail=function(a,b){return S(this,ug,{idToken:a,email:b})};T.prototype.updatePassword=function(a,b){return S(this,Xf,{idToken:a,password:b})};var vg={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"}; -T.prototype.updateProfile=function(a,b){var c={idToken:a},d=[];Ra(vg,function(a,f){var e=b[f];null===e?d.push(a):f in b&&(c[f]=e)});d.length&&(c.deleteAttribute=d);return S(this,ug,c)};T.prototype.sendPasswordResetEmail=function(a){return S(this,wg,{requestType:"PASSWORD_RESET",email:a})};T.prototype.sendEmailVerification=function(a){return S(this,xg,{requestType:"VERIFY_EMAIL",idToken:a})}; -var zg=function(a,b,c){return S(a,yg,{idToken:b,deleteProvider:c})},Ag=function(a){if(!a.requestUri||!a.sessionId&&!a.postBody)throw new R("internal-error");},Bg=function(a){var b=null;a.needConfirmation?(a.code="account-exists-with-different-credential",b=bg(a)):"FEDERATED_USER_ID_ALREADY_LINKED"==a.errorMessage?(a.code="credential-already-in-use",b=bg(a)):"EMAIL_EXISTS"==a.errorMessage&&(a.code="email-already-in-use",b=bg(a));if(b)throw b;if(!a.idToken)throw new R("internal-error");},Nf=function(a, -b){b.returnIdpCredential=!0;return S(a,Cg,b)},Pf=function(a,b){b.returnIdpCredential=!0;return S(a,Dg,b)},Eg=function(a){if(!a.oobCode)throw new R("invalid-action-code");};T.prototype.confirmPasswordReset=function(a,b){return S(this,Fg,{oobCode:a,newPassword:b})};T.prototype.checkActionCode=function(a){return S(this,Gg,{oobCode:a})};T.prototype.applyActionCode=function(a){return S(this,Hg,{oobCode:a})}; -var Hg={endpoint:"setAccountInfo",D:Eg,cb:"email"},Gg={endpoint:"resetPassword",D:Eg,ta:function(a){if(!Zb.test(a.email))throw new R("internal-error");}},Ig={endpoint:"signupNewUser",D:function(a){mg(a);if(!a.password)throw new R("weak-password");},ta:sg,ua:!0},og={endpoint:"createAuthUri"},Jg={endpoint:"deleteAccount",ab:["idToken"]},yg={endpoint:"setAccountInfo",ab:["idToken","deleteProvider"],D:function(a){if(!ea(a.deleteProvider))throw new R("internal-error");}},Kg={endpoint:"getAccountInfo"}, -xg={endpoint:"getOobConfirmationCode",ab:["idToken","requestType"],D:function(a){if("VERIFY_EMAIL"!=a.requestType)throw new R("internal-error");},cb:"email"},wg={endpoint:"getOobConfirmationCode",ab:["requestType"],D:function(a){if("PASSWORD_RESET"!=a.requestType)throw new R("internal-error");mg(a)},cb:"email"},qg={Rd:!0,endpoint:"getProjectConfig",je:"GET"},Fg={endpoint:"resetPassword",D:Eg,cb:"email"},ug={endpoint:"setAccountInfo",ab:["idToken"],D:ng,ua:!0},Xf={endpoint:"setAccountInfo",ab:["idToken"], -D:function(a){ng(a);if(!a.password)throw new R("weak-password");},ta:sg,ua:!0},tg={endpoint:"signupNewUser",ta:sg,ua:!0},Cg={endpoint:"verifyAssertion",D:Ag,ta:Bg,ua:!0},Dg={endpoint:"verifyAssertion",D:function(a){Ag(a);if(!a.idToken)throw new R("internal-error");},ta:Bg,ua:!0},Lg={endpoint:"verifyCustomToken",D:function(a){if(!a.token)throw new R("invalid-custom-token");},ta:sg,ua:!0},Wf={endpoint:"verifyPassword",D:function(a){mg(a);if(!a.password)throw new R("wrong-password");},ta:sg,ua:!0},S= -function(a,b,c){if(!Ff(c,b.ab))return K(new R("internal-error"));var d=b.je||"POST",e;return J(c).then(b.D).then(function(){b.ua&&(c.returnSecureToken=!0);return lg(a,b.endpoint,d,c,b.Rd||!1)}).then(function(a){return e=a}).then(b.ta).then(function(){if(!b.cb)return e;if(!(b.cb in e))throw new R("internal-error");return e[b.cb]})},ig=function(a){var b,c;c=(a.error&&a.error.errors&&a.error.errors[0]||{}).reason||"";var d={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(c=d[c]? +"user-cancelled":"User did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported."};var Kf=function(a,b,c,d,e){this.wa=a;this.Aa=b||null;this.ib=c||null;this.ec=d||null;this.J=e||null;if(this.ib||this.J){if(this.ib&&this.J)throw new R("invalid-auth-event");if(this.ib&&!this.ec)throw new R("invalid-auth-event");}else throw new R("invalid-auth-event");};Kf.prototype.getError=function(){return this.J};Kf.prototype.G=function(){return{type:this.wa,eventId:this.Aa,urlResponse:this.ib,sessionId:this.ec,error:this.J&&this.J.G()}};var Lf=function(a){var b="unauthorized-domain",c=void 0,d=af(a);a=d.ga;d=d.la;"http"!=d&&"https"!=d?b="operation-not-supported-in-this-environment":c=ma("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",a);R.call(this,b,c)};t(Lf,R);var Mf=function(a){this.ve=a.sub;la();this.Fb=a.email||null};var Nf=function(a,b,c,d){var e={};ha(c)?e=c:b&&n(c)&&n(d)?e={oauthToken:c,oauthTokenSecret:d}:!b&&n(c)&&(e={accessToken:c});if(b||!e.idToken&&!e.accessToken)if(b&&e.oauthToken&&e.oauthTokenSecret)Q(this,"accessToken",e.oauthToken),Q(this,"secret",e.oauthTokenSecret);else{if(b)throw new R("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");throw new R("argument-error","credential failed: expected 1 argument (the OAuth access token).");}else e.idToken&&Q(this, +"idToken",e.idToken),e.accessToken&&Q(this,"accessToken",e.accessToken);Q(this,"provider",a)};Nf.prototype.Ib=function(a){return Of(a,Pf(this))};Nf.prototype.od=function(a,b){var c=Pf(this);c.idToken=b;return Qf(a,c)};var Pf=function(a){var b={};a.idToken&&(b.id_token=a.idToken);a.accessToken&&(b.access_token=a.accessToken);a.secret&&(b.oauth_token_secret=a.secret);b.providerId=a.provider;return{postBody:ff(b).toString(),requestUri:wf()?jf():"http://localhost"}}; +Nf.prototype.G=function(){var a={provider:this.provider};this.idToken&&(a.oauthIdToken=this.idToken);this.accessToken&&(a.oauthAccessToken=this.accessToken);this.secret&&(a.oauthTokenSecret=this.secret);return a}; +var Rf=function(a,b){var c=!!b;b=function(){Ef(this,{providerId:a,isOAuthProvider:!0});this.Nc=[];"google.com"==a&&this.addScope("profile")};c||(b.prototype.addScope=function(a){Ja(this.Nc,a)||this.Nc.push(a)});b.prototype.Jb=function(){return Pa(this.Nc)};b.credential=function(b,e){return new Nf(a,c,b,e)};Ef(b,{PROVIDER_ID:a});return b},Sf=Rf("facebook.com");Sf.prototype.addScope=Sf.prototype.addScope||void 0;var Tf=Rf("github.com");Tf.prototype.addScope=Tf.prototype.addScope||void 0;var Uf=Rf("google.com"); +Uf.prototype.addScope=Uf.prototype.addScope||void 0;Uf.credential=function(a,b){if(!a&&!b)throw new R("argument-error","credential failed: must provide the ID token and/or the access token.");return new Nf("google.com",!1,ha(a)?a:{idToken:a||null,accessToken:b||null})};var Vf=Rf("twitter.com",!0),Wf=function(a,b){this.Fb=a;this.Gc=b;Q(this,"provider","password")};Wf.prototype.Ib=function(a){return S(a,Xf,{email:this.Fb,password:this.Gc})}; +Wf.prototype.od=function(a,b){return S(a,Yf,{idToken:b,email:this.Fb,password:this.Gc})};Wf.prototype.G=function(){return{email:this.Fb,password:this.Gc}};var Zf=function(){Ef(this,{providerId:"password",isOAuthProvider:!1})};Ef(Zf,{PROVIDER_ID:"password"}); +var $f={Ve:Zf,Jd:Sf,Ld:Uf,Kd:Tf,Qd:Vf},ag=function(a){var b=a&&a.providerId;if(!b)return null;var c=a&&a.oauthAccessToken,d=a&&a.oauthTokenSecret;a=a&&a.oauthIdToken;for(var e in $f)if($f[e].PROVIDER_ID==b)try{return $f[e].credential({accessToken:c,idToken:a,oauthToken:c,oauthTokenSecret:d})}catch(f){break}return null};var bg=function(a,b,c,d){R.call(this,a,d);Q(this,"email",b);Q(this,"credential",c)};t(bg,R);bg.prototype.G=function(){var a={code:this.code,message:this.message,email:this.email},b=this.credential&&this.credential.G();b&&(Ya(a,b),a.providerId=b.provider,delete a.provider);return a};var cg=function(a){if(a.code){var b=a.code||"";0==b.indexOf("auth/")&&(b=b.substring(5));return a.email?new bg(b,a.email,ag(a),a.message):new R(b,a.message||void 0)}return null};var dg=function(a){this.Ue=a};t(dg,pc);dg.prototype.lb=function(){return new this.Ue};dg.prototype.Sb=function(){return{}}; +var T=function(a,b,c){var d;d="Node"==rf();d=l.XMLHttpRequest||d&&firebase.INTERNAL.node&&firebase.INTERNAL.node.XMLHttpRequest;if(!d)throw new R("internal-error","The XMLHttpRequest compatibility library was not found.");this.v=a;a=b||{};this.Fe=a.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token";this.Ge=a.secureTokenTimeout||1E4;this.yd=Wa(a.secureTokenHeaders||eg);this.ce=a.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/";this.de=a.firebaseTimeout|| +1E4;this.ed=Wa(a.firebaseHeaders||fg);c&&(this.ed["X-Client-Version"]=c,this.yd["X-Client-Version"]=c);this.Ud=new uc;this.Te=new dg(d)},gg,eg={"Content-Type":"application/x-www-form-urlencoded"},fg={"Content-Type":"application/json"},ig=function(a,b,c,d,e,f,g){mf()?a=q(a.Ie,a):(gg||(gg=new I(function(a,b){hg(a,b)})),a=q(a.He,a));a(b,c,d,e,f,g)}; +T.prototype.Ie=function(a,b,c,d,e,f){var g="Node"==rf(),k=sf()?g?new M(this.Te):new M:new M(this.Ud),r;f&&(k.gb=Math.max(0,f),r=setTimeout(function(){k.dispatchEvent("timeout")},f));k.listen("complete",function(){r&&clearTimeout(r);var a=null;try{var c;c=this.a?ic(this.a.responseText):void 0;a=c||null}catch(Ri){try{a=JSON.parse(Ne(this))||null}catch(Si){a=null}}b&&b(a)});Tb(k,"ready",function(){r&&clearTimeout(r);this.za||(this.za=!0,this.Pa())});Tb(k,"timeout",function(){r&&clearTimeout(r);this.za|| +(this.za=!0,this.Pa());b&&b(null)});k.send(a,c,d,e)};var Pd="__fcb"+Math.floor(1E6*Math.random()).toString(),hg=function(a,b){((window.gapi||{}).client||{}).request?a():(l[Pd]=function(){((window.gapi||{}).client||{}).request?a():b(Error("CORS_UNSUPPORTED"))},Rd(function(){b(Error("CORS_UNSUPPORTED"))}))}; +T.prototype.He=function(a,b,c,d,e){var f=this;gg.then(function(){window.gapi.client.setApiKey(f.v);var g=window.gapi.auth.getToken();window.gapi.auth.setToken(null);window.gapi.client.request({path:a,method:c,body:d,headers:e,authType:"none",callback:function(a){window.gapi.auth.setToken(g);b&&b(a)}})}).l(function(a){b&&b({error:{message:a&&a.message||"CORS_UNSUPPORTED"}})})}; +var kg=function(a,b){return new I(function(c,d){"refresh_token"==b.grant_type&&b.refresh_token||"authorization_code"==b.grant_type&&b.code?ig(a,a.Fe+"?key="+encodeURIComponent(a.v),function(a){a?a.error?d(jg(a)):a.access_token&&a.refresh_token?c(a):d(new R("internal-error")):d(new R("network-request-failed"))},"POST",ff(b).toString(),a.yd,a.Ge):d(new R("internal-error"))})},lg=function(a){var b={},c;for(c in a)null!==a[c]&&void 0!==a[c]&&(b[c]=a[c]);return lc(b)},mg=function(a,b,c,d,e){var f=a.ce+ +b+"?key="+encodeURIComponent(a.v);e&&(f+="&cb="+la().toString());return new I(function(b,e){ig(a,f,function(a){a?a.error?e(jg(a)):b(a):e(new R("network-request-failed"))},c,lg(d),a.ed,a.de)})},ng=function(a){if(!Zb.test(a.email))throw new R("invalid-email");},og=function(a){"email"in a&&ng(a)},qg=function(a,b){var c=wf()?jf():"http://localhost";return S(a,pg,{identifier:b,continueUri:c}).then(function(a){return a.allProviders||[]})},sg=function(a){return S(a,rg,{}).then(function(a){return a.authorizedDomains|| +[]})},tg=function(a){if(!a.idToken)throw new R("internal-error");};T.prototype.signInAnonymously=function(){return S(this,ug,{})};T.prototype.updateEmail=function(a,b){return S(this,vg,{idToken:a,email:b})};T.prototype.updatePassword=function(a,b){return S(this,Yf,{idToken:a,password:b})};var wg={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"}; +T.prototype.updateProfile=function(a,b){var c={idToken:a},d=[];Ra(wg,function(a,f){var e=b[f];null===e?d.push(a):f in b&&(c[f]=e)});d.length&&(c.deleteAttribute=d);return S(this,vg,c)};T.prototype.sendPasswordResetEmail=function(a){return S(this,xg,{requestType:"PASSWORD_RESET",email:a})};T.prototype.sendEmailVerification=function(a){return S(this,yg,{requestType:"VERIFY_EMAIL",idToken:a})}; +var Ag=function(a,b,c){return S(a,zg,{idToken:b,deleteProvider:c})},Bg=function(a){if(!a.requestUri||!a.sessionId&&!a.postBody)throw new R("internal-error");},Cg=function(a){var b=null;a.needConfirmation?(a.code="account-exists-with-different-credential",b=cg(a)):"FEDERATED_USER_ID_ALREADY_LINKED"==a.errorMessage?(a.code="credential-already-in-use",b=cg(a)):"EMAIL_EXISTS"==a.errorMessage&&(a.code="email-already-in-use",b=cg(a));if(b)throw b;if(!a.idToken)throw new R("internal-error");},Of=function(a, +b){b.returnIdpCredential=!0;return S(a,Dg,b)},Qf=function(a,b){b.returnIdpCredential=!0;return S(a,Eg,b)},Fg=function(a){if(!a.oobCode)throw new R("invalid-action-code");};T.prototype.confirmPasswordReset=function(a,b){return S(this,Gg,{oobCode:a,newPassword:b})};T.prototype.checkActionCode=function(a){return S(this,Hg,{oobCode:a})};T.prototype.applyActionCode=function(a){return S(this,Ig,{oobCode:a})}; +var Ig={endpoint:"setAccountInfo",D:Fg,eb:"email"},Hg={endpoint:"resetPassword",D:Fg,ua:function(a){if(!Zb.test(a.email))throw new R("internal-error");}},Jg={endpoint:"signupNewUser",D:function(a){ng(a);if(!a.password)throw new R("weak-password");},ua:tg,va:!0},pg={endpoint:"createAuthUri"},Kg={endpoint:"deleteAccount",bb:["idToken"]},zg={endpoint:"setAccountInfo",bb:["idToken","deleteProvider"],D:function(a){if(!ea(a.deleteProvider))throw new R("internal-error");}},Lg={endpoint:"getAccountInfo"}, +yg={endpoint:"getOobConfirmationCode",bb:["idToken","requestType"],D:function(a){if("VERIFY_EMAIL"!=a.requestType)throw new R("internal-error");},eb:"email"},xg={endpoint:"getOobConfirmationCode",bb:["requestType"],D:function(a){if("PASSWORD_RESET"!=a.requestType)throw new R("internal-error");ng(a)},eb:"email"},rg={Td:!0,endpoint:"getProjectConfig",me:"GET"},Gg={endpoint:"resetPassword",D:Fg,eb:"email"},vg={endpoint:"setAccountInfo",bb:["idToken"],D:og,va:!0},Yf={endpoint:"setAccountInfo",bb:["idToken"], +D:function(a){og(a);if(!a.password)throw new R("weak-password");},ua:tg,va:!0},ug={endpoint:"signupNewUser",ua:tg,va:!0},Dg={endpoint:"verifyAssertion",D:Bg,ua:Cg,va:!0},Eg={endpoint:"verifyAssertion",D:function(a){Bg(a);if(!a.idToken)throw new R("internal-error");},ua:Cg,va:!0},Mg={endpoint:"verifyCustomToken",D:function(a){if(!a.token)throw new R("invalid-custom-token");},ua:tg,va:!0},Xf={endpoint:"verifyPassword",D:function(a){ng(a);if(!a.password)throw new R("wrong-password");},ua:tg,va:!0},S= +function(a,b,c){if(!Gf(c,b.bb))return K(new R("internal-error"));var d=b.me||"POST",e;return J(c).then(b.D).then(function(){b.va&&(c.returnSecureToken=!0);return mg(a,b.endpoint,d,c,b.Td||!1)}).then(function(a){return e=a}).then(b.ua).then(function(){if(!b.eb)return e;if(!(b.eb in e))throw new R("internal-error");return e[b.eb]})},jg=function(a){var b,c;c=(a.error&&a.error.errors&&a.error.errors[0]||{}).reason||"";var d={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(c=d[c]? new R(d[c]):null)return c;c=a.error&&a.error.message||"";d={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential", FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",EMAIL_NOT_FOUND:"user-not-found",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password",OPERATION_NOT_ALLOWED:"operation-not-allowed", -USER_CANCELLED:"user-cancelled"};b=(b=c.match(/^[^\s]+\s*:\s*(.*)$/))&&1k||k>=qh.length)throw new R("internal-error","Argument validator received an unsupported number of arguments.");e=qh[k]+" argument "+(e.name?'"'+e.name+'" ':"")+"must be "+e.ca+".";break a}e=null}}if(e)throw new R("argument-error",d+" failed: "+e);return b.apply(this,a)};for(var e in b)a[e]=b[e];for(e in b.prototype)a.prototype[e]= -b.prototype[e];return a},zh=function(a){a=a.split(".");return a[a.length-1]};var Ah=function(a,b,c,d){this.te=a;this.xd=b;this.ze=c;this.eb=d;this.N={};ph||(ph=new oh);a=ph;try{var e;hf()?(fh||(fh=new eh("firebaseLocalStorageDb","firebaseLocalStorage","fbase_key","value",1)),e=fh):e=new a.$c.V;this.Ta=e}catch(f){this.Ta=new Zg,this.eb=!0}try{this.gc=new a.$c.Qc}catch(f){this.gc=new Zg}this.Ad=r(this.Bd,this);this.O={}},Bh,Ch=function(){Bh||(Bh=new Ah("firebase",":","Safari"==lf(gf())&&l.window&&l.window!=l.window.top?!0:!1,xf()));return Bh};h=Ah.prototype; -h.K=function(a,b){return this.te+this.xd+a.name+(b?this.xd+b:"")};h.get=function(a,b){return(a.V?this.Ta:this.gc).get(this.K(a,b))};h.remove=function(a,b){b=this.K(a,b);a.V&&!this.eb&&(this.O[b]=null);return(a.V?this.Ta:this.gc).remove(b)};h.set=function(a,b,c){var d=this.K(a,c),e=this,f=a.V?this.Ta:this.gc;return f.set(d,b).then(function(){return f.get(d)}).then(function(b){a.V&&!this.eb&&(e.O[d]=b)})}; -h.addListener=function(a,b,c){a=this.K(a,b);this.eb||(this.O[a]=l.localStorage.getItem(a));Ua(this.N)&&this.Oc();this.N[a]||(this.N[a]=[]);this.N[a].push(c)};h.removeListener=function(a,b,c){a=this.K(a,b);this.N[a]&&(Ma(this.N[a],function(a){return a==c}),0==this.N[a].length&&delete this.N[a]);Ua(this.N)&&this.ec()};h.Oc=function(){this.Ta.Ka(this.Ad);this.eb||Dh(this)}; -var Dh=function(a){Eh(a);a.zc=setInterval(function(){for(var b in a.N){var c=l.localStorage.getItem(b);c!=a.O[b]&&(a.O[b]=c,c=new Ab({type:"storage",key:b,target:window,oldValue:a.O[b],newValue:c}),a.Bd(c))}},1E3)},Eh=function(a){a.zc&&(clearInterval(a.zc),a.zc=null)};Ah.prototype.ec=function(){this.Ta.Za(this.Ad);this.eb||Eh(this)}; -Ah.prototype.Bd=function(a){if(a&&a.ce){var b=a.lb.key;if(this.ze){var c=l.localStorage.getItem(b);a=a.lb.newValue;a!=c&&(a?l.localStorage.setItem(b,a):a||l.localStorage.removeItem(b))}this.O[b]=l.localStorage.getItem(b);this.Vc(b)}else x(a,r(this.Vc,this))};Ah.prototype.Vc=function(a){this.N[a]&&x(this.N[a],function(a){a()})};var Fh=function(a){this.B=a;this.A=Ch()},Gh={name:"pendingRedirect",V:!1},Hh=function(a){return a.A.set(Gh,"pending",a.B)},Ih=function(a){return a.A.remove(Gh,a.B)},Jh=function(a){return a.A.get(Gh,a.B).then(function(a){return"pending"==a})};var Mh=function(a,b,c){var d=this,e=(this.xa=firebase.SDK_VERSION||null)?tf(this.xa):null;this.f=new T(b,null,e);this.qa=null;this.X=a;this.v=b;this.ea=c;this.wb=[];this.Pb=!1;this.Rc=r(this.de,this);this.Wa=new Kh(this);this.rd=new Lh(this);this.Ec=new Fh(this.v+":"+this.ea);this.gb={};this.gb.unknown=this.Wa;this.gb.signInViaRedirect=this.Wa;this.gb.linkViaRedirect=this.Wa;this.gb.signInViaPopup=this.rd;this.gb.linkViaPopup=this.rd;this.$b=this.bb=null;this.Ub=new I(function(a,b){d.bb=a;d.$b=b})}; -Mh.prototype.reset=function(){var a=this;this.qa=null;this.Ub.cancel();this.Pb=!1;this.$b=this.bb=null;this.Mb&&Xg(this.Mb,this.Rc);this.Ub=new I(function(b,c){a.bb=b;a.$b=c})}; -var Nh=function(a){var b=jf();return rg(a).then(function(a){a:{for(var c=af(b).ga,e=0;ethis.Pa-3E4?this.S?ai(this,{grant_type:"refresh_token",refresh_token:this.S}):J(null):J({accessToken:this.wa,expirationTime:this.Pa,refreshToken:this.S})};var ci=function(a,b,c,d,e){Df(this,{uid:a,displayName:d||null,photoURL:e||null,email:c||null,providerId:b})},di=function(a,b){zb.call(this,a);for(var c in b)this[c]=b[c]};t(di,zb); -var W=function(a,b,c){this.U=[];this.v=a.apiKey;this.ea=a.appName;this.X=a.authDomain||null;a=firebase.SDK_VERSION?tf(firebase.SDK_VERSION):null;this.f=new T(this.v,null,a);this.ba=new Yh(this.f);ei(this,b.idToken);$h(this.ba,b);Q(this,"refreshToken",this.ba.S);fi(this,c||{});$d.call(this);this.Vb=!1;this.X&&wf()&&(this.m=Vh(this.X,this.v,this.ea));this.dc=[]};t(W,$d); -var ei=function(a,b){a.kd=b;Q(a,"_lat",b)},gi=function(a,b){Ma(a.dc,function(a){return a==b})},hi=function(a){for(var b=[],c=0;ck||k>=rh.length)throw new R("internal-error","Argument validator received an unsupported number of arguments.");e=rh[k]+" argument "+(e.name?'"'+e.name+'" ':"")+"must be "+e.ca+".";break a}e=null}}if(e)throw new R("argument-error",d+" failed: "+e);return b.apply(this,a)};for(var e in b)a[e]=b[e];for(e in b.prototype)a.prototype[e]= +b.prototype[e];return a},Ah=function(a){a=a.split(".");return a[a.length-1]};var Bh=function(a,b,c,d){this.ye=a;this.zd=b;this.Ee=c;this.fb=d;this.N={};qh||(qh=new ph);a=qh;try{var e;hf()?(gh||(gh=new fh("firebaseLocalStorageDb","firebaseLocalStorage","fbase_key","value",1)),e=gh):e=new a.bd.V;this.Ua=e}catch(f){this.Ua=new $g,this.fb=!0}try{this.ic=new a.bd.Sc}catch(f){this.ic=new $g}this.Cd=q(this.Dd,this);this.O={}},Ch,Dh=function(){Ch||(Ch=new Bh("firebase",":",!Af(gf())&&l.window&&l.window!=l.window.top?!0:!1,xf()));return Ch};h=Bh.prototype; +h.K=function(a,b){return this.ye+this.zd+a.name+(b?this.zd+b:"")};h.get=function(a,b){return(a.V?this.Ua:this.ic).get(this.K(a,b))};h.remove=function(a,b){b=this.K(a,b);a.V&&!this.fb&&(this.O[b]=null);return(a.V?this.Ua:this.ic).remove(b)};h.set=function(a,b,c){var d=this.K(a,c),e=this,f=a.V?this.Ua:this.ic;return f.set(d,b).then(function(){return f.get(d)}).then(function(b){a.V&&!this.fb&&(e.O[d]=b)})}; +h.addListener=function(a,b,c){a=this.K(a,b);this.fb||(this.O[a]=l.localStorage.getItem(a));Ua(this.N)&&this.Qc();this.N[a]||(this.N[a]=[]);this.N[a].push(c)};h.removeListener=function(a,b,c){a=this.K(a,b);this.N[a]&&(Ma(this.N[a],function(a){return a==c}),0==this.N[a].length&&delete this.N[a]);Ua(this.N)&&this.gc()};h.Qc=function(){this.Ua.La(this.Cd);this.fb||Eh(this)}; +var Eh=function(a){Fh(a);a.Cc=setInterval(function(){for(var b in a.N){var c=l.localStorage.getItem(b);c!=a.O[b]&&(a.O[b]=c,c=new Ab({type:"storage",key:b,target:window,oldValue:a.O[b],newValue:c}),a.Dd(c))}},1E3)},Fh=function(a){a.Cc&&(clearInterval(a.Cc),a.Cc=null)};Bh.prototype.gc=function(){this.Ua.$a(this.Cd);this.fb||Fh(this)}; +Bh.prototype.Dd=function(a){if(a&&a.fe){var b=a.mb.key;if(this.Ee){var c=l.localStorage.getItem(b);a=a.mb.newValue;a!=c&&(a?l.localStorage.setItem(b,a):a||l.localStorage.removeItem(b))}this.O[b]=l.localStorage.getItem(b);this.Xc(b)}else x(a,q(this.Xc,this))};Bh.prototype.Xc=function(a){this.N[a]&&x(this.N[a],function(a){a()})};var Gh=function(a){this.B=a;this.A=Dh()},Hh={name:"pendingRedirect",V:!1},Ih=function(a){return a.A.set(Hh,"pending",a.B)},Jh=function(a){return a.A.remove(Hh,a.B)},Kh=function(a){return a.A.get(Hh,a.B).then(function(a){return"pending"==a})};var Nh=function(a,b,c){var d=this,e=(this.ya=firebase.SDK_VERSION||null)?tf(this.ya):null;this.f=new T(b,null,e);this.qa=null;this.X=a;this.v=b;this.ea=c;this.yb=[];this.Rb=!1;this.Tc=q(this.ge,this);this.Xa=new Lh(this);this.td=new Mh(this);this.Hc=new Gh(this.v+":"+this.ea);this.hb={};this.hb.unknown=this.Xa;this.hb.signInViaRedirect=this.Xa;this.hb.linkViaRedirect=this.Xa;this.hb.signInViaPopup=this.td;this.hb.linkViaPopup=this.td;this.bc=this.cb=null;this.Wb=new I(function(a,b){d.cb=a;d.bc=b})}; +Nh.prototype.reset=function(){var a=this;this.qa=null;this.Wb.cancel();this.Rb=!1;this.bc=this.cb=null;this.Ob&&Yg(this.Ob,this.Tc);this.Wb=new I(function(b,c){a.cb=b;a.bc=c})}; +var Oh=function(a){var b=jf();return sg(a).then(function(a){a:{for(var c=af(b).ga,e=0;ethis.Qa-3E4?this.S?bi(this,{grant_type:"refresh_token",refresh_token:this.S}):J(null):J({accessToken:this.xa,expirationTime:this.Qa,refreshToken:this.S})};var di=function(a,b,c,d,e){Ef(this,{uid:a,displayName:d||null,photoURL:e||null,email:c||null,providerId:b})},ei=function(a,b){zb.call(this,a);for(var c in b)this[c]=b[c]};t(ei,zb); +var W=function(a,b,c){this.U=[];this.v=a.apiKey;this.ea=a.appName;this.X=a.authDomain||null;a=firebase.SDK_VERSION?tf(firebase.SDK_VERSION):null;this.f=new T(this.v,null,a);this.ba=new Zh(this.f);fi(this,b.idToken);ai(this.ba,b);Q(this,"refreshToken",this.ba.S);gi(this,c||{});$d.call(this);this.Xb=!1;this.X&&wf()&&(this.m=Wh(this.X,this.v,this.ea));this.fc=[];this.pc=J()};t(W,$d); +W.prototype.sa=function(a,b){var c=Array.prototype.slice.call(arguments,1),d=this;return this.pc=this.pc.then(function(){return a.apply(d,c)},function(){return a.apply(d,c)})}; +var fi=function(a,b){a.md=b;Q(a,"_lat",b)},hi=function(a,b){Ma(a.fc,function(a){return a==b})},ii=function(a){for(var b=[],c=0;cb?e+="000":256>b?e+="00":4096>b&&(e+="0");return Aa[a]=e+b.toString(16)}),'"')};var v;a:{var Ca=n.navigator;if(Ca){var Da=Ca.userAgent;if(Da){v=Da;break a}}v=""};function Ea(a){if(Error.captureStackTrace)Error.captureStackTrace(this,Ea);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))}ka(Ea,Error);Ea.prototype.name="CustomError";var w=Array.prototype,Fa=w.indexOf?function(a,b,c){return w.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(q(a))return q(b)&&1==b.length?a.indexOf(b,c):-1;for(;cc?null:q(a)?a.charAt(c):a[c]}function Ma(a,b,c){for(var d=a.length,e=q(a)?a.split(""):a,f=0;f=arguments.length?w.slice.call(a,b):w.slice.call(a,b,c)} -function Pa(a,b){a.sort(b||Qa)}function Qa(a,b){return a>b?1:aparseFloat(a))?String(b):a})();function Va(a){n.setTimeout(function(){throw a;},0)}var Wa; -function Xa(){var a=n.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&-1==v.indexOf("Presto")&&(a=function(){var a=document.createElement("iframe");a.style.display="none";a.src="";document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=r(function(a){if(("*"==d||a.origin== -d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&-1==v.indexOf("Trident")&&-1==v.indexOf("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(p(c.next)){c=c.next;var a=c.Le;c.Le=null;a()}};return function(a){d.next={Le:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof document&&"onreadystatechange"in document.createElement("script")?function(a){var b= -document.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};document.documentElement.appendChild(b)}:function(a){n.setTimeout(a,0)}};function Ya(a,b){Za||$a();ab||(Za(),ab=!0);bb.push(new cb(a,b))}var Za;function $a(){if(n.Promise&&n.Promise.resolve){var a=n.Promise.resolve();Za=function(){a.then(db)}}else Za=function(){var a=db;!ga(n.setImmediate)||n.Window&&n.Window.prototype&&n.Window.prototype.setImmediate==n.setImmediate?(Wa||(Wa=Xa()),Wa(a)):n.setImmediate(a)}}var ab=!1,bb=[];[].push(function(){ab=!1;bb=[]}); -function db(){for(;bb.length;){var a=bb;bb=[];for(var b=0;b>2,f=(f&3)<<4|k>>4,k=(k&15)<<2|l>>6,l=l&63;m||(l=64,h||(k=64));d.push(c[u],c[f],c[k],c[l])}return d.join("")} -function xb(){if(!tb){tb={};ub={};vb={};for(var a=0;65>a;a++)tb[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a),ub[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a),vb[ub[a]]=a,62<=a&&(vb["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a)]=a)}};function yb(){this.Ya=-1};function zb(){this.Ya=-1;this.Ya=64;this.N=[];this.Wd=[];this.Jf=[];this.zd=[];this.zd[0]=128;for(var a=1;ae;e++)d[e]=b.charCodeAt(c)<<24|b.charCodeAt(c+1)<<16|b.charCodeAt(c+2)<<8|b.charCodeAt(c+3),c+=4;else for(e=0;16>e;e++)d[e]=b[c]<<24|b[c+1]<<16|b[c+2]<<8|b[c+3],c+=4;for(e=16;80>e;e++){var f=d[e-3]^d[e-8]^d[e-14]^d[e-16];d[e]=(f<<1|f>>>31)&4294967295}b=a.N[0];c=a.N[1];for(var h=a.N[2],k=a.N[3],m=a.N[4],l,e=0;80>e;e++)40>e?20>e?(f=k^c&(h^k),l=1518500249):(f=c^h^k,l=1859775393):60>e?(f=c&h|k&(c|h),l=2400959708):(f=c^h^k,l=3395469782),f=(b<< +function ka(a,b){function c(){}c.prototype=b.prototype;a.Ig=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.Eg=function(a,c,f){for(var h=Array(arguments.length-2),k=2;ke;e++)d[e]=b.charCodeAt(c)<<24|b.charCodeAt(c+1)<<16|b.charCodeAt(c+2)<<8|b.charCodeAt(c+3),c+=4;else for(e=0;16>e;e++)d[e]=b[c]<<24|b[c+1]<<16|b[c+2]<<8|b[c+3],c+=4;for(e=16;80>e;e++){var f=d[e-3]^d[e-8]^d[e-14]^d[e-16];d[e]=(f<<1|f>>>31)&4294967295}b=a.N[0];c=a.N[1];for(var h=a.N[2],k=a.N[3],m=a.N[4],l,e=0;80>e;e++)40>e?20>e?(f=k^c&(h^k),l=1518500249):(f=c^h^k,l=1859775393):60>e?(f=c&h|k&(c|h),l=2400959708):(f=c^h^k,l=3395469782),f=(b<< 5|b>>>27)+f+m+l+d[e]&4294967295,m=k,k=h,h=(c<<30|c>>>2)&4294967295,c=b,b=f;a.N[0]=a.N[0]+b&4294967295;a.N[1]=a.N[1]+c&4294967295;a.N[2]=a.N[2]+h&4294967295;a.N[3]=a.N[3]+k&4294967295;a.N[4]=a.N[4]+m&4294967295} -zb.prototype.update=function(a,b){if(null!=a){p(b)||(b=a.length);for(var c=b-this.Ya,d=0,e=this.Wd,f=this.ac;dc&&(e=0===c?"none":"no more than "+c);if(e)throw Error(a+" failed: Was called with "+d+(1===d?" argument.":" arguments.")+" Expects "+e+".");}function Bb(a,b,c){var d="";switch(b){case 1:d=c?"first":"First";break;case 2:d=c?"second":"Second";break;case 3:d=c?"third":"Third";break;case 4:d=c?"fourth":"Fourth";break;default:throw Error("errorPrefix called with argumentNumber > 4. Need to update it?");}return a=a+" failed: "+(d+" argument ")} -function y(a,b,c,d){if((!d||p(c))&&!ga(c))throw Error(Bb(a,b,d)+"must be a valid function.");}function Cb(a,b,c){if(p(c)&&(!ha(c)||null===c))throw Error(Bb(a,b,!0)+"must be a valid context object.");};var Db=n.Promise||eb;eb.prototype["catch"]=eb.prototype.Ag;function Eb(){var a=this;this.reject=this.resolve=null;this.sa=new Db(function(b,c){a.resolve=b;a.reject=c})}function Fb(a,b){return function(c,d){c?a.reject(c):a.resolve(d);ga(b)&&(Gb(a.sa),1===b.length?b(c):b(c,d))}}function Gb(a){a.then(void 0,aa)};function Hb(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function A(a,b){if(Object.prototype.hasOwnProperty.call(a,b))return a[b]}function Ib(a,b){for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b(c,a[c])};function Jb(a){var b=[];Ib(a,function(a,d){da(d)?Ga(d,function(d){b.push(encodeURIComponent(a)+"="+encodeURIComponent(d))}):b.push(encodeURIComponent(a)+"="+encodeURIComponent(d))});return b.length?"&"+b.join("&"):""};function Kb(a){return"undefined"!==typeof JSON&&p(JSON.parse)?JSON.parse(a):wa(a)}function B(a){if("undefined"!==typeof JSON&&p(JSON.stringify))a=JSON.stringify(a);else{var b=[];ya(new xa,a,b);a=b.join("")}return a};function Lb(a,b){if(!a)throw Mb(b);}function Mb(a){return Error("Firebase Database ("+firebase.SDK_VERSION+") INTERNAL ASSERT FAILED: "+a)};function Nb(a){for(var b=[],c=0,d=0;d=e&&(e-=55296,d++,Lb(de?b[c++]=e:(2048>e?b[c++]=e>>6|192:(65536>e?b[c++]=e>>12|224:(b[c++]=e>>18|240,b[c++]=e>>12&63|128),b[c++]=e>>6&63|128),b[c++]=e&63|128)}return b}function Ob(a){for(var b=0,c=0;cd?b++:2048>d?b+=2:55296<=d&&56319>=d?(b+=4,c++):b+=3}return b};function Pb(){return"undefined"!==typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!==typeof navigator&&"string"===typeof navigator.userAgent?navigator.userAgent:"")};function Qb(a){this.te=a;this.Bd=[];this.Rb=0;this.Yd=-1;this.Gb=null}function Rb(a,b,c){a.Yd=b;a.Gb=c;a.Yd");return a};function fc(){this.Jd=F}fc.prototype.j=function(a){return this.Jd.Q(a)};fc.prototype.toString=function(){return this.Jd.toString()};function H(a,b,c,d){this.type=a;this.Ma=b;this.Za=c;this.qe=d;this.Dd=void 0}function gc(a){return new H(hc,a)}var hc="value";function ic(a,b,c,d){this.ae=b;this.Md=c;this.Dd=d;this.gd=a}ic.prototype.Zb=function(){var a=this.Md.xb();return"value"===this.gd?a.path:a.getParent().path};ic.prototype.ge=function(){return this.gd};ic.prototype.Ub=function(){return this.ae.Ub(this)};ic.prototype.toString=function(){return this.Zb().toString()+":"+this.gd+":"+B(this.Md.Ue())};function jc(a,b,c){this.ae=a;this.error=b;this.path=c}jc.prototype.Zb=function(){return this.path};jc.prototype.ge=function(){return"cancel"}; -jc.prototype.Ub=function(){return this.ae.Ub(this)};jc.prototype.toString=function(){return this.path.toString()+":cancel"};function kc(){}kc.prototype.Xe=function(){return null};kc.prototype.fe=function(){return null};var lc=new kc;function mc(a,b,c){this.Gf=a;this.Na=b;this.yd=c}mc.prototype.Xe=function(a){var b=this.Na.O;if(nc(b,a))return b.j().R(a);b=null!=this.yd?new oc(this.yd,!0,!1):this.Na.w();return this.Gf.rc(a,b)};mc.prototype.fe=function(a,b,c){var d=null!=this.yd?this.yd:pc(this.Na);a=this.Gf.Xd(d,b,1,c,a);return 0===a.length?null:a[0]};function qc(){this.wb=[]}function rc(a,b){for(var c=null,d=0;db?c=c.left:0c?d=d.left:0e)a=this.le?a.left:a.right;else if(0===e){this.Sa.push(a);break}else this.Sa.push(a),a=this.le?a.right:a.left} -function K(a){if(0===a.Sa.length)return null;var b=a.Sa.pop(),c;c=a.Hd?a.Hd(b.key,b.value):{key:b.key,value:b.value};if(a.le)for(b=b.left;!b.e();)a.Sa.push(b),b=b.right;else for(b=b.right;!b.e();)a.Sa.push(b),b=b.left;return c}function Ec(a){if(0===a.Sa.length)return null;var b;b=a.Sa;b=b[b.length-1];return a.Hd?a.Hd(b.key,b.value):{key:b.key,value:b.value}}function Fc(a,b,c,d,e){this.key=a;this.value=b;this.color=null!=c?c:!0;this.left=null!=d?d:Bc;this.right=null!=e?e:Bc}g=Fc.prototype; -g.Y=function(a,b,c,d,e){return new Fc(null!=a?a:this.key,null!=b?b:this.value,null!=c?c:this.color,null!=d?d:this.left,null!=e?e:this.right)};g.count=function(){return this.left.count()+1+this.right.count()};g.e=function(){return!1};g.ia=function(a){return this.left.ia(a)||a(this.key,this.value)||this.right.ia(a)};function Gc(a){return a.left.e()?a:Gc(a.left)}g.Hc=function(){return Gc(this).key};g.fc=function(){return this.right.e()?this.key:this.right.fc()}; -g.Ra=function(a,b,c){var d,e;e=this;d=c(a,e.key);e=0>d?e.Y(null,null,null,e.left.Ra(a,b,c),null):0===d?e.Y(null,b,null,null,null):e.Y(null,null,null,null,e.right.Ra(a,b,c));return Hc(e)};function Ic(a){if(a.left.e())return Bc;a.left.fa()||a.left.left.fa()||(a=Jc(a));a=a.Y(null,null,null,Ic(a.left),null);return Hc(a)} -g.remove=function(a,b){var c,d;c=this;if(0>b(a,c.key))c.left.e()||c.left.fa()||c.left.left.fa()||(c=Jc(c)),c=c.Y(null,null,null,c.left.remove(a,b),null);else{c.left.fa()&&(c=Kc(c));c.right.e()||c.right.fa()||c.right.left.fa()||(c=Lc(c),c.left.left.fa()&&(c=Kc(c),c=Lc(c)));if(0===b(a,c.key)){if(c.right.e())return Bc;d=Gc(c.right);c=c.Y(d.key,d.value,null,null,Ic(c.right))}c=c.Y(null,null,null,null,c.right.remove(a,b))}return Hc(c)};g.fa=function(){return this.color}; -function Hc(a){a.right.fa()&&!a.left.fa()&&(a=Mc(a));a.left.fa()&&a.left.left.fa()&&(a=Kc(a));a.left.fa()&&a.right.fa()&&(a=Lc(a));return a}function Jc(a){a=Lc(a);a.right.left.fa()&&(a=a.Y(null,null,null,null,Kc(a.right)),a=Mc(a),a=Lc(a));return a}function Mc(a){return a.right.Y(null,null,a.color,a.Y(null,null,!0,null,a.right.left),null)}function Kc(a){return a.left.Y(null,null,a.color,null,a.Y(null,null,!0,a.left.right,null))} -function Lc(a){return a.Y(null,null,!a.color,a.left.Y(null,null,!a.left.color,null,null),a.right.Y(null,null,!a.right.color,null,null))}function Nc(){}g=Nc.prototype;g.Y=function(){return this};g.Ra=function(a,b){return new Fc(a,b,null)};g.remove=function(){return this};g.count=function(){return 0};g.e=function(){return!0};g.ia=function(){return!1};g.Hc=function(){return null};g.fc=function(){return null};g.fa=function(){return!1};var Bc=new Nc;var Oc=function(){var a=1;return function(){return a++}}(),E=Lb,Pc=Mb; -function Qc(a){try{var b;xb();for(var c=vb,d=[],e=0;e>4);64!=k&&(d.push(h<<4&240|k>>2),64!=m&&d.push(k<<6&192|m))}if(8192>d.length)b=String.fromCharCode.apply(null,d);else{a="";for(c=0;ca.ac?a.update(a.zd,56-a.ac):a.update(a.zd,a.Ya-(a.ac-56));for(var d=a.Ya-1;56<=d;d--)a.Wd[d]=c&255,c/=256;Ab(a,a.Wd);for(d=c=0;5>d;d++)for(var e=24;0<=e;e-=8)b[c]=a.N[d]>>e&255,++c;return wb(b)}function Sc(a){for(var b="",c=0;c.firebaseio.com instead"); -c&&"undefined"!=c||Xc("Cannot parse Firebase url. Please use https://.firebaseio.com");d||"undefined"!==typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&L("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");return{kc:new cc(b,d,c,"ws"===e||"wss"===e),path:new M(f)}}function Zc(a){return fa(a)&&(a!=a||a==Number.POSITIVE_INFINITY||a==Number.NEGATIVE_INFINITY)} -function $c(a){if("complete"===document.readyState)a();else{var b=!1,c=function(){document.body?b||(b=!0,a()):setTimeout(c,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",c,!1),window.addEventListener("load",c,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&c()}),window.attachEvent("onload",c))}} -function ad(a,b){if(a===b)return 0;if("[MIN_NAME]"===a||"[MAX_NAME]"===b)return-1;if("[MIN_NAME]"===b||"[MAX_NAME]"===a)return 1;var c=bd(a),d=bd(b);return null!==c?null!==d?0==c-d?a.length-b.length:c-d:-1:null!==d?1:aa?c.push(a.substring(d,a.length)):c.push(a.substring(d,d+b));return c}function fd(a,b){if(da(a))for(var c=0;ca,a=Math.abs(a),a>=Math.pow(2,-1022)?(d=Math.min(Math.floor(Math.log(a)/Math.LN2),1023),c=d+1023,d=Math.round(a*Math.pow(2,52-d)-Math.pow(2,52))):(c=0,d=Math.round(a/Math.pow(2,-1074))));e=[];for(a=52;a;--a)e.push(d%2?1:0),d=Math.floor(d/2);for(a=11;a;--a)e.push(c%2?1:0),c=Math.floor(c/2);e.push(b?1:0);e.reverse();b=e.join("");c="";for(a=0;64>a;a+=8)d=parseInt(b.substr(a,8),2).toString(16),1===d.length&& -(d="0"+d),c+=d;return c.toLowerCase()}var hd=/^-?\d{1,10}$/;function bd(a){return hd.test(a)&&(a=Number(a),-2147483648<=a&&2147483647>=a)?a:null}function Tb(a){try{a()}catch(b){setTimeout(function(){L("Exception was thrown by user callback.",b.stack||"");throw b;},Math.floor(0))}}function id(a,b,c){Object.defineProperty(a,b,{get:c})};function jd(a){var b={},c={},d={},e="";try{var f=a.split("."),b=Kb(Qc(f[0])||""),c=Kb(Qc(f[1])||""),e=f[2],d=c.d||{};delete c.d}catch(h){}return{Fg:b,Me:c,data:d,xg:e}}function kd(a){a=jd(a);var b=a.Me;return!!a.xg&&!!b&&"object"===typeof b&&b.hasOwnProperty("iat")}function ld(a){a=jd(a).Me;return"object"===typeof a&&!0===A(a,"admin")};function md(a,b,c){this.type=nd;this.source=a;this.path=b;this.children=c}md.prototype.Nc=function(a){if(this.path.e())return a=this.children.subtree(new M(a)),a.e()?null:a.value?new ac(this.source,C,a.value):new md(this.source,C,a);E(J(this.path)===a,"Can't get a merge for a child not on the path of the operation");return new md(this.source,D(this.path),this.children)};md.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"};function od(a){this.g=a}g=od.prototype;g.F=function(a,b,c,d,e,f){E(a.zc(this.g),"A node must be indexed if only a child is updated");e=a.R(b);if(e.Q(d).$(c.Q(d))&&e.e()==c.e())return a;null!=f&&(c.e()?a.Fa(b)?pd(f,new H("child_removed",e,b)):E(a.J(),"A child remove without an old child only makes sense on a leaf node"):e.e()?pd(f,new H("child_added",c,b)):pd(f,new H("child_changed",c,b,e)));return a.J()&&c.e()?a:a.U(b,c).ob(this.g)}; -g.za=function(a,b,c){null!=c&&(a.J()||a.P(N,function(a,e){b.Fa(a)||pd(c,new H("child_removed",e,a))}),b.J()||b.P(N,function(b,e){if(a.Fa(b)){var f=a.R(b);f.$(e)||pd(c,new H("child_changed",e,b,f))}else pd(c,new H("child_added",e,b))}));return b.ob(this.g)};g.ga=function(a,b){return a.e()?F:a.ga(b)};g.Qa=function(){return!1};g.Vb=function(){return this};function qd(a){this.he=new od(a.g);this.g=a.g;var b;a.la?(b=rd(a),b=a.g.Fc(sd(a),b)):b=a.g.Ic();this.Uc=b;a.oa?(b=td(a),a=a.g.Fc(ud(a),b)):a=a.g.Gc();this.wc=a}g=qd.prototype;g.matches=function(a){return 0>=this.g.compare(this.Uc,a)&&0>=this.g.compare(a,this.wc)};g.F=function(a,b,c,d,e,f){this.matches(new O(b,c))||(c=F);return this.he.F(a,b,c,d,e,f)}; -g.za=function(a,b,c){b.J()&&(b=F);var d=b.ob(this.g),d=d.ga(F),e=this;b.P(N,function(a,b){e.matches(new O(a,b))||(d=d.U(a,F))});return this.he.za(a,d,c)};g.ga=function(a){return a};g.Qa=function(){return!0};g.Vb=function(){return this.he};function vd(){this.hb={}} -function pd(a,b){var c=b.type,d=b.Za;E("child_added"==c||"child_changed"==c||"child_removed"==c,"Only child changes supported for tracking");E(".priority"!==d,"Only non-priority child changes can be tracked.");var e=A(a.hb,d);if(e){var f=e.type;if("child_added"==c&&"child_removed"==f)a.hb[d]=new H("child_changed",b.Ma,d,e.Ma);else if("child_removed"==c&&"child_added"==f)delete a.hb[d];else if("child_removed"==c&&"child_changed"==f)a.hb[d]=new H("child_removed",e.qe,d);else if("child_changed"==c&& -"child_added"==f)a.hb[d]=new H("child_added",b.Ma,d);else if("child_changed"==c&&"child_changed"==f)a.hb[d]=new H("child_changed",b.Ma,d,e.qe);else throw Pc("Illegal combination of changes: "+b+" occurred after "+e);}else a.hb[d]=b};function wd(a,b){this.Sd=a;this.Mf=b}function xd(a){this.V=a} -xd.prototype.gb=function(a,b,c,d){var e=new vd,f;if(b.type===bc)b.source.ee?c=yd(this,a,b.path,b.Ja,c,d,e):(E(b.source.We,"Unknown source."),f=b.source.Ee||yc(a.w())&&!b.path.e(),c=zd(this,a,b.path,b.Ja,c,d,f,e));else if(b.type===nd)b.source.ee?c=Ad(this,a,b.path,b.children,c,d,e):(E(b.source.We,"Unknown source."),f=b.source.Ee||yc(a.w()),c=Bd(this,a,b.path,b.children,c,d,f,e));else if(b.type===Dd)if(b.Id)if(b=b.path,null!=c.mc(b))c=a;else{f=new mc(c,a,d);d=a.O.j();if(b.e()||".priority"===J(b))xc(a.w())? -b=c.Ba(pc(a)):(b=a.w().j(),E(b instanceof P,"serverChildren would be complete if leaf node"),b=c.sc(b)),b=this.V.za(d,b,e);else{var h=J(b),k=c.rc(h,a.w());null==k&&nc(a.w(),h)&&(k=d.R(h));b=null!=k?this.V.F(d,h,k,D(b),f,e):a.O.j().Fa(h)?this.V.F(d,h,F,D(b),f,e):d;b.e()&&xc(a.w())&&(d=c.Ba(pc(a)),d.J()&&(b=this.V.za(b,d,e)))}d=xc(a.w())||null!=c.mc(C);c=Ed(a,b,d,this.V.Qa())}else c=Fd(this,a,b.path,b.Pb,c,d,e);else if(b.type===$b)d=b.path,b=a.w(),f=b.j(),h=b.ea||d.e(),c=Gd(this,new Hd(a.O,new oc(f, -h,b.Tb)),d,c,lc,e);else throw Pc("Unknown operation type: "+b.type);e=pa(e.hb);d=c;b=d.O;b.ea&&(f=b.j().J()||b.j().e(),h=Id(a),(0f;f++)b[f]=Math.floor(64*Math.random());for(f=0;12>f;f++)c+="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".charAt(b[f]);E(20===c.length,"nextPushId: Length should be 20."); -return c}}();function M(a,b){if(1==arguments.length){this.o=a.split("/");for(var c=0,d=0;d=a.o.length?null:a.o[a.Z]}function Jd(a){return a.o.length-a.Z}function D(a){var b=a.Z;b=this.o.length)return null;for(var a=[],b=this.Z;b=this.o.length};g.$=function(a){if(Jd(this)!==Jd(a))return!1;for(var b=this.Z,c=a.Z;b<=this.o.length;b++,c++)if(this.o[b]!==a.o[c])return!1;return!0}; -g.contains=function(a){var b=this.Z,c=a.Z;if(Jd(this)>Jd(a))return!1;for(;b10485760/3&&10485760=this.g.compare(this.ta.Uc,f):0>=this.g.compare(f,this.ta.wc))d=d.U(f.name,f.S),e++;else break}}else{d=b.ob(this.g);d=d.ga(F);var k,m,l;if(this.Jb){b=d.$e(this.g);k=this.ta.wc;m=this.ta.Uc;var u=Ue(this.g);l=function(a,b){return u(b,a)}}else b=d.Xb(this.g),k=this.ta.Uc, -m=this.ta.wc,l=Ue(this.g);for(var e=0,z=!1;0=l(k,f)&&(z=!0),(h=z&&e=l(f,m))?e++:d=d.U(f.name,F)}return this.ta.Vb().za(a,d,c)};g.ga=function(a){return a};g.Qa=function(){return!0};g.Vb=function(){return this.ta.Vb()}; -function nf(a,b,c,d,e,f){var h;if(a.Jb){var k=Ue(a.g);h=function(a,b){return k(b,a)}}else h=Ue(a.g);E(b.Fb()==a.pa,"");var m=new O(c,d),l=a.Jb?of(b,a.g):pf(b,a.g),u=a.ta.matches(m);if(b.Fa(c)){for(var z=b.R(c),l=e.fe(a.g,l,a.Jb);null!=l&&(l.name==c||b.Fa(l.name));)l=e.fe(a.g,l,a.Jb);e=null==l?1:h(l,m);if(u&&!d.e()&&0<=e)return null!=f&&pd(f,new H("child_changed",d,c,z)),b.U(c,d);null!=f&&pd(f,new H("child_removed",z,c));b=b.U(c,F);return null!=l&&a.ta.matches(l)?(null!=f&&pd(f,new H("child_added", -l.S,l.name)),b.U(l.name,l.S)):b}return d.e()?b:u&&0<=h(l,m)?(null!=f&&(pd(f,new H("child_removed",l.S,l.name)),pd(f,new H("child_added",d,c))),b.U(c,d).U(l.name,F)):b};function qf(a){this.W=a;this.g=a.n.g}function rf(a,b,c,d){var e=[],f=[];Ga(b,function(b){"child_changed"===b.type&&a.g.nd(b.qe,b.Ma)&&f.push(new H("child_moved",b.Ma,b.Za))});sf(a,e,"child_removed",b,d,c);sf(a,e,"child_added",b,d,c);sf(a,e,"child_moved",f,d,c);sf(a,e,"child_changed",b,d,c);sf(a,e,hc,b,d,c);return e}function sf(a,b,c,d,e,f){d=Ha(d,function(a){return a.type===c});Pa(d,r(a.Of,a));Ga(d,function(c){var d=tf(a,c,f);Ga(e,function(e){e.tf(c.type)&&b.push(e.createEvent(d,a.W))})})} -function tf(a,b,c){"value"!==b.type&&"child_removed"!==b.type&&(b.Dd=c.Ze(b.Za,b.Ma,a.g));return b}qf.prototype.Of=function(a,b){if(null==a.Za||null==b.Za)throw Pc("Should only compare child_ events.");return this.g.compare(new O(a.Za,a.Ma),new O(b.Za,b.Ma))};function uf(){this.Sb=this.oa=this.Lb=this.la=this.ya=!1;this.pa=0;this.oc="";this.ec=null;this.Ab="";this.bc=null;this.yb="";this.g=N}var vf=new uf;function mf(a){return""===a.oc?a.la:"l"===a.oc}function sd(a){E(a.la,"Only valid if start has been set");return a.ec}function rd(a){E(a.la,"Only valid if start has been set");return a.Lb?a.Ab:"[MIN_NAME]"}function ud(a){E(a.oa,"Only valid if end has been set");return a.bc} -function td(a){E(a.oa,"Only valid if end has been set");return a.Sb?a.yb:"[MAX_NAME]"}function wf(a){var b=new uf;b.ya=a.ya;b.pa=a.pa;b.la=a.la;b.ec=a.ec;b.Lb=a.Lb;b.Ab=a.Ab;b.oa=a.oa;b.bc=a.bc;b.Sb=a.Sb;b.yb=a.yb;b.g=a.g;return b}g=uf.prototype;g.ne=function(a){var b=wf(this);b.ya=!0;b.pa=a;b.oc="l";return b};g.oe=function(a){var b=wf(this);b.ya=!0;b.pa=a;b.oc="r";return b};g.Nd=function(a,b){var c=wf(this);c.la=!0;p(a)||(a=null);c.ec=a;null!=b?(c.Lb=!0,c.Ab=b):(c.Lb=!1,c.Ab="");return c}; -g.fd=function(a,b){var c=wf(this);c.oa=!0;p(a)||(a=null);c.bc=a;p(b)?(c.Sb=!0,c.yb=b):(c.Hg=!1,c.yb="");return c};function xf(a,b){var c=wf(a);c.g=b;return c}function yf(a){var b={};a.la&&(b.sp=a.ec,a.Lb&&(b.sn=a.Ab));a.oa&&(b.ep=a.bc,a.Sb&&(b.en=a.yb));if(a.ya){b.l=a.pa;var c=a.oc;""===c&&(c=mf(a)?"l":"r");b.vf=c}a.g!==N&&(b.i=a.g.toString());return b}function T(a){return!(a.la||a.oa||a.ya)}function zf(a){return T(a)&&a.g==N} -function Af(a){var b={};if(zf(a))return b;var c;a.g===N?c="$priority":a.g===bf?c="$value":a.g===Od?c="$key":(E(a.g instanceof We,"Unrecognized index type!"),c=a.g.toString());b.orderBy=B(c);a.la&&(b.startAt=B(a.ec),a.Lb&&(b.startAt+=","+B(a.Ab)));a.oa&&(b.endAt=B(a.bc),a.Sb&&(b.endAt+=","+B(a.yb)));a.ya&&(mf(a)?b.limitToFirst=a.pa:b.limitToLast=a.pa);return b}g.toString=function(){return B(yf(this))};function Qe(a,b){this.B=a;E(p(this.B)&&null!==this.B,"LeafNode shouldn't be created with null/undefined value.");this.ba=b||F;Bf(this.ba);this.Eb=null}var Cf=["object","boolean","number","string"];g=Qe.prototype;g.J=function(){return!0};g.C=function(){return this.ba};g.ga=function(a){return new Qe(this.B,a)};g.R=function(a){return".priority"===a?this.ba:F};g.Q=function(a){return a.e()?this:".priority"===J(a)?this.ba:F};g.Fa=function(){return!1};g.Ze=function(){return null}; -g.U=function(a,b){return".priority"===a?this.ga(b):b.e()&&".priority"!==a?this:F.U(a,b).ga(this.ba)};g.F=function(a,b){var c=J(a);if(null===c)return b;if(b.e()&&".priority"!==c)return this;E(".priority"!==c||1===Jd(a),".priority must be the last token in a path");return this.U(c,F.F(D(a),b))};g.e=function(){return!1};g.Fb=function(){return 0};g.P=function(){return!1};g.H=function(a){return a&&!this.C().e()?{".value":this.Ea(),".priority":this.C().H()}:this.Ea()}; -g.hash=function(){if(null===this.Eb){var a="";this.ba.e()||(a+="priority:"+Df(this.ba.H())+":");var b=typeof this.B,a=a+(b+":"),a="number"===b?a+gd(this.B):a+this.B;this.Eb=Rc(a)}return this.Eb};g.Ea=function(){return this.B};g.tc=function(a){if(a===F)return 1;if(a instanceof P)return-1;E(a.J(),"Unknown node type");var b=typeof a.B,c=typeof this.B,d=Fa(Cf,b),e=Fa(Cf,c);E(0<=d,"Unknown leaf type: "+b);E(0<=e,"Unknown leaf type: "+c);return d===e?"object"===c?0:this.Bb.compare(d,a);)K(c),d=Ec(c);return c};g.$e=function(a){return this.$b(a.Gc(),a)};g.$b=function(a,b){var c=Ff(this,b);if(c)return c.$b(a,function(a){return a});for(var c=this.k.$b(a.name,gf),d=Ec(c);null!=d&&0h.status){try{b=Kb(h.responseText)}catch(c){L("Failed to parse JSON response for "+f+": "+h.responseText)}d(null, -b)}else 401!==h.status&&404!==h.status&&L("Got unsuccessful REST response for "+f+" Status: "+h.status),d(h.status);d=null}};h.open("GET",f,!0);h.send()})};function Rf(a){this.He=a}Rf.prototype.getToken=function(a){return this.He.INTERNAL.getToken(a).then(null,function(a){return a&&"auth/token-not-initialized"===a.code?(I("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(a)})};function Sf(a,b){a.He.INTERNAL.addAuthTokenListener(b)};function Tf(a){this.Nf=a;this.rd=null}Tf.prototype.get=function(){var a=this.Nf.get(),b=va(a);if(this.rd)for(var c in this.rd)b[c]-=this.rd[c];this.rd=a;return b};function Uf(){this.uc={}}function Vf(a,b,c){p(c)||(c=1);Hb(a.uc,b)||(a.uc[b]=0);a.uc[b]+=c}Uf.prototype.get=function(){return va(this.uc)};function Wf(a,b){this.zf={};this.Vc=new Tf(a);this.wa=b;var c=1E4+2E4*Math.random();setTimeout(r(this.rf,this),Math.floor(c))}Wf.prototype.rf=function(){var a=this.Vc.get(),b={},c=!1,d;for(d in a)0=a.length){var b=Number(a);if(!isNaN(b)){e.Fe=b;e.frames=[];a=null;break a}}e.Fe=1;e.frames=[]}null!==a&&eg(e,a)}};this.La.onerror=function(a){e.f("WebSocket error. Closing connection.");(a=a.message||a.data)&&e.f(a);e.fb()}};bg.prototype.start=function(){}; -bg.isAvailable=function(){var a=!1;if("undefined"!==typeof navigator&&navigator.userAgent){var b=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);b&&1parseFloat(b[1])&&(a=!0)}return!a&&null!==ag&&!cg};bg.responsesRequiredToBeHealthy=2;bg.healthyTimeout=3E4;g=bg.prototype;g.sd=function(){Xb.remove("previous_websocket_failure")};function eg(a,b){a.frames.push(b);if(a.frames.length==a.Fe){var c=a.frames.join("");a.frames=null;c=Kb(c);a.hg(c)}} -g.send=function(a){dg(this);a=B(a);this.rb+=a.length;Vf(this.Xa,"bytes_sent",a.length);a=ed(a,16384);1document.domain="'+document.domain+'";\x3c/script>');a=""+a+"";try{this.Ga.ib.open(),this.Ga.ib.write(a),this.Ga.ib.close()}catch(f){I("frame writing exception"),f.stack&&I(f.stack),I(f)}} -jg.prototype.close=function(){this.Ud=!1;if(this.Ga){this.Ga.ib.body.innerHTML="";var a=this;setTimeout(function(){null!==a.Ga&&(document.body.removeChild(a.Ga),a.Ga=null)},Math.floor(0))}var b=this.kb;b&&(this.kb=null,b())}; -function mg(a){if(a.Ud&&a.Kd&&a.ve.count()<(0=a.Qc[0].Se.length+30+c.length){var e=a.Qc.shift(),c=c+"&seg"+d+"="+e.ug+"&ts"+d+"="+e.Bg+"&d"+d+"="+e.Se;d++}else break;ng(a,b+c,a.$d);return!0}return!1}function ng(a,b,c){function d(){a.ve.remove(c);mg(a)}a.ve.add(c,1);var e=setTimeout(d,Math.floor(25E3));lg(a,b,function(){clearTimeout(e);d()})} -function lg(a,b,c){setTimeout(function(){try{if(a.Kd){var d=a.Ga.ib.createElement("script");d.type="text/javascript";d.async=!0;d.src=b;d.onload=d.onreadystatechange=function(){var a=d.readyState;a&&"loaded"!==a&&"complete"!==a||(d.onload=d.onreadystatechange=null,d.parentNode&&d.parentNode.removeChild(d),c())};d.onerror=function(){I("Long-poll script failed to load: "+b);a.Kd=!1;a.close()};a.Ga.ib.body.appendChild(d)}}catch(e){}},Math.floor(1))};function og(a){pg(this,a)}var qg=[gg,bg];function pg(a,b){var c=bg&&bg.isAvailable(),d=c&&!(Xb.cf||!0===Xb.get("previous_websocket_failure"));b.Cg&&(c||L("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),d=!0);if(d)a.Wc=[bg];else{var e=a.Wc=[];fd(qg,function(a,b){b&&b.isAvailable()&&e.push(b)})}}function rg(a){if(0=a.xf?(a.f("Secondary connection is healthy."),a.Cb=!0,a.D.sd(),a.D.start(),a.f("sending client ack on secondary"),a.D.send({t:"c",d:{t:"a",d:{}}}),a.f("Ending transmission on primary"),a.I.send({t:"c",d:{t:"n",d:{}}}),a.Xc=a.D,yg(a)):(a.f("sending ping on secondary."),a.D.send({t:"c",d:{t:"p",d:{}}}))}sg.prototype.wd=function(a){Ag(this);this.te(a)};function Ag(a){a.Cb||(a.xe--,0>=a.xe&&(a.f("Primary connection is healthy."),a.Cb=!0,a.I.sd()))} -function xg(a,b){a.D=new b("c:"+a.id+":"+a.Oe++,a.M,a.yf);a.xf=b.responsesRequiredToBeHealthy||0;a.D.open(ug(a,a.D),vg(a,a.D));setTimeout(function(){a.D&&(a.f("Timed out trying to upgrade."),a.D.close())},Math.floor(6E4))}function wg(a,b,c){a.f("Realtime connection established.");a.I=b;a.L=1;a.Mc&&(a.Mc(c,a.yf),a.Mc=null);0===a.xe?(a.f("Primary connection is healthy."),a.Cb=!0):setTimeout(function(){Bg(a)},Math.floor(5E3))} -function Bg(a){a.Cb||1!==a.L||(a.f("sending ping on primary."),Dg(a,{t:"c",d:{t:"p",d:{}}}))}function Dg(a,b){if(1!==a.L)throw"Connection is not connected";a.Xc.send(b)}sg.prototype.close=function(){2!==this.L&&(this.f("Closing realtime connection."),this.L=2,zg(this),this.ja&&(this.ja(),this.ja=null))};function zg(a){a.f("Shutting down all connections");a.I&&(a.I.close(),a.I=null);a.D&&(a.D.close(),a.D=null);a.md&&(clearTimeout(a.md),a.md=null)};function Eg(a,b,c,d,e,f){this.id=Fg++;this.f=Vc("p:"+this.id+":");this.qd={};this.aa={};this.qa=[];this.Pc=0;this.Lc=[];this.na=!1;this.Va=1E3;this.td=3E5;this.Hb=b;this.Kc=c;this.ue=d;this.M=a;this.pb=this.Ia=this.Db=this.ze=null;this.Vd=e;this.de=!1;this.ke=0;if(f)throw Error("Auth override specified in options, but not supported on non Node.js platforms");this.Je=f||null;this.vb=null;this.Nb=!1;this.Gd={};this.tg=0;this.Ve=!0;this.Bc=this.me=null;Gg(this,0);He.Wb().hc("visible",this.jg,this);-1=== -a.host.indexOf("fblocal")&&Re.Wb().hc("online",this.ig,this)}var Fg=0,Hg=0;g=Eg.prototype;g.va=function(a,b,c){var d=++this.tg;a={r:d,a:a,b:b};this.f(B(a));E(this.na,"sendRequest call when we're not connected not allowed.");this.Ia.va(a);c&&(this.Gd[d]=c)}; -g.df=function(a,b,c,d){var e=a.ka(),f=a.path.toString();this.f("Listen called for "+f+" "+e);this.aa[f]=this.aa[f]||{};E(zf(a.n)||!T(a.n),"listen() called for non-default but complete query");E(!this.aa[f][e],"listen() called twice for same path/queryId.");a={G:d,ld:b,pg:a,tag:c};this.aa[f][e]=a;this.na&&Ig(this,a)}; -function Ig(a,b){var c=b.pg,d=c.path.toString(),e=c.ka();a.f("Listen on "+d+" for "+e);var f={p:d};b.tag&&(f.q=yf(c.n),f.t=b.tag);f.h=b.ld();a.va("q",f,function(f){var k=f.d,m=f.s;if(k&&"object"===typeof k&&Hb(k,"w")){var l=A(k,"w");da(l)&&0<=Fa(l,"no_index")&&L("Using an unspecified index. Consider adding "+('".indexOn": "'+c.n.g.toString()+'"')+" at "+c.path.toString()+" to your security rules for better performance")}(a.aa[d]&&a.aa[d][e])===b&&(a.f("listen response",f),"ok"!==m&&Jg(a,d,e),b.G&& -b.G(m,k))})}g.qf=function(a){this.pb=a;this.f("Auth token refreshed");this.pb?Kg(this):this.na&&this.va("unauth",{},function(){});if(a&&40===a.length||ld(a))this.f("Admin auth credential detected. Reducing max reconnect time."),this.td=3E4};function Kg(a){if(a.na&&a.pb){var b=a.pb,c=kd(b)?"auth":"gauth",d={cred:b};a.Je&&(d.authvar=a.Je);a.va(c,d,function(c){var d=c.s;c=c.d||"error";a.pb===b&&("ok"===d?this.ke=0:Lg(a,d,c))})}} -g.Ef=function(a,b){var c=a.path.toString(),d=a.ka();this.f("Unlisten called for "+c+" "+d);E(zf(a.n)||!T(a.n),"unlisten() called for non-default but complete query");if(Jg(this,c,d)&&this.na){var e=yf(a.n);this.f("Unlisten on "+c+" for "+d);c={p:c};b&&(c.q=e,c.t=b);this.va("n",c)}};g.re=function(a,b,c){this.na?Mg(this,"o",a,b,c):this.Lc.push({we:a,action:"o",data:b,G:c})};g.gf=function(a,b,c){this.na?Mg(this,"om",a,b,c):this.Lc.push({we:a,action:"om",data:b,G:c})}; -g.xd=function(a,b){this.na?Mg(this,"oc",a,null,b):this.Lc.push({we:a,action:"oc",data:null,G:b})};function Mg(a,b,c,d,e){c={p:c,d:d};a.f("onDisconnect "+b,c);a.va(b,c,function(a){e&&setTimeout(function(){e(a.s,a.d)},Math.floor(0))})}g.put=function(a,b,c,d){Ng(this,"p",a,b,c,d)};g.ef=function(a,b,c,d){Ng(this,"m",a,b,c,d)};function Ng(a,b,c,d,e,f){d={p:c,d:d};p(f)&&(d.h=f);a.qa.push({action:b,sf:d,G:e});a.Pc++;b=a.qa.length-1;a.na?Og(a,b):a.f("Buffering put: "+c)} -function Og(a,b){var c=a.qa[b].action,d=a.qa[b].sf,e=a.qa[b].G;a.qa[b].qg=a.na;a.va(c,d,function(d){a.f(c+" response",d);delete a.qa[b];a.Pc--;0===a.Pc&&(a.qa=[]);e&&e(d.s,d.d)})}g.ye=function(a){this.na&&(a={c:a},this.f("reportStats",a),this.va("s",a,function(a){"ok"!==a.s&&this.f("reportStats","Error sending stats: "+a.d)}))}; -g.wd=function(a){if("r"in a){this.f("from server: "+B(a));var b=a.r,c=this.Gd[b];c&&(delete this.Gd[b],c(a.b))}else{if("error"in a)throw"A server-side error has occurred: "+a.error;"a"in a&&(b=a.a,a=a.b,this.f("handleServerMessage",b,a),"d"===b?this.Hb(a.p,a.d,!1,a.t):"m"===b?this.Hb(a.p,a.d,!0,a.t):"c"===b?Pg(this,a.p,a.q):"ac"===b?Lg(this,a.s,a.d):"sd"===b?this.ze?this.ze(a):"msg"in a&&"undefined"!==typeof console&&console.log("FIREBASE: "+a.msg.replace("\n","\nFIREBASE: ")):Wc("Unrecognized action received from server: "+ -B(b)+"\nAre you using the latest client?"))}};g.Mc=function(a,b){this.f("connection ready");this.na=!0;this.Bc=(new Date).getTime();this.ue({serverTimeOffset:a-(new Date).getTime()});this.Db=b;if(this.Ve){var c={};c["sdk.js."+firebase.SDK_VERSION.replace(/\./g,"-")]=1;Pb()?c["framework.cordova"]=1:"object"===typeof navigator&&"ReactNative"===navigator.product&&(c["framework.reactnative"]=1);this.ye(c)}Qg(this);this.Ve=!1;this.Kc(!0)}; -function Gg(a,b){E(!a.Ia,"Scheduling a connect when we're already connected/ing?");a.vb&&clearTimeout(a.vb);a.vb=setTimeout(function(){a.vb=null;Rg(a)},Math.floor(b))}g.jg=function(a){a&&!this.Nb&&this.Va===this.td&&(this.f("Window became visible. Reducing delay."),this.Va=1E3,this.Ia||Gg(this,0));this.Nb=a};g.ig=function(a){a?(this.f("Browser went online."),this.Va=1E3,this.Ia||Gg(this,0)):(this.f("Browser went offline. Killing connection."),this.Ia&&this.Ia.close())}; -g.jf=function(){this.f("data client disconnected");this.na=!1;this.Ia=null;for(var a=0;a=b&&ch(h,c.path)?d=!1:c.path.contains(h.path)&&(e=!0));f--}if(d){if(e)this.T=dh(this.ma,eh,C),this.Cc=0f.Cc,"Stacking an older write on top of newer ones");p(h)||(h=!0);f.ma.push({path:b,Ja:c,Zc:d,visible:h});h&&(f.T=Vg(f.T,b,c));f.Cc=d;return e?sh(a,new ac(Ee,b,c)):[]}function th(a,b,c,d){var e=a.lb;E(d>e.Cc,"Stacking an older merge on top of newer ones");e.ma.push({path:b,children:c,Zc:d,visible:!0});e.T=Wg(e.T,b,c);e.Cc=d;c=se(c);return sh(a,new md(Ee,b,c))} -function uh(a,b,c){c=c||!1;var d=bh(a.lb,b);if(a.lb.Ed(b)){var e=Q;null!=d.Ja?e=e.set(C,!0):Ib(d.children,function(a,b){e=e.set(new M(a),b)});return sh(a,new De(d.path,e,c))}return[]}function vh(a,b,c){c=se(c);return sh(a,new md(Ge,b,c))}function wh(a,b,c,d){d=xh(a,d);if(null!=d){var e=yh(d);d=e.path;e=e.Ib;b=R(d,b);c=new ac(new Fe(!1,!0,e,!0),b,c);return zh(a,d,c)}return[]} -function Ah(a,b,c,d){if(d=xh(a,d)){var e=yh(d);d=e.path;e=e.Ib;b=R(d,b);c=se(c);c=new md(new Fe(!1,!0,e,!0),b,c);return zh(a,d,c)}return[]} -qh.prototype.Ob=function(a,b){var c=a.path,d=null,e=!1;ze(this.xa,c,function(a,b){var f=R(a,c);d=d||b.jb(f);e=e||null!=nh(b)});var f=this.xa.get(c);f?(e=e||null!=nh(f),d=d||f.jb(C)):(f=new mh,this.xa=this.xa.set(c,f));var h;null!=d?h=!0:(h=!1,d=F,Ce(this.xa.subtree(c),function(a,b){var c=b.jb(C);c&&(d=d.U(a,c))}));var k=null!=ph(f,a);if(!k&&!T(a.n)){var m=Bh(a);E(!(m in this.jc),"View does not exist, but we have a tag");var l=Ch++;this.jc[m]=l;this.De["_"+l]=m}h=f.Ob(a,b,new fh(c,this.lb),d,h);k|| -e||(f=ph(f,a),h=h.concat(Dh(this,a,f)));return h}; -qh.prototype.mb=function(a,b,c){var d=a.path,e=this.xa.get(d),f=[];if(e&&("default"===a.ka()||null!=ph(e,a))){f=e.mb(a,b,c);e.e()&&(this.xa=this.xa.remove(d));e=f.sg;f=f.Tf;b=-1!==Ma(e,function(a){return T(a.n)});var h=xe(this.xa,d,function(a,b){return null!=nh(b)});if(b&&!h&&(d=this.xa.subtree(d),!d.e()))for(var d=Eh(d),k=0;k=a)throw Error("Query.limitToFirst: First argument must be a positive integer.");if(this.n.ya)throw Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new X(this.u,this.path,this.n.ne(a),this.Oc)}; -g.oe=function(a){x("Query.limitToLast",1,1,arguments.length);if(!fa(a)||Math.floor(a)!==a||0>=a)throw Error("Query.limitToLast: First argument must be a positive integer.");if(this.n.ya)throw Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new X(this.u,this.path,this.n.oe(a),this.Oc)}; -g.lg=function(a){x("Query.orderByChild",1,1,arguments.length);if("$key"===a)throw Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===a)throw Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===a)throw Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');ee("Query.orderByChild",a);Nh(this,"Query.orderByChild");var b=new M(a);if(b.e())throw Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead."); -b=new We(b);b=xf(this.n,b);Lh(b);return new X(this.u,this.path,b,!0)};g.mg=function(){x("Query.orderByKey",0,0,arguments.length);Nh(this,"Query.orderByKey");var a=xf(this.n,Od);Lh(a);return new X(this.u,this.path,a,!0)};g.ng=function(){x("Query.orderByPriority",0,0,arguments.length);Nh(this,"Query.orderByPriority");var a=xf(this.n,N);Lh(a);return new X(this.u,this.path,a,!0)}; -g.og=function(){x("Query.orderByValue",0,0,arguments.length);Nh(this,"Query.orderByValue");var a=xf(this.n,bf);Lh(a);return new X(this.u,this.path,a,!0)};g.Nd=function(a,b){x("Query.startAt",0,2,arguments.length);Yd("Query.startAt",a,this.path,!0);de("Query.startAt",b);var c=this.n.Nd(a,b);Mh(c);Lh(c);if(this.n.la)throw Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");p(a)||(b=a=null);return new X(this.u,this.path,c,this.Oc)}; -g.fd=function(a,b){x("Query.endAt",0,2,arguments.length);Yd("Query.endAt",a,this.path,!0);de("Query.endAt",b);var c=this.n.fd(a,b);Mh(c);Lh(c);if(this.n.oa)throw Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new X(this.u,this.path,c,this.Oc)}; -g.Rf=function(a,b){x("Query.equalTo",1,2,arguments.length);Yd("Query.equalTo",a,this.path,!1);de("Query.equalTo",b);if(this.n.la)throw Error("Query.equalTo: Starting point was already set (by another call to endAt or equalTo).");if(this.n.oa)throw Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.Nd(a,b).fd(a,b)}; -g.toString=function(){x("Query.toString",0,0,arguments.length);for(var a=this.path,b="",c=a.Z;cb?e+="000":256>b?e+="00":4096>b&&(e+="0");return Da[a]=e+b.toString(16)}),'"')};var v;a:{var Fa=n.navigator;if(Fa){var Ga=Fa.userAgent;if(Ga){v=Ga;break a}}v=""};function Ha(a){if(Error.captureStackTrace)Error.captureStackTrace(this,Ha);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))}ka(Ha,Error);Ha.prototype.name="CustomError";var w=Array.prototype,Ia=w.indexOf?function(a,b,c){return w.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(q(a))return q(b)&&1==b.length?a.indexOf(b,c):-1;for(;cc?null:q(a)?a.charAt(c):a[c]}function Pa(a,b,c){for(var d=a.length,e=q(a)?a.split(""):a,f=0;f=arguments.length?w.slice.call(a,b):w.slice.call(a,b,c)} +function Sa(a,b){a.sort(b||Ta)}function Ta(a,b){return a>b?1:aparseFloat(a))?String(b):a})();var Ya=null,Za=null,$a=null;function ab(a,b){if(!ea(a))throw Error("encodeByteArray takes an array as a parameter");bb();for(var c=b?Za:Ya,d=[],e=0;e>2,f=(f&3)<<4|k>>4,k=(k&15)<<2|l>>6,l=l&63;m||(l=64,h||(k=64));d.push(c[u],c[f],c[k],c[l])}return d.join("")} +function bb(){if(!Ya){Ya={};Za={};$a={};for(var a=0;65>a;a++)Ya[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a),Za[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a),$a[Za[a]]=a,62<=a&&($a["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a)]=a)}};function cb(a){n.setTimeout(function(){throw a;},0)}var db; +function eb(){var a=n.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&-1==v.indexOf("Presto")&&(a=function(){var a=document.createElement("iframe");a.style.display="none";a.src="";document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=r(function(a){if(("*"==d||a.origin== +d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&-1==v.indexOf("Trident")&&-1==v.indexOf("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(p(c.next)){c=c.next;var a=c.Le;c.Le=null;a()}};return function(a){d.next={Le:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof document&&"onreadystatechange"in document.createElement("script")?function(a){var b= +document.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};document.documentElement.appendChild(b)}:function(a){n.setTimeout(a,0)}};function fb(a,b){gb||hb();ib||(gb(),ib=!0);jb.push(new kb(a,b))}var gb;function hb(){if(n.Promise&&n.Promise.resolve){var a=n.Promise.resolve();gb=function(){a.then(lb)}}else gb=function(){var a=lb;!ga(n.setImmediate)||n.Window&&n.Window.prototype&&n.Window.prototype.setImmediate==n.setImmediate?(db||(db=eb()),db(a)):n.setImmediate(a)}}var ib=!1,jb=[];[].push(function(){ib=!1;jb=[]}); +function lb(){for(;jb.length;){var a=jb;jb=[];for(var b=0;bc&&(e=0===c?"none":"no more than "+c);if(e)throw Error(a+" failed: Was called with "+d+(1===d?" argument.":" arguments.")+" Expects "+e+".");}function Db(a,b,c){var d="";switch(b){case 1:d=c?"first":"First";break;case 2:d=c?"second":"Second";break;case 3:d=c?"third":"Third";break;case 4:d=c?"fourth":"Fourth";break;default:throw Error("errorPrefix called with argumentNumber > 4. Need to update it?");}return a=a+" failed: "+(d+" argument ")} +function A(a,b,c,d){if((!d||p(c))&&!ga(c))throw Error(Db(a,b,d)+"must be a valid function.");}function Eb(a,b,c){if(p(c)&&(!ha(c)||null===c))throw Error(Db(a,b,!0)+"must be a valid context object.");};function Fb(a){var b=[];Cb(a,function(a,d){da(d)?Ja(d,function(d){b.push(encodeURIComponent(a)+"="+encodeURIComponent(d))}):b.push(encodeURIComponent(a)+"="+encodeURIComponent(d))});return b.length?"&"+b.join("&"):""};var Gb=n.Promise||mb;mb.prototype["catch"]=mb.prototype.Ag;function Hb(){var a=this;this.reject=this.resolve=null;this.sa=new Gb(function(b,c){a.resolve=b;a.reject=c})}function Ib(a,b){return function(c,d){c?a.reject(c):a.resolve(d);ga(b)&&(Jb(a.sa),1===b.length?b(c):b(c,d))}}function Jb(a){a.then(void 0,aa)};function Kb(a,b){if(!a)throw Lb(b);}function Lb(a){return Error("Firebase Database ("+firebase.SDK_VERSION+") INTERNAL ASSERT FAILED: "+a)};function Mb(a){for(var b=[],c=0,d=0;d=e&&(e-=55296,d++,Kb(de?b[c++]=e:(2048>e?b[c++]=e>>6|192:(65536>e?b[c++]=e>>12|224:(b[c++]=e>>18|240,b[c++]=e>>12&63|128),b[c++]=e>>6&63|128),b[c++]=e&63|128)}return b}function Nb(a){for(var b=0,c=0;cd?b++:2048>d?b+=2:55296<=d&&56319>=d?(b+=4,c++):b+=3}return b};function Ob(a){return"undefined"!==typeof JSON&&p(JSON.parse)?JSON.parse(a):za(a)}function B(a){if("undefined"!==typeof JSON&&p(JSON.stringify))a=JSON.stringify(a);else{var b=[];Ba(new Aa,a,b);a=b.join("")}return a};function Pb(a,b){this.committed=a;this.snapshot=b};function Qb(){return"undefined"!==typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!==typeof navigator&&"string"===typeof navigator.userAgent?navigator.userAgent:"")};function Rb(a){this.te=a;this.Bd=[];this.Rb=0;this.Yd=-1;this.Gb=null}function Sb(a,b,c){a.Yd=b;a.Gb=c;a.Yd");return a};function jc(){this.uc={}}function kc(a,b,c){p(c)||(c=1);Bb(a.uc,b)||(a.uc[b]=0);a.uc[b]+=c}jc.prototype.get=function(){return ya(this.uc)};function lc(a){this.Nf=a;this.rd=null}lc.prototype.get=function(){var a=this.Nf.get(),b=ya(a);if(this.rd)for(var c in this.rd)b[c]-=this.rd[c];this.rd=a;return b};function mc(){this.wb=[]}function nc(a,b){for(var c=null,d=0;d>4);64!=k&&(d.push(h<<4&240|k>>2),64!=m&&d.push(k<<6&192|m))}if(8192>d.length)b=String.fromCharCode.apply(null,d);else{a="";for(c=0;ca.ac?a.update(a.zd,56-a.ac):a.update(a.zd,a.Ya-(a.ac-56));for(var d=a.Ya-1;56<=d;d--)a.Wd[d]=c&255,c/=256;na(a,a.Wd);for(d=c=0;5>d;d++)for(var e=24;0<=e;e-=8)b[c]=a.N[d]>>e&255,++c;return ab(b)}function Vc(a){for(var b="",c=0;c.firebaseio.com instead"); +c&&"undefined"!=c||$c("Cannot parse Firebase url. Please use https://.firebaseio.com");d||"undefined"!==typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&O("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");return{kc:new gc(b,d,c,"ws"===e||"wss"===e),path:new L(f)}}function bd(a){return fa(a)&&(a!=a||a==Number.POSITIVE_INFINITY||a==Number.NEGATIVE_INFINITY)} +function cd(a){if("complete"===document.readyState)a();else{var b=!1,c=function(){document.body?b||(b=!0,a()):setTimeout(c,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",c,!1),window.addEventListener("load",c,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&c()}),window.attachEvent("onload",c))}} +function Hc(a,b){if(a===b)return 0;if("[MIN_NAME]"===a||"[MAX_NAME]"===b)return-1;if("[MIN_NAME]"===b||"[MAX_NAME]"===a)return 1;var c=dd(a),d=dd(b);return null!==c?null!==d?0==c-d?a.length-b.length:c-d:-1:null!==d?1:aa?c.push(a.substring(d,a.length)):c.push(a.substring(d,d+b));return c}function hd(a,b){if(da(a))for(var c=0;ca,a=Math.abs(a),a>=Math.pow(2,-1022)?(d=Math.min(Math.floor(Math.log(a)/Math.LN2),1023),c=d+1023,d=Math.round(a*Math.pow(2,52-d)-Math.pow(2,52))):(c=0,d=Math.round(a/Math.pow(2,-1074))));e=[];for(a=52;a;--a)e.push(d%2?1:0),d=Math.floor(d/2);for(a=11;a;--a)e.push(c%2?1:0),c=Math.floor(c/2);e.push(b?1:0);e.reverse();b=e.join("");c="";for(a=0;64>a;a+=8)d=parseInt(b.substr(a,8),2).toString(16),1===d.length&& +(d="0"+d),c+=d;return c.toLowerCase()}var jd=/^-?\d{1,10}$/;function dd(a){return jd.test(a)&&(a=Number(a),-2147483648<=a&&2147483647>=a)?a:null}function Ub(a){try{a()}catch(b){setTimeout(function(){O("Exception was thrown by user callback.",b.stack||"");throw b;},Math.floor(0))}}function kd(a,b,c){Object.defineProperty(a,b,{get:c})}function ld(a,b){var c=setTimeout(a,b);"object"===typeof c&&c.unref&&c.unref();return c};function md(a){var b={},c={},d={},e="";try{var f=a.split("."),b=Ob(Tc(f[0])||""),c=Ob(Tc(f[1])||""),e=f[2],d=c.d||{};delete c.d}catch(h){}return{Fg:b,Me:c,data:d,xg:e}}function nd(a){a=md(a);var b=a.Me;return!!a.xg&&!!b&&"object"===typeof b&&b.hasOwnProperty("iat")}function od(a){a=md(a).Me;return"object"===typeof a&&!0===x(a,"admin")};function pd(a,b,c){this.f=Yc("p:rest:");this.M=a;this.Hb=b;this.Vd=c;this.aa={}}function qd(a,b){if(p(b))return"tag$"+b;H(rd(a.n),"should have a tag if it's not a default query.");return a.path.toString()}g=pd.prototype; +g.df=function(a,b,c,d){var e=a.path.toString();this.f("Listen called for "+e+" "+a.ka());var f=qd(a,c),h={};this.aa[f]=h;a=sd(a.n);var k=this;td(this,e+".json",a,function(a,b){var u=b;404===a&&(a=u=null);null===a&&k.Hb(e,u,!1,c);x(k.aa,f)===h&&d(a?401==a?"permission_denied":"rest_error:"+a:"ok",null)})};g.Ef=function(a,b){var c=qd(a,b);delete this.aa[c]};g.qf=function(){};g.re=function(){};g.gf=function(){};g.xd=function(){};g.put=function(){};g.ef=function(){};g.ye=function(){}; +function td(a,b,c,d){c=c||{};c.format="export";a.Vd.getToken(!1).then(function(e){(e=e&&e.accessToken)&&(c.auth=e);var f=(a.M.Sc?"https://":"http://")+a.M.host+b+"?"+Fb(c);a.f("Sending REST request for "+f);var h=new XMLHttpRequest;h.onreadystatechange=function(){if(d&&4===h.readyState){a.f("REST Response for "+f+" received. status:",h.status,"response:",h.responseText);var b=null;if(200<=h.status&&300>h.status){try{b=Ob(h.responseText)}catch(c){O("Failed to parse JSON response for "+f+": "+h.responseText)}d(null, +b)}else 401!==h.status&&404!==h.status&&O("Got unsuccessful REST response for "+f+" Status: "+h.status),d(h.status);d=null}};h.open("GET",f,!0);h.send()})};function vd(a,b,c){this.type=wd;this.source=a;this.path=b;this.children=c}vd.prototype.Nc=function(a){if(this.path.e())return a=this.children.subtree(new L(a)),a.e()?null:a.value?new $b(this.source,C,a.value):new vd(this.source,C,a);H(J(this.path)===a,"Can't get a merge for a child not on the path of the operation");return new vd(this.source,D(this.path),this.children)};vd.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"};function xd(a,b){this.zf={};this.Vc=new lc(a);this.wa=b;var c=1E4+2E4*Math.random();ld(r(this.rf,this),Math.floor(c))}xd.prototype.rf=function(){var a=this.Vc.get(),b={},c=!1,d;for(d in a)0=a.length){var b=Number(a);if(!isNaN(b)){e.Fe=b;e.frames=[];a=null;break a}}e.Fe=1;e.frames=[]}null!==a&&Gd(e,a)}};this.La.onerror=function(a){e.f("WebSocket error. Closing connection.");(a=a.message||a.data)&&e.f(a);e.fb()}};Dd.prototype.start=function(){}; +Dd.isAvailable=function(){var a=!1;if("undefined"!==typeof navigator&&navigator.userAgent){var b=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);b&&1parseFloat(b[1])&&(a=!0)}return!a&&null!==Cd&&!Ed};Dd.responsesRequiredToBeHealthy=2;Dd.healthyTimeout=3E4;g=Dd.prototype;g.sd=function(){Yb.remove("previous_websocket_failure")};function Gd(a,b){a.frames.push(b);if(a.frames.length==a.Fe){var c=a.frames.join("");a.frames=null;c=Ob(c);a.hg(c)}} +g.send=function(a){Fd(this);a=B(a);this.rb+=a.length;kc(this.Xa,"bytes_sent",a.length);a=gd(a,16384);1=this.g.compare(this.Uc,a)&&0>=this.g.compare(a,this.wc)};g.F=function(a,b,c,d,e,f){this.matches(new K(b,c))||(c=F);return this.he.F(a,b,c,d,e,f)}; +g.za=function(a,b,c){b.J()&&(b=F);var d=b.ob(this.g),d=d.ga(F),e=this;b.P(N,function(a,b){e.matches(new K(a,b))||(d=d.U(a,F))});return this.he.za(a,d,c)};g.ga=function(a){return a};g.Qa=function(){return!0};g.Vb=function(){return this.he};function le(a){this.ta=new ge(a);this.g=a.g;H(a.ya,"Only valid if limit has been set");this.pa=a.pa;this.Jb=!me(a)}g=le.prototype;g.F=function(a,b,c,d,e,f){this.ta.matches(new K(b,c))||(c=F);return a.R(b).$(c)?a:a.Fb()=this.g.compare(this.ta.Uc,f):0>=this.g.compare(f,this.ta.wc))d=d.U(f.name,f.S),e++;else break}}else{d=b.ob(this.g);d=d.ga(F);var k,m,l;if(this.Jb){b=d.$e(this.g);k=this.ta.wc;m=this.ta.Uc;var u=oe(this.g);l=function(a,b){return u(b,a)}}else b=d.Xb(this.g),k=this.ta.Uc, +m=this.ta.wc,l=oe(this.g);for(var e=0,z=!1;0=l(k,f)&&(z=!0),(h=z&&e=l(f,m))?e++:d=d.U(f.name,F)}return this.ta.Vb().za(a,d,c)};g.ga=function(a){return a};g.Qa=function(){return!0};g.Vb=function(){return this.ta.Vb()}; +function ne(a,b,c,d,e,f){var h;if(a.Jb){var k=oe(a.g);h=function(a,b){return k(b,a)}}else h=oe(a.g);H(b.Fb()==a.pa,"");var m=new K(c,d),l=a.Jb?pe(b,a.g):qe(b,a.g),u=a.ta.matches(m);if(b.Fa(c)){for(var z=b.R(c),l=e.fe(a.g,l,a.Jb);null!=l&&(l.name==c||b.Fa(l.name));)l=e.fe(a.g,l,a.Jb);e=null==l?1:h(l,m);if(u&&!d.e()&&0<=e)return null!=f&&Jd(f,new I("child_changed",d,c,z)),b.U(c,d);null!=f&&Jd(f,new I("child_removed",z,c));b=b.U(c,F);return null!=l&&a.ta.matches(l)?(null!=f&&Jd(f,new I("child_added", +l.S,l.name)),b.U(l.name,l.S)):b}return d.e()?b:u&&0<=h(l,m)?(null!=f&&(Jd(f,new I("child_removed",l.S,l.name)),Jd(f,new I("child_added",d,c))),b.U(c,d).U(l.name,F)):b};function Qc(a,b){this.B=a;H(p(this.B)&&null!==this.B,"LeafNode shouldn't be created with null/undefined value.");this.ba=b||F;re(this.ba);this.Eb=null}var se=["object","boolean","number","string"];g=Qc.prototype;g.J=function(){return!0};g.C=function(){return this.ba};g.ga=function(a){return new Qc(this.B,a)};g.R=function(a){return".priority"===a?this.ba:F};g.Q=function(a){return a.e()?this:".priority"===J(a)?this.ba:F};g.Fa=function(){return!1};g.Ze=function(){return null}; +g.U=function(a,b){return".priority"===a?this.ga(b):b.e()&&".priority"!==a?this:F.U(a,b).ga(this.ba)};g.F=function(a,b){var c=J(a);if(null===c)return b;if(b.e()&&".priority"!==c)return this;H(".priority"!==c||1===$d(a),".priority must be the last token in a path");return this.U(c,F.F(D(a),b))};g.e=function(){return!1};g.Fb=function(){return 0};g.P=function(){return!1};g.H=function(a){return a&&!this.C().e()?{".value":this.Ea(),".priority":this.C().H()}:this.Ea()}; +g.hash=function(){if(null===this.Eb){var a="";this.ba.e()||(a+="priority:"+te(this.ba.H())+":");var b=typeof this.B,a=a+(b+":"),a="number"===b?a+id(this.B):a+this.B;this.Eb=Uc(a)}return this.Eb};g.Ea=function(){return this.B};g.tc=function(a){if(a===F)return 1;if(a instanceof P)return-1;H(a.J(),"Unknown node type");var b=typeof a.B,c=typeof this.B,d=Ia(se,b),e=Ia(se,c);H(0<=d,"Unknown leaf type: "+b);H(0<=e,"Unknown leaf type: "+c);return d===e?"object"===c?0:this.Bdocument.domain="'+document.domain+'";\x3c/script>');a=""+a+"";try{this.Ga.ib.open(),this.Ga.ib.write(a),this.Ga.ib.close()}catch(f){E("frame writing exception"),f.stack&&E(f.stack),E(f)}} +Te.prototype.close=function(){this.Ud=!1;if(this.Ga){this.Ga.ib.body.innerHTML="";var a=this;setTimeout(function(){null!==a.Ga&&(document.body.removeChild(a.Ga),a.Ga=null)},Math.floor(0))}var b=this.kb;b&&(this.kb=null,b())}; +function We(a){if(a.Ud&&a.Kd&&a.ve.count()<(0=a.Qc[0].Se.length+30+c.length){var e=a.Qc.shift(),c=c+"&seg"+d+"="+e.ug+"&ts"+d+"="+e.Bg+"&d"+d+"="+e.Se;d++}else break;Xe(a,b+c,a.$d);return!0}return!1}function Xe(a,b,c){function d(){a.ve.remove(c);We(a)}a.ve.add(c,1);var e=setTimeout(d,Math.floor(25E3));Ve(a,b,function(){clearTimeout(e);d()})} +function Ve(a,b,c){setTimeout(function(){try{if(a.Kd){var d=a.Ga.ib.createElement("script");d.type="text/javascript";d.async=!0;d.src=b;d.onload=d.onreadystatechange=function(){var a=d.readyState;a&&"loaded"!==a&&"complete"!==a||(d.onload=d.onreadystatechange=null,d.parentNode&&d.parentNode.removeChild(d),c())};d.onerror=function(){E("Long-poll script failed to load: "+b);a.Kd=!1;a.close()};a.Ga.ib.body.appendChild(d)}}catch(e){}},Math.floor(1))};function Ye(a){Ze(this,a)}var $e=[Qe,Dd];function Ze(a,b){var c=Dd&&Dd.isAvailable(),d=c&&!(Yb.cf||!0===Yb.get("previous_websocket_failure"));b.Cg&&(c||O("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),d=!0);if(d)a.Wc=[Dd];else{var e=a.Wc=[];hd($e,function(a,b){b&&b.isAvailable()&&e.push(b)})}}function af(a){if(0=a.xf?(a.f("Secondary connection is healthy."),a.Cb=!0,a.D.sd(),a.D.start(),a.f("sending client ack on secondary"),a.D.send({t:"c",d:{t:"a",d:{}}}),a.f("Ending transmission on primary"),a.I.send({t:"c",d:{t:"n",d:{}}}),a.Xc=a.D,hf(a)):(a.f("sending ping on secondary."),a.D.send({t:"c",d:{t:"p",d:{}}}))}bf.prototype.wd=function(a){kf(this);this.te(a)};function kf(a){a.Cb||(a.xe--,0>=a.xe&&(a.f("Primary connection is healthy."),a.Cb=!0,a.I.sd()))} +function gf(a,b){a.D=new b("c:"+a.id+":"+a.Oe++,a.M,a.yf);a.xf=b.responsesRequiredToBeHealthy||0;a.D.open(df(a,a.D),ef(a,a.D));ld(function(){a.D&&(a.f("Timed out trying to upgrade."),a.D.close())},Math.floor(6E4))}function ff(a,b,c){a.f("Realtime connection established.");a.I=b;a.L=1;a.Mc&&(a.Mc(c,a.yf),a.Mc=null);0===a.xe?(a.f("Primary connection is healthy."),a.Cb=!0):ld(function(){lf(a)},Math.floor(5E3))} +function lf(a){a.Cb||1!==a.L||(a.f("sending ping on primary."),nf(a,{t:"c",d:{t:"p",d:{}}}))}function nf(a,b){if(1!==a.L)throw"Connection is not connected";a.Xc.send(b)}bf.prototype.close=function(){2!==this.L&&(this.f("Closing realtime connection."),this.L=2,jf(this),this.ja&&(this.ja(),this.ja=null))};function jf(a){a.f("Shutting down all connections");a.I&&(a.I.close(),a.I=null);a.D&&(a.D.close(),a.D=null);a.md&&(clearTimeout(a.md),a.md=null)};function L(a,b){if(1==arguments.length){this.o=a.split("/");for(var c=0,d=0;d=a.o.length?null:a.o[a.Z]}function $d(a){return a.o.length-a.Z}function D(a){var b=a.Z;b=this.o.length)return null;for(var a=[],b=this.Z;b=this.o.length};g.$=function(a){if($d(this)!==$d(a))return!1;for(var b=this.Z,c=a.Z;b<=this.o.length;b++,c++)if(this.o[b]!==a.o[c])return!1;return!0}; +g.contains=function(a){var b=this.Z,c=a.Z;if($d(this)>$d(a))return!1;for(;b10485760/3&&10485760f;f++)b[f]=Math.floor(64*Math.random());for(f=0;12>f;f++)c+="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".charAt(b[f]);H(20===c.length,"nextPushId: Length should be 20."); +return c}}();function Vf(a,b){this.Oa=a;this.ca=b?b:Wf}g=Vf.prototype;g.Ra=function(a,b){return new Vf(this.Oa,this.ca.Ra(a,b,this.Oa).Y(null,null,!1,null,null))};g.remove=function(a){return new Vf(this.Oa,this.ca.remove(a,this.Oa).Y(null,null,!1,null,null))};g.get=function(a){for(var b,c=this.ca;!c.e();){b=this.Oa(a,c.key);if(0===b)return c.value;0>b?c=c.left:0c?d=d.left:0e)a=this.le?a.left:a.right;else if(0===e){this.Sa.push(a);break}else this.Sa.push(a),a=this.le?a.right:a.left} +function R(a){if(0===a.Sa.length)return null;var b=a.Sa.pop(),c;c=a.Hd?a.Hd(b.key,b.value):{key:b.key,value:b.value};if(a.le)for(b=b.left;!b.e();)a.Sa.push(b),b=b.right;else for(b=b.right;!b.e();)a.Sa.push(b),b=b.left;return c}function Zf(a){if(0===a.Sa.length)return null;var b;b=a.Sa;b=b[b.length-1];return a.Hd?a.Hd(b.key,b.value):{key:b.key,value:b.value}}function $f(a,b,c,d,e){this.key=a;this.value=b;this.color=null!=c?c:!0;this.left=null!=d?d:Wf;this.right=null!=e?e:Wf}g=$f.prototype; +g.Y=function(a,b,c,d,e){return new $f(null!=a?a:this.key,null!=b?b:this.value,null!=c?c:this.color,null!=d?d:this.left,null!=e?e:this.right)};g.count=function(){return this.left.count()+1+this.right.count()};g.e=function(){return!1};g.ia=function(a){return this.left.ia(a)||a(this.key,this.value)||this.right.ia(a)};function ag(a){return a.left.e()?a:ag(a.left)}g.Hc=function(){return ag(this).key};g.fc=function(){return this.right.e()?this.key:this.right.fc()}; +g.Ra=function(a,b,c){var d,e;e=this;d=c(a,e.key);e=0>d?e.Y(null,null,null,e.left.Ra(a,b,c),null):0===d?e.Y(null,b,null,null,null):e.Y(null,null,null,null,e.right.Ra(a,b,c));return bg(e)};function cg(a){if(a.left.e())return Wf;a.left.fa()||a.left.left.fa()||(a=dg(a));a=a.Y(null,null,null,cg(a.left),null);return bg(a)} +g.remove=function(a,b){var c,d;c=this;if(0>b(a,c.key))c.left.e()||c.left.fa()||c.left.left.fa()||(c=dg(c)),c=c.Y(null,null,null,c.left.remove(a,b),null);else{c.left.fa()&&(c=eg(c));c.right.e()||c.right.fa()||c.right.left.fa()||(c=fg(c),c.left.left.fa()&&(c=eg(c),c=fg(c)));if(0===b(a,c.key)){if(c.right.e())return Wf;d=ag(c.right);c=c.Y(d.key,d.value,null,null,cg(c.right))}c=c.Y(null,null,null,null,c.right.remove(a,b))}return bg(c)};g.fa=function(){return this.color}; +function bg(a){a.right.fa()&&!a.left.fa()&&(a=gg(a));a.left.fa()&&a.left.left.fa()&&(a=eg(a));a.left.fa()&&a.right.fa()&&(a=fg(a));return a}function dg(a){a=fg(a);a.right.left.fa()&&(a=a.Y(null,null,null,null,eg(a.right)),a=gg(a),a=fg(a));return a}function gg(a){return a.right.Y(null,null,a.color,a.Y(null,null,!0,null,a.right.left),null)}function eg(a){return a.left.Y(null,null,a.color,null,a.Y(null,null,!0,a.left.right,null))} +function fg(a){return a.Y(null,null,!a.color,a.left.Y(null,null,!a.left.color,null,null),a.right.Y(null,null,!a.right.color,null,null))}function hg(){}g=hg.prototype;g.Y=function(){return this};g.Ra=function(a,b){return new $f(a,b,null)};g.remove=function(){return this};g.count=function(){return 0};g.e=function(){return!0};g.ia=function(){return!1};g.Hc=function(){return null};g.fc=function(){return null};g.fa=function(){return!1};var Wf=new hg;function P(a,b,c){this.m=a;(this.ba=b)&&re(this.ba);a.e()&&H(!this.ba||this.ba.e(),"An empty node cannot have a priority");this.zb=c;this.Eb=null}g=P.prototype;g.J=function(){return!1};g.C=function(){return this.ba||F};g.ga=function(a){return this.m.e()?this:new P(this.m,a,this.zb)};g.R=function(a){if(".priority"===a)return this.C();a=this.m.get(a);return null===a?F:a};g.Q=function(a){var b=J(a);return null===b?this:this.R(b).Q(D(a))};g.Fa=function(a){return null!==this.m.get(a)}; +g.U=function(a,b){H(b,"We should always be passing snapshot nodes");if(".priority"===a)return this.ga(b);var c=new K(a,b),d,e;b.e()?(d=this.m.remove(a),c=Me(this.zb,c,this.m)):(d=this.m.Ra(a,b),c=Ke(this.zb,c,this.m));e=d.e()?F:this.ba;return new P(d,e,c)};g.F=function(a,b){var c=J(a);if(null===c)return b;H(".priority"!==J(a)||1===$d(a),".priority must be the last token in a path");var d=this.R(c).F(D(a),b);return this.U(c,d)};g.e=function(){return this.m.e()};g.Fb=function(){return this.m.count()}; +var ig=/^(0|[1-9]\d*)$/;g=P.prototype;g.H=function(a){if(this.e())return null;var b={},c=0,d=0,e=!0;this.P(N,function(f,h){b[f]=h.H(a);c++;e&&ig.test(f)?d=Math.max(d,Number(f)):e=!1});if(!a&&e&&d<2*c){var f=[],h;for(h in b)f[h]=b[h];return f}a&&!this.C().e()&&(b[".priority"]=this.C().H());return b};g.hash=function(){if(null===this.Eb){var a="";this.C().e()||(a+="priority:"+te(this.C().H())+":");this.P(N,function(b,c){var d=c.hash();""!==d&&(a+=":"+b+":"+d)});this.Eb=""===a?"":Uc(a)}return this.Eb}; +g.Ze=function(a,b,c){return(c=jg(this,c))?(a=Xf(c,new K(a,b)))?a.name:null:Xf(this.m,a)};function pe(a,b){var c;c=(c=jg(a,b))?(c=c.Hc())&&c.name:a.m.Hc();return c?new K(c,a.m.get(c)):null}function qe(a,b){var c;c=(c=jg(a,b))?(c=c.fc())&&c.name:a.m.fc();return c?new K(c,a.m.get(c)):null}g.P=function(a,b){var c=jg(this,a);return c?c.ia(function(a){return b(a.name,a.S)}):this.m.ia(b)};g.Xb=function(a){return this.Yb(a.Ic(),a)}; +g.Yb=function(a,b){var c=jg(this,b);if(c)return c.Yb(a,function(a){return a});for(var c=this.m.Yb(a.name,Jc),d=Zf(c);null!=d&&0>b.compare(d,a);)R(c),d=Zf(c);return c};g.$e=function(a){return this.$b(a.Gc(),a)};g.$b=function(a,b){var c=jg(this,b);if(c)return c.$b(a,function(a){return a});for(var c=this.m.$b(a.name,Jc),d=Zf(c);null!=d&&0=a)throw Error("Query.limitToFirst: First argument must be a positive integer.");if(this.n.ya)throw Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new X(this.u,this.path,this.n.ne(a),this.Oc)}; +g.oe=function(a){y("Query.limitToLast",1,1,arguments.length);if(!fa(a)||Math.floor(a)!==a||0>=a)throw Error("Query.limitToLast: First argument must be a positive integer.");if(this.n.ya)throw Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new X(this.u,this.path,this.n.oe(a),this.Oc)}; +g.lg=function(a){y("Query.orderByChild",1,1,arguments.length);if("$key"===a)throw Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===a)throw Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===a)throw Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');Lf("Query.orderByChild",a);wg(this,"Query.orderByChild");var b=new L(a);if(b.e())throw Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead."); +b=new xe(b);b=He(this.n,b);ug(b);return new X(this.u,this.path,b,!0)};g.mg=function(){y("Query.orderByKey",0,0,arguments.length);wg(this,"Query.orderByKey");var a=He(this.n,ee);ug(a);return new X(this.u,this.path,a,!0)};g.ng=function(){y("Query.orderByPriority",0,0,arguments.length);wg(this,"Query.orderByPriority");var a=He(this.n,N);ug(a);return new X(this.u,this.path,a,!0)}; +g.og=function(){y("Query.orderByValue",0,0,arguments.length);wg(this,"Query.orderByValue");var a=He(this.n,De);ug(a);return new X(this.u,this.path,a,!0)};g.Nd=function(a,b){y("Query.startAt",0,2,arguments.length);Ef("Query.startAt",a,this.path,!0);Kf("Query.startAt",b);var c=this.n.Nd(a,b);vg(c);ug(c);if(this.n.la)throw Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");p(a)||(b=a=null);return new X(this.u,this.path,c,this.Oc)}; +g.fd=function(a,b){y("Query.endAt",0,2,arguments.length);Ef("Query.endAt",a,this.path,!0);Kf("Query.endAt",b);var c=this.n.fd(a,b);vg(c);ug(c);if(this.n.oa)throw Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new X(this.u,this.path,c,this.Oc)}; +g.Rf=function(a,b){y("Query.equalTo",1,2,arguments.length);Ef("Query.equalTo",a,this.path,!1);Kf("Query.equalTo",b);if(this.n.la)throw Error("Query.equalTo: Starting point was already set (by another call to endAt or equalTo).");if(this.n.oa)throw Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.Nd(a,b).fd(a,b)}; +g.toString=function(){y("Query.toString",0,0,arguments.length);for(var a=this.path,b="",c=a.Z;c=b&&dh(h,c.path)?d=!1:c.path.contains(h.path)&&(e=!0));f--}if(d){if(e)this.T=eh(this.ma,fh,C),this.Cc=0f.Cc,"Stacking an older write on top of newer ones");p(h)||(h=!0);f.ma.push({path:b,Ja:c,Zc:d,visible:h});h&&(f.T=Sg(f.T,b,c));f.Cc=d;return e?Fh(a,new $b(Ng,b,c)):[]}function Gh(a,b,c,d){var e=a.lb;H(d>e.Cc,"Stacking an older merge on top of newer ones");e.ma.push({path:b,children:c,Zc:d,visible:!0});e.T=Tg(e.T,b,c);e.Cc=d;c=Bg(c);return Fh(a,new vd(Ng,b,c))} +function Hh(a,b,c){c=c||!1;var d=ch(a.lb,b);if(a.lb.Ed(b)){var e=Q;null!=d.Ja?e=e.set(C,!0):Cb(d.children,function(a,b){e=e.set(new L(a),b)});return Fh(a,new Mg(d.path,e,c))}return[]}function Ih(a,b,c){c=Bg(c);return Fh(a,new vd(Pg,b,c))}function Jh(a,b,c,d){d=Kh(a,d);if(null!=d){var e=Lh(d);d=e.path;e=e.Ib;b=T(d,b);c=new $b(new Og(!1,!0,e,!0),b,c);return Mh(a,d,c)}return[]} +function Nh(a,b,c,d){if(d=Kh(a,d)){var e=Lh(d);d=e.path;e=e.Ib;b=T(d,b);c=Bg(c);c=new vd(new Og(!1,!0,e,!0),b,c);return Mh(a,d,c)}return[]} +Dh.prototype.Ob=function(a,b){var c=a.path,d=null,e=!1;Ig(this.xa,c,function(a,b){var f=T(a,c);d=d||b.jb(f);e=e||null!=Zg(b)});var f=this.xa.get(c);f?(e=e||null!=Zg(f),d=d||f.jb(C)):(f=new Yg,this.xa=this.xa.set(c,f));var h;null!=d?h=!0:(h=!1,d=F,Lg(this.xa.subtree(c),function(a,b){var c=b.jb(C);c&&(d=d.U(a,c))}));var k=null!=ah(f,a);if(!k&&!S(a.n)){var m=Oh(a);H(!(m in this.jc),"View does not exist, but we have a tag");var l=Ph++;this.jc[m]=l;this.De["_"+l]=m}h=f.Ob(a,b,new gh(c,this.lb),d,h);k|| +e||(f=ah(f,a),h=h.concat(Qh(this,a,f)));return h}; +Dh.prototype.mb=function(a,b,c){var d=a.path,e=this.xa.get(d),f=[];if(e&&("default"===a.ka()||null!=ah(e,a))){f=e.mb(a,b,c);e.e()&&(this.xa=this.xa.remove(d));e=f.sg;f=f.Tf;b=-1!==Pa(e,function(a){return S(a.n)});var h=Gg(this.xa,d,function(a,b){return null!=Zg(b)});if(b&&!h&&(d=this.xa.subtree(d),!d.e()))for(var d=Rh(d),k=0;k>> -0),ga=0,ha=function(a,b,c){return a.call.apply(a.bind,arguments)},ia=function(a,b,c){if(!a)throw Error();if(2h&&(h*=2);var c;1===O?(O=2,c=0):c=1E3*(h+Math.random());e(c)}}function g(a){ec||(ec=!0,N||(null!==m?(a||(O=2),clearTimeout(m),e(0)):a||(O=1)))}var h=1,m=null,x=!1,O=0,N=!1,ec=!1;e(0);setTimeout(function(){x=!0;g(!0)},c);return g};var la="https://firebasestorage.googleapis.com";var v=function(a,b){this.code="storage/"+a;this.message="Firebase Storage: "+b;this.serverResponse=null;this.name="FirebaseError"};u(v,Error); -var ma=function(){return new v("unknown","An unknown error occurred, please check the error payload for server response.")},na=function(){return new v("canceled","User canceled the upload/download.")},oa=function(){return new v("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")},pa=function(a,b,c){return new v("invalid-argument","Invalid argument in `"+b+"` at index "+a+": "+c)},qa=function(){return new v("app-deleted","The Firebase app was deleted.")},ra=function(a,b){return new v("invalid-format", -"String does not match format '"+a+"': "+b)};var sa=function(a,b){for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b(c,a[c])},ta=function(a){var b={};sa(a,function(a,d){b[a]=d});return b};var w=function(a,b,c,d){this.i=a;this.b={};this.method=b;this.headers={};this.body="";this.N=c;this.c=this.a=null;this.f=[200];this.g=[];this.h=d};var ua={STATE_CHANGED:"state_changed"},va={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"},wa=function(a){switch(a){case "running":case "pausing":case "canceling":return"running";case "paused":return"paused";case "success":return"success";case "canceled":return"canceled";case "error":return"error";default:return"error"}};var y=function(a){return n(a)&&null!==a},xa=function(a){return"string"===typeof a||a instanceof String},ya=function(){return"undefined"!==typeof Blob};var za=function(a,b,c){this.f=c;this.c=a;this.g=b;this.b=0;this.a=null};za.prototype.get=function(){var a;0b?1:0};var Qa=function(a,b){this.a=a;this.b=b};var z=function(a,b){this.bucket=a;this.path=b},Ra=function(a){var b=encodeURIComponent;return"/b/"+b(a.bucket)+"/o/"+b(a.path)},Sa=function(a){for(var b=null,c=[{ia:/^gs:\/\/([A-Za-z0-9.\-]+)(\/(.*))?$/i,ba:{bucket:1,path:3},ha:function(a){"/"===a.path.charAt(a.path.length-1)&&(a.path=a.path.slice(0,-1))}},{ia:/^https?:\/\/firebasestorage\.googleapis\.com\/v[A-Za-z0-9_]+\/b\/([A-Za-z0-9.\-]+)\/o(\/([^?#]*).*)?$/i,ba:{bucket:1,path:3},ha:function(a){a.path=decodeURIComponent(a.path)}}],d=0;d>> +0),ga=0,ha=function(a,b,c){return a.call.apply(a.bind,arguments)},ia=function(a,b,c){if(!a)throw Error();if(2h&&(h*=2);var c;1===Q?(Q=2,c=0):c=1E3*(h+Math.random());e(c)}}function g(a){jc||(jc=!0,P||(null!==m?(a||(Q=2),clearTimeout(m),e(0)):a||(Q=1)))}var h=1,m=null,q=!1,Q=0,P=!1,jc=!1;e(0);setTimeout(function(){q=!0;g(!0)},c);return g};var la="https://firebasestorage.googleapis.com";var w=function(a,b){this.code="storage/"+a;this.message="Firebase Storage: "+b;this.serverResponse=null;this.name="FirebaseError"};v(w,Error); +var ma=function(){return new w("unknown","An unknown error occurred, please check the error payload for server response.")},na=function(){return new w("canceled","User canceled the upload/download.")},oa=function(){return new w("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")},pa=function(a,b,c){return new w("invalid-argument","Invalid argument in `"+b+"` at index "+a+": "+c)},qa=function(){return new w("app-deleted","The Firebase app was deleted.")},ra=function(a,b){return new w("invalid-format", +"String does not match format '"+a+"': "+b)};var sa=function(a,b){for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b(c,a[c])},ta=function(a){var b={};sa(a,function(a,d){b[a]=d});return b};var x=function(a,b,c,d){this.j=a;this.b={};this.method=b;this.headers={};this.body="";this.M=c;this.c=this.a=null;this.f=[200];this.h=[];this.i=d;this.g=!0};var ua={STATE_CHANGED:"state_changed"},va={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"},wa=function(a){switch(a){case "running":case "pausing":case "canceling":return"running";case "paused":return"paused";case "success":return"success";case "canceled":return"canceled";case "error":return"error";default:return"error"}};var y=function(a){return n(a)&&null!==a},xa=function(a){return"string"===typeof a||a instanceof String},ya=function(){return"undefined"!==typeof Blob};var za=function(a,b,c){this.f=c;this.c=a;this.g=b;this.b=0;this.a=null};za.prototype.get=function(){var a;0b?1:0};var Pa=function(a,b){this.a=a;this.b=b};var Qa=function(a,b){this.bucket=a;this.path=b},Ra=function(a){var b=encodeURIComponent;return"/b/"+b(a.bucket)+"/o/"+b(a.path)},Sa=function(a){for(var b=null,c=[{ia:/^gs:\/\/([A-Za-z0-9.\-]+)(\/(.*))?$/i,ba:{bucket:1,path:3},ha:function(a){"/"===a.path.charAt(a.path.length-1)&&(a.path=a.path.slice(0,-1))}},{ia:/^https?:\/\/firebasestorage\.googleapis\.com\/v[A-Za-z0-9_]+\/b\/([A-Za-z0-9.\-]+)\/o(\/([^?#]*).*)?$/i,ba:{bucket:1,path:3},ha:function(a){a.path=decodeURIComponent(a.path)}}],d=0;d=d)b.push(d);else if(2047>=d)b.push(192|d>>6,128|d&63);else if(55296==(d&64512))if(c>18,128|d>>12&63,128|d>>6&63,128|d&63)}else b.push(239,191,189);else 56320==(d&64512)?b.push(239,191,189):b.push(224|d>>12,128|d>>6&63,128|d&63)}return new Uint8Array(b)},Ya=function(a,b){switch(a){case "base64":var c=-1!==b.indexOf("-"), d=-1!==b.indexOf("_");if(c||d)throw ra(a,"Invalid character '"+(c?"-":"_")+"' found: is it base64url encoded?");break;case "base64url":c=-1!==b.indexOf("+");d=-1!==b.indexOf("/");if(c||d)throw ra(a,"Invalid character '"+(c?"+":"/")+"' found: is it base64 encoded?");b=b.replace(/-/g,"+").replace(/_/g,"/")}var e;try{e=atob(b)}catch(f){throw ra(a,"Invalid character found");}a=new Uint8Array(e.length);for(b=0;b][;base64],");b=b[1]||null;this.a=!1;this.b=null;if(null!=b){var c=b.length-7;this.b=(this.a=0<=c&&b.indexOf(";base64",c)==c)?b.substring(0,b.length-7):b}this.c=a.substring(a.indexOf(",")+1)};var ab=function(a){var b=encodeURIComponent,c="?";sa(a,function(a,e){a=b(a)+"="+b(e);c=c+a+"&"});return c=c.slice(0,-1)};var A=function(a,b,c,d,e,f){this.b=a;this.h=b;this.f=c;this.a=d;this.g=e;this.c=f};k=A.prototype;k.na=function(){return this.b};k.Ja=function(){return this.h};k.Ga=function(){return this.f};k.Ba=function(){return this.a};k.pa=function(){if(y(this.a)){var a=this.a.downloadURLs;return y(a)&&y(a[0])?a[0]:null}return null};k.Ia=function(){return this.g};k.Ea=function(){return this.c};var bb=function(a,b){b.unshift(a);Ba.call(this,Na.apply(null,b));b.shift()};u(bb,Ba);bb.prototype.name="AssertionError"; -var cb=function(a,b,c,d){var e="Assertion failed";if(c)var e=e+(": "+c),f=d;else a&&(e+=": "+a,f=b);throw new bb(""+e,f||[]);},B=function(a,b,c){a||cb("",null,b,Array.prototype.slice.call(arguments,2))},db=function(a,b){throw new bb("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));},eb=function(a,b,c){r(a)||cb("Expected function but got %s: %s.",[p(a),a],b,Array.prototype.slice.call(arguments,2))};var fb=function(){this.g=this.g;this.o=this.o};fb.prototype.g=!1;fb.prototype.ea=function(){this.g||(this.g=!0,this.C())};fb.prototype.C=function(){if(this.o)for(;this.o.length;)this.o.shift()()};var gb="closure_listenable_"+(1E6*Math.random()|0),hb=0;var ib;a:{var jb=l.navigator;if(jb){var kb=jb.userAgent;if(kb){ib=kb;break a}}ib=""}var C=function(a){return-1!=ib.indexOf(a)};var lb=function(){};lb.prototype.b=null;lb.prototype.a=ca;var mb=function(a){return a.b||(a.b=a.f())};lb.prototype.f=ca;var nb=Array.prototype.indexOf?function(a,b,c){B(null!=a.length);return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(q(a))return q(b)&&1==b.length?a.indexOf(b,c):-1;for(;cb?null:q(a)?a.charAt(b):a[b]},ub=function(a,b){return 0<=nb(a,b)},vb=function(a){if("array"!=p(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0},wb=function(a,b){b=nb(a,b);var c;if(c=0<=b)B(null!=a.length),Array.prototype.splice.call(a, -b,1);return c},xb=function(a){var b=a.length;if(0=this.b()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c};Pb.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;d][;base64],");b=b[1]||null;this.a=!1;this.b=null;if(null!=b){var c=b.length-7;this.b=(this.a=0<=c&&b.indexOf(";base64",c)==c)?b.substring(0,b.length-7):b}this.c=a.substring(a.indexOf(",")+1)};var ab=function(a){var b=encodeURIComponent,c="?";sa(a,function(a,e){a=b(a)+"="+b(e);c=c+a+"&"});return c=c.slice(0,-1)};var A=function(a,b,c,d,e,f){this.b=a;this.h=b;this.f=c;this.a=d;this.g=e;this.c=f};k=A.prototype;k.na=function(){return this.b};k.Ja=function(){return this.h};k.Ga=function(){return this.f};k.Ba=function(){return this.a};k.pa=function(){if(y(this.a)){var a=this.a.downloadURLs;return y(a)&&y(a[0])?a[0]:null}return null};k.Ia=function(){return this.g};k.Ea=function(){return this.c};var bb=function(a,b){b.unshift(a);z.call(this,Ma.apply(null,b));b.shift()};v(bb,z);bb.prototype.name="AssertionError"; +var cb=function(a,b,c,d){var e="Assertion failed";if(c)var e=e+(": "+c),f=d;else a&&(e+=": "+a,f=b);throw new bb(""+e,f||[]);},B=function(a,b,c){a||cb("",null,b,Array.prototype.slice.call(arguments,2))},db=function(a,b){throw new bb("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));},eb=function(a,b,c){t(a)||cb("Expected function but got %s: %s.",[p(a),a],b,Array.prototype.slice.call(arguments,2))};var fb=function(){this.g=this.g;this.o=this.o};fb.prototype.g=!1;fb.prototype.ea=function(){this.g||(this.g=!0,this.D())};fb.prototype.D=function(){if(this.o)for(;this.o.length;)this.o.shift()()};var gb="closure_listenable_"+(1E6*Math.random()|0),hb=0;var ib;a:{var jb=l.navigator;if(jb){var kb=jb.userAgent;if(kb){ib=kb;break a}}ib=""}var C=function(a){return-1!=ib.indexOf(a)};var lb=function(){};lb.prototype.b=null;lb.prototype.a=ca;var mb=function(a){return a.b||(a.b=a.f())};lb.prototype.f=ca;var nb=Array.prototype.indexOf?function(a,b,c){B(null!=a.length);return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(r(a))return r(b)&&1==b.length?a.indexOf(b,c):-1;for(;cb?null:r(a)?a.charAt(b):a[b]},ub=function(a,b){return 0<=nb(a,b)},vb=function(a){if("array"!=p(a))for(var b=a.length-1;0<=b;b--)delete a[b];a.length=0},wb=function(a,b){b=nb(a,b);var c;if(c=0<=b)B(null!=a.length),Array.prototype.splice.call(a, +b,1);return c},xb=function(a){var b=a.length;if(0=this.b()){for(var c=this.a,d=0;d>1,a[d].a>c.a)a[b]=a[d],b=d;else break;a[b]=c};Pb.prototype.A=function(){for(var a=this.a,b=[],c=a.length,d=0;dparseFloat(hc)){gc=String(jc);break a}}gc=hc} -var kc=gc,La={},E=function(a){return Ma(a,function(){for(var b=0,c=Oa(String(kc)).split("."),d=Oa(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&fparseFloat(gc)){fc=String(ic);break a}}fc=gc} +var kc=fc,Ka={},E=function(a){return La(a,function(){for(var b=0,c=Na(String(kc)).split("."),d=Na(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f2*a.f&&vc(a),!0):!1},vc=function(a){if(a.f!=a.a.length){for(var b=0,c=0;b=d.a.length)throw Yb;var e=d.a[b++];return a?e:d.c[e]};return e};var xc=function(a,b){Cb.call(this,a?a.type:"");this.c=this.a=this.target=null;if(a){this.type=a.type;this.target=a.target||a.srcElement;this.a=b;if((b=a.relatedTarget)&&cc)try{Ka(b.nodeName)}catch(c){}this.c=a;a.defaultPrevented&&this.b()}};u(xc,Cb);xc.prototype.b=function(){xc.I.b.call(this);var a=this.c;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,uc)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};var G=function(a,b){this.a=0;this.i=void 0;this.c=this.b=this.f=null;this.g=this.h=!1;if(a!=ba)try{var c=this;a.call(b,function(a){yc(c,2,a)},function(a){try{if(a instanceof Error)throw a;throw Error("Promise rejected.");}catch(e){}yc(c,3,a)})}catch(d){yc(this,3,d)}},zc=function(){this.next=this.f=this.c=this.a=this.b=null;this.g=!1};zc.prototype.reset=function(){this.f=this.c=this.a=this.b=null;this.g=!1}; -var Ac=new za(function(){return new zc},function(a){a.reset()},100),Bc=function(a,b,c){var d=Ac.get();d.a=a;d.c=b;d.f=c;return d},Cc=function(a){if(a instanceof G)return a;var b=new G(ba);yc(b,2,a);return b},Dc=function(a){return new G(function(b,c){c(a)})}; -G.prototype.then=function(a,b,c){null!=a&&eb(a,"opt_onFulfilled should be a function.");null!=b&&eb(b,"opt_onRejected should be a function. Did you pass opt_context as the second argument instead of the third?");return Ec(this,r(a)?a:null,r(b)?b:null,c)};Ia(G);G.prototype.l=function(a,b){return Ec(this,null,a,b)}; -var Gc=function(a,b){a.b||2!=a.a&&3!=a.a||Fc(a);B(null!=b.a);a.c?a.c.next=b:a.b=b;a.c=b},Ec=function(a,b,c,d){var e=Bc(null,null,null);e.b=new G(function(a,g){e.a=b?function(c){try{var e=b.call(d,c);a(e)}catch(x){g(x)}}:a;e.c=c?function(b){try{var e=c.call(d,b);a(e)}catch(x){g(x)}}:g});e.b.f=a;Gc(a,e);return e.b};G.prototype.o=function(a){B(1==this.a);this.a=0;yc(this,2,a)};G.prototype.m=function(a){B(1==this.a);this.a=0;yc(this,3,a)}; -var yc=function(a,b,c){if(0==a.a){a===c&&(b=3,c=new TypeError("Promise cannot resolve to itself"));a.a=1;var d;a:{var e=c,f=a.o,g=a.m;if(e instanceof G)null!=f&&eb(f,"opt_onFulfilled should be a function."),null!=g&&eb(g,"opt_onRejected should be a function. Did you pass opt_context as the second argument instead of the third?"),Gc(e,Bc(f||ba,g||null,a)),d=!0;else if(Ja(e))e.then(f,g,a),d=!0;else{if(ea(e))try{var h=e.then;if(r(h)){Hc(e,h,f,g,a);d=!0;break a}}catch(m){g.call(a,m);d=!0;break a}d=!1}}d|| -(a.i=c,a.a=b,a.f=null,Fc(a),3!=b||Ic(a,c))}},Hc=function(a,b,c,d,e){var f=!1,g=function(a){f||(f=!0,c.call(e,a))},h=function(a){f||(f=!0,d.call(e,a))};try{b.call(a,g,h)}catch(m){h(m)}},Fc=function(a){a.h||(a.h=!0,qc(a.j,a))},Jc=function(a){var b=null;a.b&&(b=a.b,a.b=b.next,b.next=null);a.b||(a.c=null);null!=b&&B(null!=b.a);return b}; -G.prototype.j=function(){for(var a;a=Jc(this);){var b=this.a,c=this.i;if(3==b&&a.c&&!a.g){var d;for(d=this;d&&d.g;d=d.f)d.g=!1}if(a.b)a.b.f=null,Kc(a,b,c);else try{a.g?a.a.call(a.f):Kc(a,b,c)}catch(e){Lc.call(null,e)}Aa(Ac,a)}this.h=!1};var Kc=function(a,b,c){2==b?a.a.call(a.f,c):a.c&&a.c.call(a.f,c)},Ic=function(a,b){a.g=!0;qc(function(){a.g&&Lc.call(null,b)})},Lc=Vb;var Nc=function(a){this.a=new F;if(a){a=Tb(a);for(var b=a.length,c=0;cd.keyCode||void 0!=d.returnValue)){a:{var e= -!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(g){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=dd(d[e],a,!0,b),c=c&&f}for(e=0;e>>0),Tc=function(a){B(a,"Listener can not be null.");if(r(a))return a;B(a.handleEvent,"An object listener must have handleEvent method."); -a[ed]||(a[ed]=function(b){return a.handleEvent(b)});return a[ed]};var H=function(a,b){fb.call(this);this.m=a||0;this.f=b||10;if(this.m>this.f)throw Error("[goog.structs.Pool] Min can not be greater than max");this.a=new Rb;this.c=new Nc;this.j=null;this.S()};u(H,fb);H.prototype.W=function(){var a=ja();if(!(null!=this.j&&0>a-this.j)){for(var b;0this.f&&0=d.a.length)throw Yb;var e=d.a[b++];return a?e:d.c[e]};return e};var xc=function(a,b){Cb.call(this,a?a.type:"");this.c=this.a=this.target=null;if(a){this.type=a.type;this.target=a.target||a.srcElement;this.a=b;if((b=a.relatedTarget)&&cc)try{Ja(b.nodeName)}catch(c){}this.c=a;a.defaultPrevented&&this.b()}};v(xc,Cb);xc.prototype.b=function(){xc.I.b.call(this);var a=this.c;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,uc)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};var G=function(a,b){this.a=0;this.i=void 0;this.f=this.b=this.c=null;this.g=this.h=!1;if(a!=ba)try{var c=this;a.call(b,function(a){yc(c,2,a)},function(a){if(!(a instanceof zc))try{if(a instanceof Error)throw a;throw Error("Promise rejected.");}catch(e){}yc(c,3,a)})}catch(d){yc(this,3,d)}},Ac=function(){this.next=this.f=this.c=this.b=this.a=null;this.g=!1};Ac.prototype.reset=function(){this.f=this.c=this.b=this.a=null;this.g=!1}; +var Bc=new za(function(){return new Ac},function(a){a.reset()},100),Cc=function(a,b,c){var d=Bc.get();d.b=a;d.c=b;d.f=c;return d},Dc=function(a){if(a instanceof G)return a;var b=new G(ba);yc(b,2,a);return b},Ec=function(a){return new G(function(b,c){c(a)})}; +G.prototype.then=function(a,b,c){null!=a&&eb(a,"opt_onFulfilled should be a function.");null!=b&&eb(b,"opt_onRejected should be a function. Did you pass opt_context as the second argument instead of the third?");return Fc(this,t(a)?a:null,t(b)?b:null,c)};Ha(G);G.prototype.l=function(a,b){return Fc(this,null,a,b)};G.prototype.cancel=function(a){0==this.a&&qc(function(){var b=new zc(a);Gc(this,b)},this)}; +var Gc=function(a,b){if(0==a.a)if(a.c){var c=a.c;if(c.b){for(var d=0,e=null,f=null,g=c.b;g&&(g.g||(d++,g.a==a&&(e=g),!(e&&1d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode= +-1;break a}catch(g){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.a;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.a=d[e];var f=gd(d[e],a,!0,b),c=c&&f}for(e=0;e>>0),Wc=function(a){B(a,"Listener can not be null.");if(t(a))return a;B(a.handleEvent,"An object listener must have handleEvent method."); +a[hd]||(a[hd]=function(b){return a.handleEvent(b)});return a[hd]};var H=function(a,b){fb.call(this);this.m=a||0;this.f=b||10;if(this.m>this.f)throw Error("[goog.structs.Pool] Min can not be greater than max");this.a=new Rb;this.c=new Qc;this.j=null;this.S()};v(H,fb);H.prototype.W=function(){var a=ja();if(!(null!=this.j&&0>a-this.j)){for(var b;0this.f&&0=td(this).value)for(r(b)&&(b=b()),a=new Ca(a,String(b),this.f),c&&(a.a=c),c="log:"+a.b,l.console&&(l.console.timeStamp?l.console.timeStamp(c):l.console.markTimeline&&l.console.markTimeline(c)),l.msWriteProfilerMark&&l.msWriteProfilerMark(c),c=this;c;)c=c.a}; -var ud={},vd=null,wd=function(a){vd||(vd=new od(""),ud[""]=vd,vd.c=rd);var b;if(!(b=ud[a])){b=new od(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=wd(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;ud[a]=b}return b};var xd=function(){fb.call(this);this.b=new Ib(this);this.Y=this;this.G=null};u(xd,fb);xd.prototype[gb]=!0;xd.prototype.removeEventListener=function(a,b,c,d){ad(this,a,b,c,d)}; -var I=function(a,b){Uc(a);var c,d=a.G;if(d){c=[];for(var e=1;d;d=d.G)c.push(d),B(1E3>++e,"infinite loop")}a=a.Y;d=b.type||b;q(b)?b=new Cb(b,a):b instanceof Cb?b.target=b.target||a:(e=b,b=new Cb(d,a),Ha(b,e));var e=!0,f;if(c)for(var g=c.length-1;0<=g;g--)f=b.a=c[g],e=yd(f,d,!0,b)&&e;f=b.a=a;e=yd(f,d,!0,b)&&e;e=yd(f,d,!1,b)&&e;if(c)for(g=0;g=f)c=void 0;else{if(1==f)vb(e);else{e[0]=e.pop();for(var e=0,d=d.a,f=d.length,g=d[e];e>1;){var h=2*e+1,m=2*e+2,h=mg.a)break;d[e]=d[h];e=h}d[e]=g}c=c.b}c.apply(this,[b])}else break}}; -k.$=function(a){J.I.$.call(this,a);this.aa()};k.S=function(){J.I.S.call(this);this.aa()};k.C=function(){J.I.C.call(this);l.clearTimeout(void 0);vb(this.h.a);this.h=null};var K=function(a,b){a&&a.log(sd,b,void 0)};var zd=function(a,b,c){if(r(a))c&&(a=t(a,c));else if(a&&"function"==typeof a.handleEvent)a=t(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647e,h=ub([408,429],e),g=ub(g.m,e),f=f||h||g;f?(e=7===b.J,gd(b),a(!1,new Td(!1,null,e))):(e=ub(d.K,e),a(!0,new Td(e,b)))})})}function c(a,b){var c=d.o;a=d.l;var e=b.c;if(b.b)try{var f=d.w(e,Od(e));n(f)?c(f):c()}catch(x){a(x)}else null!==e?(b=ma(),f=Od(e),b.serverResponse=f,d.j?a(d.j(e,b)):a(b)):(b=b.a?d.h?qa(): -na():new v("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),a(b));gd(e)}var d=a;a.i?c(0,new Td(!1,null,!0)):a.f=ka(b,c,a.F)};Sd.prototype.a=function(){return this.D};Sd.prototype.b=function(a){this.i=!0;this.h=a||!1;null!==this.f&&(0,this.f)(!1);null!==this.c&&Hd(this.c)}; -var Ud=function(a,b,c){var d=ab(a.b),d=a.i+d,e=a.headers?ta(a.headers):{};null!==b&&0b&&(b+=a.size),0>b&&(b=0),0>c&&(c+=a.size),cb.length?b:Hb(b)};a.push(b);b=new S("size");b.a=function(a,b){return y(b)?+b:b};a.push(b);a.push(new S("timeCreated"));a.push(new S("updated"));a.push(new S("md5Hash",null,!0));a.push(new S("cacheControl", -null,!0));a.push(new S("contentDisposition",null,!0));a.push(new S("contentEncoding",null,!0));a.push(new S("contentLanguage",null,!0));a.push(new S("contentType",null,!0));a.push(new S("metadata","customMetadata",!0));a.push(new S("downloadTokens","downloadURLs",!1,function(a,b){if(!(xa(b)&&0m;m++)h+=Math.random().toString().slice(2);g["Content-Type"]="multipart/related; boundary="+h;e=ve(b,d,e);m=he(e,c);d=Xd("--"+h+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+ -m+"\r\n--"+h+"\r\nContent-Type: "+e.contentType+"\r\n\r\n",d,"\r\n--"+h+"--");if(null===d)throw oa();a=new w(la+"/v0"+f,"POST",qe(a,c),a.b);a.b={name:e.fullPath};a.headers=g;a.body=d.s;a.a=re(b);return a},xe=function(a,b,c,d){this.a=a;this.total=b;this.b=!!c;this.c=d||null},ye=function(a,b){var c;try{c=Pd(a,"X-Goog-Upload-Status")}catch(d){pe(!1)}pe(ub(b||["active"],c));return c},ze=function(a,b,c,d,e){var f="/b/"+encodeURIComponent(b.bucket)+"/o",g=ve(b,d,e);e={name:g.fullPath};f=la+"/v0"+f;d={"X-Goog-Upload-Protocol":"resumable", -"X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":d.a,"X-Goog-Upload-Header-Content-Type":g.contentType,"Content-Type":"application/json; charset=utf-8"};c=he(g,c);a=new w(f,"POST",function(a){ye(a);var b;try{b=Pd(a,"X-Goog-Upload-URL")}catch(x){pe(!1)}pe(xa(b));return b},a.b);a.b=e;a.headers=d;a.body=c;a.a=re(b);return a},Ae=function(a,b,c,d){a=new w(c,"POST",function(a){var b=ye(a,["active","final"]),c;try{c=Pd(a,"X-Goog-Upload-Size-Received")}catch(h){pe(!1)}a=c;isFinite(a)&& -(a=String(a));a=q(a)?/^\s*-?0x/i.test(a)?parseInt(a,16):parseInt(a,10):NaN;pe(!isNaN(a));return new xe(a,d.a,"final"===b)},a.b);a.headers={"X-Goog-Upload-Command":"query"};a.a=re(b);return a},Be=function(a,b,c,d,e,f){var g=new xe(0,0);f?(g.a=f.a,g.total=f.total):(g.a=0,g.total=d.a);if(d.a!==g.total)throw new v("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var h=f=g.total-g.a,h=Math.min(h,262144),m=g.a;f={"X-Goog-Upload-Command":h===f?"upload, finalize": -"upload","X-Goog-Upload-Offset":g.a};m=d.slice(m,m+h);if(null===m)throw oa();c=new w(c,"POST",function(a,c){var f=ye(a,["active","final"]),m=g.a+h,O=d.a,x;"final"===f?x=qe(b,e)(a,c):x=null;return new xe(m,O,"final"===f,x)},b.b);c.headers=f;c.body=m.s;c.c=null;c.a=re(a);return c};var W=function(a,b,c,d,e,f){this.K=a;this.c=b;this.i=c;this.f=e;this.h=f||null;this.o=d;this.j=0;this.G=this.m=!1;this.B=[];this.Z=262144c&&Le(a)},V=function(a,b){if(a.b!==b)switch(b){case "canceling":a.b=b;null!==a.a&&a.a.b();break;case "pausing":a.b=b;null!==a.a&&a.a.b();break;case "running":var c="paused"===a.b;a.b=b;c&&(Le(a),De(a));break;case "paused":a.b=b;Le(a);break;case "canceled":a.g=na();a.b=b;Le(a);break;case "error":a.b=b;Le(a);break;case "success":a.b=b,Le(a)}},Ce=function(a){switch(a.b){case "pausing":V(a,"paused");break;case "canceling":V(a, -"canceled");break;case "running":De(a)}};W.prototype.D=function(){return new A(this.j,this.f.a,wa(this.b),this.h,this,this.K)}; -W.prototype.M=function(a,b,c,d){function e(a){try{g(a);return}catch(N){}try{if(h(a),!(n(a.next)||n(a.error)||n(a.complete)))throw"";}catch(N){throw"Expected a function or an Object with one of `next`, `error`, `complete` properties.";}}function f(a){return function(b,c,d){null!==a&&T("on",a,arguments);var e=new Ta(b,c,d);Me(m,e);return function(){wb(m.B,e)}}}var g=oe().a,h=ne(null,!0).a;T("on",[ke(function(){if("state_changed"!==a)throw"Expected one of the event types: [state_changed].";}),ne(e,!0), -oe(),oe()],arguments);var m=this,x=[ne(function(a){if(null===a)throw"Expected a function or an Object with one of `next`, `error`, `complete` properties.";e(a)}),oe(),oe()];return n(b)||n(c)||n(d)?f(null)(b,c,d):f(x)};W.prototype.then=function(a,b){return this.F.then(a,b)}; -var Me=function(a,b){a.B.push(b);Ne(a,b)},Le=function(a){Oe(a);var b=xb(a.B);ob(b,function(b){Ne(a,b)})},Oe=function(a){if(null!==a.l){var b=!0;switch(wa(a.b)){case "success":Oc(a.l.bind(null,a.D()))();break;case "canceled":case "error":Oc(a.w.bind(null,a.g))();break;default:b=!1}b&&(a.l=null,a.w=null)}},Ne=function(a,b){switch(wa(a.b)){case "running":case "paused":null!==b.next&&Oc(b.next.bind(b,a.D()))();break;case "success":null!==b.b&&Oc(b.b.bind(b))();break;case "canceled":case "error":null!== -b.a&&Oc(b.a.bind(b,a.g))();break;default:null!==b.a&&Oc(b.a.bind(b,a.g))()}};W.prototype.R=function(){T("resume",[],arguments);var a="paused"===this.b||"pausing"===this.b;a&&V(this,"running");return a};W.prototype.P=function(){T("pause",[],arguments);var a="running"===this.b;a&&V(this,"pausing");return a};W.prototype.L=function(){T("cancel",[],arguments);var a="running"===this.b||"pausing"===this.b;a&&V(this,"canceling");return a};var X=function(a,b){this.b=a;if(b)this.a=b instanceof z?b:Sa(b);else if(a=a.bucket(),null!==a)this.a=new z(a,"");else throw new v("no-default-bucket","No default bucket found. Did you set the 'storageBucket' property when initializing the app?");};X.prototype.toString=function(){T("toString",[],arguments);return"gs://"+this.a.bucket+"/"+this.a.path};var Pe=function(a,b){return new X(a,b)};k=X.prototype; -k.fa=function(a){T("child",[ke()],arguments);var b=Gb(this.a.path,a);return Pe(this.b,new z(this.a.bucket,b))};k.Da=function(){var a;a=this.a.path;if(0==a.length)a=null;else{var b=a.lastIndexOf("/");a=-1===b?"":a.slice(0,b)}return null===a?null:Pe(this.b,new z(this.a.bucket,a))};k.Fa=function(){return Pe(this.b,new z(this.a.bucket,""))};k.ma=function(){return this.a.bucket};k.ya=function(){return this.a.path};k.Ca=function(){return Hb(this.a.path)};k.Ha=function(){return this.b.i}; -k.ra=function(a,b){T("put",[le(),new U(ie,!0)],arguments);Qe(this,"put");return new W(this,this.b,this.a,fe(),new Q(a),b)};k.sa=function(a,b,c){T("putString",[ke(),ke(Va,!0),new U(ie,!0)],arguments);Qe(this,"putString");var d=$a(y(b)?b:"raw",a),e=c?ta(c):{};!y(e.contentType)&&y(d.a)&&(e.contentType=d.a);return new W(this,this.b,this.a,fe(),new Q(d.data,!0),e)}; -k.delete=function(){T("delete",[],arguments);Qe(this,"delete");var a=this;return ce(this.b).then(function(b){var c=ue(a.b,a.a);return R(a.b,c,b).a()})};k.ga=function(){T("getMetadata",[],arguments);Qe(this,"getMetadata");var a=this;return ce(this.b).then(function(b){var c=te(a.b,a.a,fe());return R(a.b,c,b).a()})}; -k.ta=function(a){T("updateMetadata",[new U(ie,void 0)],arguments);Qe(this,"updateMetadata");var b=this;return ce(this.b).then(function(c){var d=b.b,e=b.a,f=a,g=fe(),h=Ra(e),h=la+"/v0"+h,f=he(f,g),d=new w(h,"PATCH",qe(d,g),d.c);d.headers={"Content-Type":"application/json; charset=utf-8"};d.body=f;d.a=se(e);return R(b.b,d,c).a()})}; -k.qa=function(){T("getDownloadURL",[],arguments);Qe(this,"getDownloadURL");return this.ga().then(function(a){a=a.downloadURLs[0];if(y(a))return a;throw new v("no-download-url","The given file does not have any download URLs.");})};var Qe=function(a,b){if(""===a.a.path)throw new v("invalid-root-operation","The operation '"+b+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').");};var Y=function(a){this.a=new be(a,function(a,c){return new X(a,c)},Ud,this);this.b=a;this.c=new Re(this)};k=Y.prototype;k.ua=function(a){T("ref",[ke(function(a){if(/^[A-Za-z]+:\/\//.test(a))throw"Expected child path but got a URL, use refFromURL instead.";},!0)],arguments);var b=new X(this.a);return n(a)?b.fa(a):b}; -k.va=function(a){T("refFromURL",[ke(function(a){if(!/^[A-Za-z]+:\/\//.test(a))throw"Expected full URL but got a child path, use ref instead.";try{Sa(a)}catch(c){throw"Expected valid full URL but got an invalid one.";}},!1)],arguments);return new X(this.a,a)};k.Aa=function(){return this.a.b};k.xa=function(a){T("setMaxUploadRetryTime",[me()],arguments);this.a.b=a};k.za=function(){return this.a.c};k.wa=function(a){T("setMaxOperationRetryTime",[me()],arguments);this.a.c=a};k.la=function(){return this.b}; -k.ka=function(){return this.c};var Re=function(a){this.a=a};Re.prototype.delete=function(){var a=this.a.a;a.f=!0;a.a=null;ae(a.h)};var Z=function(a,b,c){Object.defineProperty(a,b,{get:c})};X.prototype.toString=X.prototype.toString;X.prototype.child=X.prototype.fa;X.prototype.put=X.prototype.ra;X.prototype.putString=X.prototype.sa;X.prototype["delete"]=X.prototype.delete;X.prototype.getMetadata=X.prototype.ga;X.prototype.updateMetadata=X.prototype.ta;X.prototype.getDownloadURL=X.prototype.qa;Z(X.prototype,"parent",X.prototype.Da);Z(X.prototype,"root",X.prototype.Fa);Z(X.prototype,"bucket",X.prototype.ma); -Z(X.prototype,"fullPath",X.prototype.ya);Z(X.prototype,"name",X.prototype.Ca);Z(X.prototype,"storage",X.prototype.Ha);Y.prototype.ref=Y.prototype.ua;Y.prototype.refFromURL=Y.prototype.va;Z(Y.prototype,"maxOperationRetryTime",Y.prototype.za);Y.prototype.setMaxOperationRetryTime=Y.prototype.wa;Z(Y.prototype,"maxUploadRetryTime",Y.prototype.Aa);Y.prototype.setMaxUploadRetryTime=Y.prototype.xa;Z(Y.prototype,"app",Y.prototype.la);Z(Y.prototype,"INTERNAL",Y.prototype.ka);Re.prototype["delete"]=Re.prototype.delete; -Y.prototype.capi_=function(a){la=a};W.prototype.on=W.prototype.M;W.prototype.resume=W.prototype.R;W.prototype.pause=W.prototype.P;W.prototype.cancel=W.prototype.L;Z(W.prototype,"snapshot",W.prototype.D);Z(A.prototype,"bytesTransferred",A.prototype.na);Z(A.prototype,"totalBytes",A.prototype.Ja);Z(A.prototype,"state",A.prototype.Ga);Z(A.prototype,"metadata",A.prototype.Ba);Z(A.prototype,"downloadURL",A.prototype.pa);Z(A.prototype,"task",A.prototype.Ia);Z(A.prototype,"ref",A.prototype.Ea); +var ld=function(a,b){this.g=[];this.u=a;this.s=b||null;this.f=this.a=!1;this.b=void 0;this.l=this.o=this.i=!1;this.h=0;this.c=null;this.j=0}; +ld.prototype.cancel=function(a){if(this.a)this.b instanceof ld&&this.b.cancel();else{if(this.c){var b=this.c;delete this.c;a?b.cancel(a):(b.j--,0>=b.j&&b.cancel())}this.u?this.u.call(this.s,this):this.l=!0;if(!this.a){a=new md;if(this.a){if(!this.l)throw new nd;this.l=!1}B(!(a instanceof ld),"An execution sequence may not be initiated with a blocking Deferred.");this.a=!0;this.b=a;this.f=!0;od(this)}}};ld.prototype.m=function(a,b){this.i=!1;this.a=!0;this.b=b;this.f=!a;od(this)}; +var pd=function(a,b,c){B(!a.o,"Blocking Deferreds can not be re-used");a.g.push([b,c,void 0]);a.a&&od(a)};ld.prototype.then=function(a,b,c){var d,e,f=new G(function(a,b){d=a;e=b});pd(this,d,function(a){a instanceof md?f.cancel():e(a)});return f.then(a,b,c)};Ha(ld); +var qd=function(a){return rb(a.g,function(a){return t(a[1])})},od=function(a){if(a.h&&a.a&&qd(a)){var b=a.h,c=rd[b];c&&(l.clearTimeout(c.a),delete rd[b]);a.h=0}a.c&&(a.c.j--,delete a.c);for(var b=a.b,d=c=!1;a.g.length&&!a.i;){var e=a.g.shift(),f=e[0],g=e[1],e=e[2];if(f=a.f?g:f)try{var h=f.call(e||a.s,b);n(h)&&(a.f=a.f&&(h==b||h instanceof Error),a.b=b=h);if(Ia(b)||"function"===typeof l.Promise&&b instanceof l.Promise)d=!0,a.i=!0}catch(m){b=m,a.f=!0,qd(a)||(c=!0)}}a.b=b;d&&(h=u(a.m,a,!0),d=u(a.m,a, +!1),b instanceof ld?(pd(b,h,d),b.o=!0):b.then(h,d));c&&(b=new sd(b),rd[b.a]=b,a.h=b.a)},nd=function(){z.call(this)};v(nd,z);nd.prototype.message="Deferred has already fired";nd.prototype.name="AlreadyCalledError";var md=function(){z.call(this)};v(md,z);md.prototype.message="Deferred was canceled";md.prototype.name="CanceledError";var sd=function(a){this.a=l.setTimeout(u(this.c,this),0);this.b=a}; +sd.prototype.c=function(){B(rd[this.a],"Cannot throw an error that is not scheduled.");delete rd[this.a];throw this.b;};var rd={};var td=function(a){this.f=a;this.b=this.c=this.a=null},ud=function(a,b){this.name=a;this.value=b};ud.prototype.toString=function(){return this.name};var vd=new ud("SEVERE",1E3),wd=new ud("CONFIG",700),xd=new ud("FINE",500),yd=function(a){if(a.c)return a.c;if(a.a)return yd(a.a);db("Root logger has no level set.");return null}; +td.prototype.log=function(a,b,c){if(a.value>=yd(this).value)for(t(b)&&(b=b()),a=new Ba(a,String(b),this.f),c&&(a.a=c),c="log:"+a.b,l.console&&(l.console.timeStamp?l.console.timeStamp(c):l.console.markTimeline&&l.console.markTimeline(c)),l.msWriteProfilerMark&&l.msWriteProfilerMark(c),c=this;c;)c=c.a}; +var zd={},Ad=null,Bd=function(a){Ad||(Ad=new td(""),zd[""]=Ad,Ad.c=wd);var b;if(!(b=zd[a])){b=new td(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=Bd(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;zd[a]=b}return b};var Cd=function(){fb.call(this);this.b=new Ib(this);this.Y=this;this.G=null};v(Cd,fb);Cd.prototype[gb]=!0;Cd.prototype.removeEventListener=function(a,b,c,d){dd(this,a,b,c,d)}; +var I=function(a,b){Xc(a);var c,d=a.G;if(d){c=[];for(var e=1;d;d=d.G)c.push(d),B(1E3>++e,"infinite loop")}a=a.Y;d=b.type||b;r(b)?b=new Cb(b,a):b instanceof Cb?b.target=b.target||a:(e=b,b=new Cb(d,a),Ga(b,e));var e=!0,f;if(c)for(var g=c.length-1;0<=g;g--)f=b.a=c[g],e=Dd(f,d,!0,b)&&e;f=b.a=a;e=Dd(f,d,!0,b)&&e;e=Dd(f,d,!1,b)&&e;if(c)for(g=0;g=f)c=void 0;else{if(1==f)vb(e);else{e[0]=e.pop();for(var e=0,d=d.a,f=d.length,g=d[e];e>1;){var h=2*e+1,m=2*e+2,h=mg.a)break;d[e]=d[h];e=h}d[e]=g}c=c.b}c.apply(this,[b])}else break}}; +k.$=function(a){J.I.$.call(this,a);this.aa()};k.S=function(){J.I.S.call(this);this.aa()};k.D=function(){J.I.D.call(this);l.clearTimeout(void 0);vb(this.h.a);this.h=null};var K=function(a,b){a&&a.log(xd,b,void 0)};var Ed=function(a,b,c){if(t(a))c&&(a=u(a,c));else if(a&&"function"==typeof a.handleEvent)a=u(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647e,h=ub([408,429],e),g=ub(g.o,e),f=f||h||g;f?(e=7===b.K,jd(b),a(!1,new Xd(!1,null,e))):(e=ub(d.G,e),a(!0,new Xd(e,b)))})})}function c(a,b){var c=d.l;a=d.j;var e=b.c;if(b.b)try{var f=d.s(e,Sd(e));n(f)?c(f):c()}catch(q){a(q)}else null!==e?(b=ma(),f=Sd(e),b.serverResponse=f,d.i?a(d.i(e,b)):a(b)):(b=b.a?d.g?qa(): +na():new w("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),a(b));jd(e)}var d=a;a.h?c(0,new Xd(!1,null,!0)):a.c=ka(b,c,a.F)};Wd.prototype.a=function(){return this.B};Wd.prototype.cancel=function(a){this.h=!0;this.g=a||!1;null!==this.c&&(0,this.c)(!1);null!==this.b&&this.b.abort()}; +var Yd=function(a,b,c){var d=ab(a.b),d=a.j+d,e=a.headers?ta(a.headers):{};null!==b&&0b&&(b+=a.size),0>b&&(b=0),0>c&&(c+=a.size),cb.length?b:Hb(b)};a.push(b);b=new S("size");b.a=function(a,b){return y(b)?+b:b};a.push(b);a.push(new S("timeCreated"));a.push(new S("updated"));a.push(new S("md5Hash",null,!0)); +a.push(new S("cacheControl",null,!0));a.push(new S("contentDisposition",null,!0));a.push(new S("contentEncoding",null,!0));a.push(new S("contentLanguage",null,!0));a.push(new S("contentType",null,!0));a.push(new S("metadata","customMetadata",!0));a.push(new S("downloadTokens","downloadURLs",!1,function(a,b){if(!(xa(b)&&0m;m++)h+=Math.random().toString().slice(2);g["Content-Type"]="multipart/related; boundary="+h;e=ze(b,d,e);m=le(e,c);d=ae("--"+h+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+ +m+"\r\n--"+h+"\r\nContent-Type: "+e.contentType+"\r\n\r\n",d,"\r\n--"+h+"--");if(null===d)throw oa();a=new x(la+"/v0"+f,"POST",ue(a,c),a.b);a.b={name:e.fullPath};a.headers=g;a.body=d.v;a.a=ve(b);return a},Be=function(a,b,c,d){this.a=a;this.total=b;this.b=!!c;this.c=d||null},Ce=function(a,b){var c;try{c=Td(a,"X-Goog-Upload-Status")}catch(d){te(!1)}te(ub(b||["active"],c));return c},De=function(a,b,c,d,e){var f="/b/"+encodeURIComponent(b.bucket)+"/o",g=ze(b,d,e);e={name:g.fullPath};f=la+"/v0"+f;d={"X-Goog-Upload-Protocol":"resumable", +"X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":d.a,"X-Goog-Upload-Header-Content-Type":g.contentType,"Content-Type":"application/json; charset=utf-8"};c=le(g,c);a=new x(f,"POST",function(a){Ce(a);var b;try{b=Td(a,"X-Goog-Upload-URL")}catch(q){te(!1)}te(xa(b));return b},a.b);a.b=e;a.headers=d;a.body=c;a.a=ve(b);return a},Ee=function(a,b,c,d){a=new x(c,"POST",function(a){var b=Ce(a,["active","final"]),c;try{c=Td(a,"X-Goog-Upload-Size-Received")}catch(h){te(!1)}a=c;isFinite(a)&& +(a=String(a));a=r(a)?/^\s*-?0x/i.test(a)?parseInt(a,16):parseInt(a,10):NaN;te(!isNaN(a));return new Be(a,d.a,"final"===b)},a.b);a.headers={"X-Goog-Upload-Command":"query"};a.a=ve(b);a.g=!1;return a},Fe=function(a,b,c,d,e,f,g){var h=new Be(0,0);g?(h.a=g.a,h.total=g.total):(h.a=0,h.total=d.a);if(d.a!==h.total)throw new w("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var m=g=h.total-h.a;0262144*a.i&&(a.i*=2);a.a=null;Oe(a,b.a);b.b?(a.h=b.c,V(a,"success")):Ge(a)},a.V)})},Ke=function(a){Ne(a,function(b){var c=xe(a.c,a.j,a.m);a.a=R(a.c,c,b);a.a.a().then(function(b){a.a=null;a.h=b;V(a,"success")},a.Y)})},Me=function(a){Ne(a,function(b){var c=Ae(a.c,a.j,a.m,a.f,a.h);a.a= +R(a.c,c,b);a.a.a().then(function(b){a.a=null;a.h=b;Oe(a,a.f.a);V(a,"success")},a.V)})},Oe=function(a,b){var c=a.l;a.l=b;a.l>c&&Pe(a)},V=function(a,b){if(a.b!==b)switch(b){case "canceling":a.b=b;null!==a.a&&a.a.cancel();break;case "pausing":a.b=b;null!==a.a&&a.a.cancel();break;case "running":var c="paused"===a.b;a.b=b;c&&(Pe(a),He(a));break;case "paused":a.b=b;Pe(a);break;case "canceled":a.g=na();a.b=b;Pe(a);break;case "error":a.b=b;Pe(a);break;case "success":a.b=b,Pe(a)}},Ge=function(a){switch(a.b){case "pausing":V(a, +"paused");break;case "canceling":V(a,"canceled");break;case "running":He(a)}};W.prototype.C=function(){return new A(this.l,this.f.a,wa(this.b),this.h,this,this.L)}; +W.prototype.O=function(a,b,c,d){function e(a){try{g(a);return}catch(P){}try{if(h(a),!(n(a.next)||n(a.error)||n(a.complete)))throw"";}catch(P){throw"Expected a function or an Object with one of `next`, `error`, `complete` properties.";}}function f(a){return function(b,c,d){null!==a&&T("on",a,arguments);var e=new Ta(b,c,d);Qe(m,e);return function(){wb(m.F,e)}}}var g=se().a,h=re(null,!0).a;T("on",[oe(function(){if("state_changed"!==a)throw"Expected one of the event types: [state_changed].";}),re(e,!0), +se(),se()],arguments);var m=this,q=[re(function(a){if(null===a)throw"Expected a function or an Object with one of `next`, `error`, `complete` properties.";e(a)}),se(),se()];return n(b)||n(c)||n(d)?f(null)(b,c,d):f(q)};W.prototype.then=function(a,b){return this.G.then(a,b)}; +var Qe=function(a,b){a.F.push(b);Re(a,b)},Pe=function(a){Se(a);var b=xb(a.F);ob(b,function(b){Re(a,b)})},Se=function(a){if(null!==a.o){var b=!0;switch(wa(a.b)){case "success":Rc(a.o.bind(null,a.C()))();break;case "canceled":case "error":Rc(a.B.bind(null,a.g))();break;default:b=!1}b&&(a.o=null,a.B=null)}},Re=function(a,b){switch(wa(a.b)){case "running":case "paused":null!==b.next&&Rc(b.next.bind(b,a.C()))();break;case "success":null!==b.b&&Rc(b.b.bind(b))();break;case "canceled":case "error":null!== +b.a&&Rc(b.a.bind(b,a.g))();break;default:null!==b.a&&Rc(b.a.bind(b,a.g))()}};W.prototype.R=function(){T("resume",[],arguments);var a="paused"===this.b||"pausing"===this.b;a&&V(this,"running");return a};W.prototype.P=function(){T("pause",[],arguments);var a="running"===this.b;a&&V(this,"pausing");return a};W.prototype.cancel=function(){T("cancel",[],arguments);var a="running"===this.b||"pausing"===this.b;a&&V(this,"canceling");return a};var X=function(a,b){this.b=a;if(b)this.a=b instanceof Qa?b:Sa(b);else if(a=a.bucket(),null!==a)this.a=new Qa(a,"");else throw new w("no-default-bucket","No default bucket found. Did you set the 'storageBucket' property when initializing the app?");};X.prototype.toString=function(){T("toString",[],arguments);return"gs://"+this.a.bucket+"/"+this.a.path};var Te=function(a,b){return new X(a,b)};k=X.prototype; +k.fa=function(a){T("child",[oe()],arguments);var b=Gb(this.a.path,a);return Te(this.b,new Qa(this.a.bucket,b))};k.Da=function(){var a;a=this.a.path;if(0==a.length)a=null;else{var b=a.lastIndexOf("/");a=-1===b?"":a.slice(0,b)}return null===a?null:Te(this.b,new Qa(this.a.bucket,a))};k.Fa=function(){return Te(this.b,new Qa(this.a.bucket,""))};k.ma=function(){return this.a.bucket};k.ya=function(){return this.a.path};k.Ca=function(){return Hb(this.a.path)};k.Ha=function(){return this.b.i}; +k.ra=function(a,b){T("put",[pe(),new U(me,!0)],arguments);Ue(this,"put");return new W(this,this.b,this.a,je(),new O(a),b)};k.sa=function(a,b,c){T("putString",[oe(),oe(Va,!0),new U(me,!0)],arguments);Ue(this,"putString");var d=$a(y(b)?b:"raw",a),e=c?ta(c):{};!y(e.contentType)&&y(d.a)&&(e.contentType=d.a);return new W(this,this.b,this.a,je(),new O(d.data,!0),e)}; +k.delete=function(){T("delete",[],arguments);Ue(this,"delete");var a=this;return ge(this.b).then(function(b){var c=ye(a.b,a.a);return R(a.b,c,b).a()})};k.ga=function(){T("getMetadata",[],arguments);Ue(this,"getMetadata");var a=this;return ge(this.b).then(function(b){var c=xe(a.b,a.a,je());return R(a.b,c,b).a()})}; +k.ta=function(a){T("updateMetadata",[new U(me,void 0)],arguments);Ue(this,"updateMetadata");var b=this;return ge(this.b).then(function(c){var d=b.b,e=b.a,f=a,g=je(),h=Ra(e),h=la+"/v0"+h,f=le(f,g),d=new x(h,"PATCH",ue(d,g),d.c);d.headers={"Content-Type":"application/json; charset=utf-8"};d.body=f;d.a=we(e);return R(b.b,d,c).a()})}; +k.qa=function(){T("getDownloadURL",[],arguments);Ue(this,"getDownloadURL");return this.ga().then(function(a){a=a.downloadURLs[0];if(y(a))return a;throw new w("no-download-url","The given file does not have any download URLs.");})};var Ue=function(a,b){if(""===a.a.path)throw new w("invalid-root-operation","The operation '"+b+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').");};var Y=function(a){this.a=new fe(a,function(a,c){return new X(a,c)},Yd,this);this.b=a;this.c=new Ve(this)};k=Y.prototype;k.ua=function(a){T("ref",[oe(function(a){if(/^[A-Za-z]+:\/\//.test(a))throw"Expected child path but got a URL, use refFromURL instead.";},!0)],arguments);var b=new X(this.a);return n(a)?b.fa(a):b}; +k.va=function(a){T("refFromURL",[oe(function(a){if(!/^[A-Za-z]+:\/\//.test(a))throw"Expected full URL but got a child path, use ref instead.";try{Sa(a)}catch(c){throw"Expected valid full URL but got an invalid one.";}},!1)],arguments);return new X(this.a,a)};k.Aa=function(){return this.a.b};k.xa=function(a){T("setMaxUploadRetryTime",[qe()],arguments);this.a.b=a};k.za=function(){return this.a.c};k.wa=function(a){T("setMaxOperationRetryTime",[qe()],arguments);this.a.c=a};k.la=function(){return this.b}; +k.ka=function(){return this.c};var Ve=function(a){this.a=a};Ve.prototype.delete=function(){var a=this.a.a;a.f=!0;a.a=null;ee(a.h)};var Z=function(a,b,c){Object.defineProperty(a,b,{get:c})};X.prototype.toString=X.prototype.toString;X.prototype.child=X.prototype.fa;X.prototype.put=X.prototype.ra;X.prototype.putString=X.prototype.sa;X.prototype["delete"]=X.prototype.delete;X.prototype.getMetadata=X.prototype.ga;X.prototype.updateMetadata=X.prototype.ta;X.prototype.getDownloadURL=X.prototype.qa;Z(X.prototype,"parent",X.prototype.Da);Z(X.prototype,"root",X.prototype.Fa);Z(X.prototype,"bucket",X.prototype.ma); +Z(X.prototype,"fullPath",X.prototype.ya);Z(X.prototype,"name",X.prototype.Ca);Z(X.prototype,"storage",X.prototype.Ha);Y.prototype.ref=Y.prototype.ua;Y.prototype.refFromURL=Y.prototype.va;Z(Y.prototype,"maxOperationRetryTime",Y.prototype.za);Y.prototype.setMaxOperationRetryTime=Y.prototype.wa;Z(Y.prototype,"maxUploadRetryTime",Y.prototype.Aa);Y.prototype.setMaxUploadRetryTime=Y.prototype.xa;Z(Y.prototype,"app",Y.prototype.la);Z(Y.prototype,"INTERNAL",Y.prototype.ka);Ve.prototype["delete"]=Ve.prototype.delete; +Y.prototype.capi_=function(a){la=a};W.prototype.on=W.prototype.O;W.prototype.resume=W.prototype.R;W.prototype.pause=W.prototype.P;W.prototype.cancel=W.prototype.cancel;Z(W.prototype,"snapshot",W.prototype.C);Z(A.prototype,"bytesTransferred",A.prototype.na);Z(A.prototype,"totalBytes",A.prototype.Ja);Z(A.prototype,"state",A.prototype.Ga);Z(A.prototype,"metadata",A.prototype.Ba);Z(A.prototype,"downloadURL",A.prototype.pa);Z(A.prototype,"task",A.prototype.Ia);Z(A.prototype,"ref",A.prototype.Ea); ua.STATE_CHANGED="state_changed";va.RUNNING="running";va.PAUSED="paused";va.SUCCESS="success";va.CANCELED="canceled";va.ERROR="error";Ua.RAW="raw";Ua.BASE64="base64";Ua.BASE64URL="base64url";Ua.DATA_URL="data_url";G.prototype["catch"]=G.prototype.l;G.prototype.then=G.prototype.then; (function(){function a(a){return new Y(a)}var b={TaskState:va,TaskEvent:ua,StringFormat:Ua,Storage:Y,Reference:X};if("undefined"!==typeof firebase)firebase.INTERNAL.registerService("storage",a,b);else throw Error("Cannot install Firebase Storage - be sure to load firebase-app.js first.");})();})(); diff --git a/lib/google-analytics/.bower.json b/lib/google-analytics/.bower.json index b396f0db..4023e583 100644 --- a/lib/google-analytics/.bower.json +++ b/lib/google-analytics/.bower.json @@ -1,13 +1,13 @@ { "name": "google-analytics", - "version": "1.2.2", + "version": "1.2.3", "description": "Encapsulates Google Analytics dashboard features into web components", "homepage": "https://googlewebcomponents.github.io/google-analytics", "authors": [ "Philip Walton " ], "main": "google-analytics.html", - "license": "Apache2", + "license": "Apache-2.0", "keywords": [ "google", "analytics", @@ -30,11 +30,11 @@ "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.2" }, - "_release": "1.2.2", + "_release": "1.2.3", "_resolution": { "type": "version", - "tag": "v1.2.2", - "commit": "2e471d658c3a535c76fa7ec7a2c23ae5bbd1865c" + "tag": "v1.2.3", + "commit": "0e04845b7da3524f929b4322ff3f16bb171c0c64" }, "_source": "git://github.com/GoogleWebComponents/google-analytics.git", "_target": "^1.0.0", diff --git a/lib/google-analytics/bower.json b/lib/google-analytics/bower.json index 4447cca3..491a6622 100644 --- a/lib/google-analytics/bower.json +++ b/lib/google-analytics/bower.json @@ -1,13 +1,13 @@ { "name": "google-analytics", - "version": "1.2.2", + "version": "1.2.3", "description": "Encapsulates Google Analytics dashboard features into web components", "homepage": "https://googlewebcomponents.github.io/google-analytics", "authors": [ "Philip Walton " ], "main": "google-analytics.html", - "license": "Apache2", + "license": "Apache-2.0", "keywords": [ "google", "analytics", diff --git a/lib/google-apis/.bower.json b/lib/google-apis/.bower.json index 0c7e5aba..0bcb76c2 100644 --- a/lib/google-apis/.bower.json +++ b/lib/google-apis/.bower.json @@ -1,6 +1,6 @@ { "name": "google-apis", - "version": "1.1.6", + "version": "1.1.7", "description": "Web components to load Google API libraries", "homepage": "https://elements.polymer-project.org/elements/google-apis?active=google-js-api", "main": "google-apis.html", @@ -8,7 +8,7 @@ "Scott Miles ", "Eric Bidelman " ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -27,11 +27,11 @@ "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0" }, - "_release": "1.1.6", + "_release": "1.1.7", "_resolution": { "type": "version", - "tag": "1.1.6", - "commit": "cc61087168d492d03865c57caae0935fb8d2e70b" + "tag": "v1.1.7", + "commit": "f49556ed82feab560202c9d13c1a7f0a77c80171" }, "_source": "git://github.com/GoogleWebComponents/google-apis.git", "_target": "^1.0.0", diff --git a/lib/google-apis/bower.json b/lib/google-apis/bower.json index 9edeb0ea..01535a9d 100644 --- a/lib/google-apis/bower.json +++ b/lib/google-apis/bower.json @@ -1,6 +1,6 @@ { "name": "google-apis", - "version": "1.1.6", + "version": "1.1.7", "description": "Web components to load Google API libraries", "homepage": "https://elements.polymer-project.org/elements/google-apis?active=google-js-api", "main": "google-apis.html", @@ -8,7 +8,7 @@ "Scott Miles ", "Eric Bidelman " ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-calendar/.bower.json b/lib/google-calendar/.bower.json index 5e45b898..5e314d29 100644 --- a/lib/google-calendar/.bower.json +++ b/lib/google-calendar/.bower.json @@ -1,13 +1,13 @@ { "name": "google-calendar", - "version": "1.0.2", + "version": "1.0.3", "homepage": "https://googlewebcomponents.github.io/google-calendar", "description": "Web components for working with Google Calendar", "main": "google-calendar.html", "authors": [ "Ewa Gasperowicz" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -28,11 +28,11 @@ "web-component-tester": "*", "iron-component-page": "PolymerElements/iron-component-page#^1.0.0" }, - "_release": "1.0.2", + "_release": "1.0.3", "_resolution": { "type": "version", - "tag": "1.0.2", - "commit": "52e322be137e9ac40ee8641f4226a13524b430e4" + "tag": "v1.0.3", + "commit": "0941df98f94923e5285ab86409f2c2733bd2db1a" }, "_source": "git://github.com/GoogleWebComponents/google-calendar.git", "_target": "^1.0.0", diff --git a/lib/google-calendar/bower.json b/lib/google-calendar/bower.json index 2f29e775..beb654d3 100644 --- a/lib/google-calendar/bower.json +++ b/lib/google-calendar/bower.json @@ -1,13 +1,13 @@ { "name": "google-calendar", - "version": "1.0.2", + "version": "1.0.3", "homepage": "https://googlewebcomponents.github.io/google-calendar", "description": "Web components for working with Google Calendar", "main": "google-calendar.html", "authors": [ "Ewa Gasperowicz" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-castable-video/.bower.json b/lib/google-castable-video/.bower.json index eac3a6d7..aed30128 100644 --- a/lib/google-castable-video/.bower.json +++ b/lib/google-castable-video/.bower.json @@ -1,6 +1,6 @@ { "name": "google-castable-video", - "version": "1.0.2", + "version": "1.0.3", "authors": [ "Thorsten Schaeff " ], @@ -12,7 +12,7 @@ "web-components" ], "main": "google-castable-video.html", - "license": "Apache-2", + "license": "Apache-2.0", "homepage": "https://github.com/GoogleWebComponents/google-castable-video", "ignore": [ "/.*", @@ -24,11 +24,11 @@ "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0" }, - "_release": "1.0.2", + "_release": "1.0.3", "_resolution": { "type": "version", - "tag": "v1.0.2", - "commit": "607f70287b99c3e1d113fc944dab1424172fa360" + "tag": "v1.0.3", + "commit": "9c9e254ee82411f2149bc553547bf42fadf20324" }, "_source": "git://github.com/GoogleWebComponents/google-castable-video.git", "_target": "^1.0.0", diff --git a/lib/google-castable-video/bower.json b/lib/google-castable-video/bower.json index ff754d88..fa023dc2 100644 --- a/lib/google-castable-video/bower.json +++ b/lib/google-castable-video/bower.json @@ -1,6 +1,6 @@ { "name": "google-castable-video", - "version": "1.0.2", + "version": "1.0.3", "authors": [ "Thorsten Schaeff " ], @@ -12,7 +12,7 @@ "web-components" ], "main": "google-castable-video.html", - "license": "Apache-2", + "license": "Apache-2.0", "homepage": "https://github.com/GoogleWebComponents/google-castable-video", "ignore": [ "/.*", diff --git a/lib/google-chart/.bower.json b/lib/google-chart/.bower.json index bc8ce2c4..5f2d5afd 100644 --- a/lib/google-chart/.bower.json +++ b/lib/google-chart/.bower.json @@ -1,6 +1,6 @@ { "name": "google-chart", - "version": "1.1.0", + "version": "1.1.1", "description": "Encapsulates Google Charts into a web component", "homepage": "https://googlewebcomponents.github.io/google-chart", "main": "google-chart.html", @@ -8,7 +8,7 @@ "Wes Alvaro", "Sérgio Gomes" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -32,11 +32,11 @@ "iron-component-page": "PolymerElements/iron-component-page#^1.0.2", "web-component-tester": "*" }, - "_release": "1.1.0", + "_release": "1.1.1", "_resolution": { "type": "version", - "tag": "v1.1.0", - "commit": "7e906acd99619e33e0cd78182c97fe6d9ad494fd" + "tag": "v1.1.1", + "commit": "4cfcf1cf4a97fd8296f66d416371b219cd725d79" }, "_source": "git://github.com/GoogleWebComponents/google-chart.git", "_target": "^1.0.0", diff --git a/lib/google-chart/README.md b/lib/google-chart/README.md index ecf9dc61..a5825788 100644 --- a/lib/google-chart/README.md +++ b/lib/google-chart/README.md @@ -4,3 +4,5 @@ google-chart [Google Charts API](https://developers.google.com/chart/) web components. See https://elements.polymer-project.org/elements/google-chart + +[![Build Status](https://travis-ci.org/GoogleWebComponents/google-chart.svg?branch=master)](https://travis-ci.org/GoogleWebComponents/google-chart) diff --git a/lib/google-chart/bower.json b/lib/google-chart/bower.json index 59b25f2f..ca3ad9f0 100644 --- a/lib/google-chart/bower.json +++ b/lib/google-chart/bower.json @@ -1,6 +1,6 @@ { "name": "google-chart", - "version": "1.1.0", + "version": "1.1.1", "description": "Encapsulates Google Charts into a web component", "homepage": "https://googlewebcomponents.github.io/google-chart", "main": "google-chart.html", @@ -8,7 +8,7 @@ "Wes Alvaro", "Sérgio Gomes" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-chart/demo/index.html b/lib/google-chart/demo/index.html index 6d6b74c6..d61b5b6f 100644 --- a/lib/google-chart/demo/index.html +++ b/lib/google-chart/demo/index.html @@ -142,6 +142,49 @@ }()); +

Here's a pie chart listening for `onmouseover`:

+ + +
+ + +
+ Moused over row: None. +
+
+ + +

Here's a chart defined using data, rather than rows and cols:

Chart gallery rows='[["Jan", 31],["Feb", 28],["Mar", 31],["Apr", 30],["May", 31],["Jun", 30]]'> +

Here's a material line chart:

+ + + + +

Here's a organization chart:

+ + + +

Here's a pie chart:

Chart gallery [68, 15]]'> +

Here's a material scatter chart:

+ + + +

Here's a stepped area chart:

- + diff --git a/lib/google-chart/google-chart.html b/lib/google-chart/google-chart.html index db37e2d2..654b285a 100644 --- a/lib/google-chart/google-chart.html +++ b/lib/google-chart/google-chart.html @@ -13,7 +13,7 @@ options='{"title": "Distribution of days in 2001Q1"}' cols='[{"label":"Month", "type":"string"}, {"label":"Days", "type":"number"}]' rows='[["Jan", 31],["Feb", 28],["Mar", 31]]'> - j + Note: if you're passing JSON as attributes, single quotes are necessary to be valid JSON. See https://www.polymer-project.org/1.0/docs/devguide/properties#configuring-object-and-array-properties. @@ -48,6 +48,12 @@ - Via the `view` attribute, passing in a Google DataView object: view='{{dataView}}' + +You can display the charts in locales other than "en" by setting the `lang` attribute +on the `html` tag of your document. + + + @demo --> @@ -100,6 +106,24 @@ observer: '_typeChanged' }, + /** + * Enumerates the chart events that should be fired. + * + * Charts support a variety of events. By default, this element only + * fires on `ready` and `select`. If you would like to be notified of + * other chart events, use this property to list them. + * Events `ready` and `select` are always fired. + * Changes to this property are _not_ observed. Events are attached only + * at chart construction time. + * + * @attribute events + * @type !Array + */ + events: { + type: Array, + value: function() { return []; } + }, + /** * Sets the options for the chart. * @@ -113,12 +137,16 @@ * See Google Visualization API reference (Chart Gallery) * for the options available to each chart type. * + * This property is observed via a deep object observer. + * If you would like to make changes to a sub-property, be sure to use the + * Polymer method `set`: `googleChart.set('options.vAxis.logScale', true)` + * (Note: Missing parent properties are not automatically created.) + * * @attribute options * @type {!Object|undefined} */ options: { - type: Object, - observer: 'redraw' + type: Object }, /** @@ -242,7 +270,10 @@ }, }, - observers: ['_draw(_chart, _dataView)'], + observers: [ + '_draw(_chart, _dataView)', + '_subOptionChanged(options.*)' + ], listeners: { 'google-chart-select': '_updateSelection', @@ -261,13 +292,28 @@ _typeChanged: function() { this.$.loader.create(this.type, this.$.chartdiv) .then(function(chart) { - this.$.loader.fireOnChartEvent(chart, 'select'); - this.$.loader.fireOnChartEvent(chart, 'ready'); + var loader = this.$.loader; + Object.keys(this.events.concat(['select', 'ready']) + .reduce(function(set, eventName) { + set[eventName] = true; + return set; + }, {})) + .forEach(function(eventName) { + loader.fireOnChartEvent(chart, eventName); + }); this._setDrawn(false); this._chart = chart; }.bind(this)); }, + _subOptionChanged: function(optionChangeDetails) { + this.options = optionChangeDetails.base; + // Debounce to allow for multiple option changes in one redraw + this.debounce('optionChangeRedraw', function() { + this.redraw(); + }, 5); + }, + _setSelection: function() { // Note: Some charts (e.g. TreeMap) must have a selection. if (!this.drawn || !this.selection || this.selection === this._selection) { diff --git a/lib/google-hangout-button/.bower.json b/lib/google-hangout-button/.bower.json index 1a81002c..86ce57b8 100644 --- a/lib/google-hangout-button/.bower.json +++ b/lib/google-hangout-button/.bower.json @@ -1,13 +1,13 @@ { "name": "google-hangout-button", - "version": "1.0.1", + "version": "1.0.2", "homepage": "http://googlewebcomponents.github.io/google-hangout-button", "description": "Google Hangout button web component", "main": "google-hangout-button.html", "authors": [ "Ewa Gasperowicz" ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -29,11 +29,11 @@ "iron-component-page": "PolymerElements/iron-component-page#^1.0.2", "sinon-browser-only": "~1.12.1" }, - "_release": "1.0.1", + "_release": "1.0.2", "_resolution": { "type": "version", - "tag": "v1.0.1", - "commit": "bead2dc203b4b6ddcf90c9dba3b72486113b7c66" + "tag": "v1.0.2", + "commit": "02af5aa4c8a3a51ff363faa9d4c3cb2b38f3d077" }, "_source": "git://github.com/GoogleWebComponents/google-hangout-button.git", "_target": "^1.0.0", diff --git a/lib/google-hangout-button/README.md b/lib/google-hangout-button/README.md index c2fcc2fd..22eaf45a 100644 --- a/lib/google-hangout-button/README.md +++ b/lib/google-hangout-button/README.md @@ -1,5 +1,5 @@ google-hangout-button ===================== -See the [component landing page](http://googlewebcomponents.github.io/google-hangout-button) for more information. +See https://elements.polymer-project.org/elements/google-hangout-button diff --git a/lib/google-hangout-button/bower.json b/lib/google-hangout-button/bower.json index b0067f1f..a9ab0700 100644 --- a/lib/google-hangout-button/bower.json +++ b/lib/google-hangout-button/bower.json @@ -1,13 +1,13 @@ { "name": "google-hangout-button", - "version": "1.0.1", + "version": "1.0.2", "homepage": "http://googlewebcomponents.github.io/google-hangout-button", "description": "Google Hangout button web component", "main": "google-hangout-button.html", "authors": [ "Ewa Gasperowicz" ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-map/.bower.json b/lib/google-map/.bower.json index 93b6b87d..63b64d31 100644 --- a/lib/google-map/.bower.json +++ b/lib/google-map/.bower.json @@ -1,6 +1,6 @@ { "name": "google-map", - "version": "1.1.11", + "version": "1.1.13", "description": "Google Maps web components", "homepage": "https://elements.polymer-project.org/elements/google-map", "main": [ @@ -14,7 +14,7 @@ "Scott Miles ", "Eric Bidelman " ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -37,11 +37,11 @@ "web-component-tester": "*", "iron-component-page": "PolymerElements/iron-component-page#^1.0.2" }, - "_release": "1.1.11", + "_release": "1.1.13", "_resolution": { "type": "version", - "tag": "1.1.11", - "commit": "54940112d458239d7fa2caf86aecb33f60a16a48" + "tag": "v1.1.13", + "commit": "5ba72b10ea02db401dc42b3ad17a22b93a58c745" }, "_source": "git://github.com/GoogleWebComponents/google-map.git", "_target": "^1.0.0", diff --git a/lib/google-map/bower.json b/lib/google-map/bower.json index 56f368d0..9ef21f05 100644 --- a/lib/google-map/bower.json +++ b/lib/google-map/bower.json @@ -1,6 +1,6 @@ { "name": "google-map", - "version": "1.1.11", + "version": "1.1.13", "description": "Google Maps web components", "homepage": "https://elements.polymer-project.org/elements/google-map", "main": [ @@ -14,7 +14,7 @@ "Scott Miles ", "Eric Bidelman " ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-map/demo/index.html b/lib/google-map/demo/index.html index 9000012e..6142f760 100644 --- a/lib/google-map/demo/index.html +++ b/lib/google-map/demo/index.html @@ -23,26 +23,36 @@ - - - - - - - - - - + diff --git a/lib/google-map/demo/kml.html b/lib/google-map/demo/kml.html index fe0ffa3a..7e4aeae8 100644 --- a/lib/google-map/demo/kml.html +++ b/lib/google-map/demo/kml.html @@ -21,7 +21,15 @@ - + + diff --git a/lib/google-map/demo/polys.html b/lib/google-map/demo/polys.html index 95568c79..50bf9f36 100644 --- a/lib/google-map/demo/polys.html +++ b/lib/google-map/demo/polys.html @@ -21,13 +21,16 @@ - - - - - - - + @@ -39,6 +42,11 @@ poly.editable = !poly.editable; button.innerText = poly.editable ? 'Disable editing' : 'Enable editing'; } + + if (location.origin === 'https://custom-elements.appspot.com') { + var t = document.querySelector('template'); + t.apiKey = 'AIzaSyD_bfL1kCUIsD0dZ4XxWAO_0W6NstEQ5Pg'; // TODO: update to your own API Key! + } diff --git a/lib/google-map/google-map.html b/lib/google-map/google-map.html index 2afd6364..0c25f091 100644 --- a/lib/google-map/google-map.html +++ b/lib/google-map/google-map.html @@ -274,6 +274,15 @@ observer: '_disableMapTypeControlChanged' }, + /** + * If set, removes the map's 'street view' UI controls. + */ + disableStreetViewControl: { + type: Boolean, + value: false, + observer: '_disableStreetViewControlChanged' + }, + /** * If set, the zoom level is set such that all markers (google-map-marker children) are brought into view. */ @@ -466,6 +475,7 @@ mapTypeId: this.mapType, disableDefaultUI: this.disableDefaultUi, mapTypeControl: !this.disableDefaultUi && !this.disableMapTypeControl, + streetViewControl: !this.disableDefaultUi && !this.disableStreetViewControl, disableDoubleClickZoom: this.disableZoom, scrollwheel: !this.disableZoom, styles: this.styles, @@ -725,7 +735,14 @@ if (!this.map) { return; } - this.map.setOptions({disableMapTypeControl: this.disableMapTypeControl}); + this.map.setOptions({mapTypeControl: !this.disableMapTypeControl}); + }, + + _disableStreetViewControlChanged: function() { + if (!this.map) { + return; + } + this.map.setOptions({streetViewControl: !this.disableStreetViewControl}); }, _disableZoomChanged: function() { diff --git a/lib/google-sheets/.bower.json b/lib/google-sheets/.bower.json index b1197ab7..d8ddbe30 100644 --- a/lib/google-sheets/.bower.json +++ b/lib/google-sheets/.bower.json @@ -1,13 +1,13 @@ { "name": "google-sheets", - "version": "1.0.5", + "version": "1.0.6", "homepage": "https://googlewebcomponents.github.io/google-sheets", "description": "Web components to interact with Google Sheets", "main": "google-sheets.html", "authors": [ "Eric Bidelman " ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -31,11 +31,11 @@ "iron-flex-layout": "PolymerElements/iron-flex-layout#^1.0.0", "web-component-tester": "*" }, - "_release": "1.0.5", + "_release": "1.0.6", "_resolution": { "type": "version", - "tag": "1.0.5", - "commit": "1e87081a4abfdd31cf7cbf4ac970c7f9873c447d" + "tag": "v1.0.6", + "commit": "b261dc69326f1c6a21a38a24137bd6d1eb480f95" }, "_source": "git://github.com/GoogleWebComponents/google-sheets.git", "_target": "^1.0.1", diff --git a/lib/google-sheets/README.md b/lib/google-sheets/README.md index 119acf43..d9a3750a 100644 --- a/lib/google-sheets/README.md +++ b/lib/google-sheets/README.md @@ -1,4 +1,4 @@ google-sheets ================ -See the [component page](https://googlewebcomponents.github.io/google-sheets) for more information. +See https://elements.polymer-project.org/elements/google-sheets diff --git a/lib/google-sheets/bower.json b/lib/google-sheets/bower.json index 1b1428c0..111b4f0a 100644 --- a/lib/google-sheets/bower.json +++ b/lib/google-sheets/bower.json @@ -1,13 +1,13 @@ { "name": "google-sheets", - "version": "1.0.5", + "version": "1.0.6", "homepage": "https://googlewebcomponents.github.io/google-sheets", "description": "Web components to interact with Google Sheets", "main": "google-sheets.html", "authors": [ "Eric Bidelman " ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-signin/.bower.json b/lib/google-signin/.bower.json index 0397a8cd..2f1995b9 100644 --- a/lib/google-signin/.bower.json +++ b/lib/google-signin/.bower.json @@ -1,6 +1,6 @@ { "name": "google-signin", - "version": "1.3.6", + "version": "1.3.7", "description": "Web components to authenticate with Google services", "homepage": "https://googlewebcomponents.github.io/google-signin", "main": "google-signin.html", @@ -8,7 +8,7 @@ "Addy Osmani", "Randy Merrill" ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" @@ -34,11 +34,11 @@ "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.2" }, - "_release": "1.3.6", + "_release": "1.3.7", "_resolution": { "type": "version", - "tag": "1.3.6", - "commit": "b060161a877553f8a96854752b6ed4c814f29355" + "tag": "v1.3.7", + "commit": "b9132e0bc1f8d810634b6d5ffcd7b08243e8af9b" }, "_source": "git://github.com/GoogleWebComponents/google-signin.git", "_target": "^1.0.0", diff --git a/lib/google-signin/bower.json b/lib/google-signin/bower.json index d0833270..59c97ce6 100644 --- a/lib/google-signin/bower.json +++ b/lib/google-signin/bower.json @@ -1,6 +1,6 @@ { "name": "google-signin", - "version": "1.3.6", + "version": "1.3.7", "description": "Web components to authenticate with Google services", "homepage": "https://googlewebcomponents.github.io/google-signin", "main": "google-signin.html", @@ -8,7 +8,7 @@ "Addy Osmani", "Randy Merrill" ], - "license": "Apache-2", + "license": "Apache-2.0", "ignore": [ "/.*", "/test/" diff --git a/lib/google-streetview-pano/.bower.json b/lib/google-streetview-pano/.bower.json index 37f7148b..128af1a8 100644 --- a/lib/google-streetview-pano/.bower.json +++ b/lib/google-streetview-pano/.bower.json @@ -1,13 +1,13 @@ { "name": "google-streetview-pano", - "version": "1.0.3", + "version": "1.0.4", "homepage": "https://elements.polymer-project.org/elements/google-streetview-pano", "description": "Google Maps street view web component", "main": "google-streetview-pano.html", "authors": [ "Rob Dodson" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "bower_components", "test", @@ -23,17 +23,18 @@ "google" ], "dependencies": { - "polymer": "Polymer/polymer#^1.1.4", - "google-apis": "GoogleWebComponents/google-apis#^1.1.1" + "google-apis": "GoogleWebComponents/google-apis#^1.1.1", + "iron-resizable-behavior": "PolymerElements/iron-resizable-behavior#~1.0.2", + "polymer": "Polymer/polymer#^1.1.4" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.2" }, - "_release": "1.0.3", + "_release": "1.0.4", "_resolution": { "type": "version", - "tag": "1.0.3", - "commit": "9a123f16a88737f967ed9e58ebb701eaa794b629" + "tag": "v1.0.4", + "commit": "6059f7d644cd97b9fe362b78a2742e3cdec6cdf4" }, "_source": "git://github.com/GoogleWebComponents/google-streetview-pano.git", "_target": "^1.0.0", diff --git a/lib/google-streetview-pano/bower.json b/lib/google-streetview-pano/bower.json index b0dcd9fd..d7d4d87c 100644 --- a/lib/google-streetview-pano/bower.json +++ b/lib/google-streetview-pano/bower.json @@ -1,13 +1,13 @@ { "name": "google-streetview-pano", - "version": "1.0.3", + "version": "1.0.4", "homepage": "https://elements.polymer-project.org/elements/google-streetview-pano", "description": "Google Maps street view web component", "main": "google-streetview-pano.html", "authors": [ "Rob Dodson" ], - "license": "Apache2", + "license": "Apache-2.0", "ignore": [ "bower_components", "test", @@ -23,8 +23,9 @@ "google" ], "dependencies": { - "polymer": "Polymer/polymer#^1.1.4", - "google-apis": "GoogleWebComponents/google-apis#^1.1.1" + "google-apis": "GoogleWebComponents/google-apis#^1.1.1", + "iron-resizable-behavior": "PolymerElements/iron-resizable-behavior#~1.0.2", + "polymer": "Polymer/polymer#^1.1.4" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.2" diff --git a/lib/google-streetview-pano/google-streetview-pano.html b/lib/google-streetview-pano/google-streetview-pano.html index a9c530f0..9fa0f7f2 100644 --- a/lib/google-streetview-pano/google-streetview-pano.html +++ b/lib/google-streetview-pano/google-streetview-pano.html @@ -1,5 +1,6 @@ + +### Description + + +### Expected outcome + + + +### Actual outcome + + + +### Live Demo + + +### Steps to reproduce + + + +### Browsers Affected + +- [ ] Chrome +- [ ] Firefox +- [ ] Safari 9 +- [ ] Safari 8 +- [ ] Safari 7 +- [ ] Edge +- [ ] IE 11 +- [ ] IE 10 diff --git a/lib/iron-iconset-svg/.travis.yml b/lib/iron-iconset-svg/.travis.yml index d4e78c40..9847a10d 100644 --- a/lib/iron-iconset-svg/.travis.yml +++ b/lib/iron-iconset-svg/.travis.yml @@ -1,28 +1,23 @@ language: node_js -sudo: false -matrix: - include: - - node_js: stable - script: xvfb-run wct - addons: - firefox: latest - apt: - sources: - - google-chrome - packages: - - google-chrome-stable - - node_js: node - script: - - | - if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then - wct -s 'default' - fi +sudo: required before_script: -- npm install web-component-tester -- npm install bower -- export PATH=$PWD/node_modules/.bin:$PATH +- npm install -g bower polylint web-component-tester - bower install +- polylint env: global: - - secure: UR1rxThVZH+l6fFHhAlgNIWs9wHmC5A102oAQBtCuQqKiXPZCDAPQHdjufX8z6hH93JkR+Esh2VPv0baSXFrHteKTRN6bsNDTMFDdHJ5BiRAdhVoV6bsdNH2GTgRXQ+ACMgrh4sXLA5+2Z+JGq7m0zaHehDfNZqmo/1U59qImP8= - - secure: PmWDypBdjKlUGPn9UoBEkjoYiyJFQGe2QiACmdOgueOLSLeA6xW+/1521uFIBHpwuWn29mxVYv5gS1D8hafWhZdXn4OYQl550RrT092jXIO6+mMKZXPmUaKCkPMY6QYJJ5j9ZOC36KgF//IpoE7OCxpLReYOD2KBR3mhw0jOYJA= + - secure: FVt0rYGSWqJW3i57y9CQHuDaa97UDwZuGc5ts+TDpbuR3DVP8LxB9MT1ApA2bqhg101hPzhWJWIK3Siotkb7eAlsiWgVhdNr8t5eZBPOOnjLiU6PNCF6ZGCZRJHQ6q4xQ2DycGug8OfwMw63yewLEYmVBppeAlStnPUfDWURlJ8= + - secure: X7cWxU13zLWoahM/BNBPSvgnI396zMmLzVHDHX6zAQL7gFL+PS4Dz6WjooO3Jx79ks2E8REUzWB8IFY3FohVAncXA///PAaqNLX0k2et4aOTOs5tcsCWL4nj8tKA6vjZIZ61rCjWTyNRR+o2QPsY9QQgi3Y+6bzLguWoPuycRbE= +node_js: stable +addons: + firefox: '46.0' + apt: + sources: + - google-chrome + packages: + - google-chrome-stable + sauce_connect: true +script: +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi +dist: trusty diff --git a/lib/iron-iconset-svg/CONTRIBUTING.md b/lib/iron-iconset-svg/CONTRIBUTING.md index 7b101415..093090d4 100644 --- a/lib/iron-iconset-svg/CONTRIBUTING.md +++ b/lib/iron-iconset-svg/CONTRIBUTING.md @@ -1,11 +1,16 @@ - + # Polymer Elements ## Guide for Contributors @@ -41,7 +46,7 @@ Polymer Elements are built in the open, and the Polymer authors eagerly encourag 3. Click the `paper-foo` element. ``` - 2. **A reduced test case that demonstrates the problem.** If possible, please include the test case as a JSBin. Start with this template to easily import and use relevant Polymer Elements: [http://jsbin.com/cagaye](http://jsbin.com/cagaye/edit?html,output). + 2. **A reduced test case that demonstrates the problem.** If possible, please include the test case as a JSBin. Start with this template to easily import and use relevant Polymer Elements: [https://jsbin.com/cagaye/edit?html,output](https://jsbin.com/cagaye/edit?html,output). 3. **A list of browsers where the problem occurs.** This can be skipped if the problem is the same across all browsers. @@ -51,14 +56,14 @@ Polymer Elements are built in the open, and the Polymer authors eagerly encourag When submitting pull requests, please provide: - 1. **A reference to the corresponding issue** or issues that will be closed by the pull request. Please refer to these issues using the following syntax: + 1. **A reference to the corresponding issue** or issues that will be closed by the pull request. Please refer to these issues in the pull request description using the following syntax: ```markdown (For a single issue) Fixes #20 (For multiple issues) - Fixes #32, #40 + Fixes #32, fixes #40 ``` 2. **A succinct description of the design** used to fix any related issues. For example: diff --git a/lib/iron-iconset-svg/README.md b/lib/iron-iconset-svg/README.md index f5b7e563..971ab0c7 100644 --- a/lib/iron-iconset-svg/README.md +++ b/lib/iron-iconset-svg/README.md @@ -7,16 +7,18 @@ iron-iconset-svg.html Edit those files, and our readme bot will duplicate them over here! Edit this file, and the bot will squash your changes :) +The bot does some handling of markdown. Please file a bug if it does the wrong +thing! https://github.com/PolymerLabs/tedium/issues + --> -[![Build Status](https://travis-ci.org/PolymerElements/iron-iconset-svg.svg?branch=master)](https://travis-ci.org/PolymerElements/iron-iconset-svg) +[![Build status](https://travis-ci.org/PolymerElements/iron-iconset-svg.svg?branch=master)](https://travis-ci.org/PolymerElements/iron-iconset-svg) -_[Demo and API Docs](https://elements.polymer-project.org/elements/iron-iconset-svg)_ +_[Demo and API docs](https://elements.polymer-project.org/elements/iron-iconset-svg)_ ##<iron-iconset-svg> - The `iron-iconset-svg` element allows users to define their own icon sets that contain svg icons. The svg icon elements should be children of the `iron-iconset-svg` element. Multiple icons should be given distinct id's. @@ -28,16 +30,18 @@ are stylable via css. Icons can be themed, colorized, and even animated. Example: - - - - - - - - - - +```html + + + + + + + + + + +``` This will automatically register the icon set "my-svg-icons" to the iconset database. To use these icons from within another element, make a @@ -45,6 +49,8 @@ database. To use these icons from within another element, make a to retrieve a given iconset. To apply a particular icon inside an element use the `applyIcon` method. For example: - iconset.applyIcon(iconNode, 'car'); +```javascript +iconset.applyIcon(iconNode, 'car'); +``` diff --git a/lib/iron-iconset-svg/bower.json b/lib/iron-iconset-svg/bower.json index 8467a3b7..664484a2 100644 --- a/lib/iron-iconset-svg/bower.json +++ b/lib/iron-iconset-svg/bower.json @@ -1,7 +1,7 @@ { "name": "iron-iconset-svg", "description": "Manages a set of svg icons", - "version": "1.0.9", + "version": "1.0.11", "keywords": [ "web-components", "polymer", @@ -27,7 +27,8 @@ "promise-polyfill": "polymerlabs/promise-polyfill#^1.0.0", "test-fixture": "polymerelements/test-fixture#^1.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0", - "web-component-tester": "*" + "web-component-tester": "^4.0.0" }, - "main": "iron-iconset-svg.html" + "main": "iron-iconset-svg.html", + "ignore": [] } diff --git a/lib/iron-iconset-svg/index.html b/lib/iron-iconset-svg/index.html index e871f17d..487bb5c3 100644 --- a/lib/iron-iconset-svg/index.html +++ b/lib/iron-iconset-svg/index.html @@ -2,11 +2,11 @@ diff --git a/lib/iron-iconset-svg/iron-iconset-svg.html b/lib/iron-iconset-svg/iron-iconset-svg.html index 5bd143ad..f7fd0d86 100644 --- a/lib/iron-iconset-svg/iron-iconset-svg.html +++ b/lib/iron-iconset-svg/iron-iconset-svg.html @@ -66,8 +66,25 @@ size: { type: Number, value: 24 + }, + + /** + * Set to true to enable mirroring of icons where specified when they are + * stamped. Icons that should be mirrored should be decorated with a + * `mirror-in-rtl` attribute. + */ + rtlMirroring: { + type: Boolean, + value: false } + }, + _targetIsRTL: function(target) { + if (target && target.nodeType !== Node.ELEMENT_NODE) { + target = target.host; + } + + return target && window.getComputedStyle(target)['direction'] === 'rtl'; }, attached: function() { @@ -103,7 +120,8 @@ // Remove old svg element this.removeIcon(element); // install new svg element - var svg = this._cloneIcon(iconName); + var svg = this._cloneIcon(iconName, + this.rtlMirroring && this._targetIsRTL(element)); if (svg) { var pde = Polymer.dom(element); pde.insertBefore(svg, pde.childNodes[0]); @@ -120,6 +138,7 @@ */ removeIcon: function(element) { // Remove old svg element + element = element.root || element; if (element._svgIcon) { Polymer.dom(element).removeChild(element._svgIcon); element._svgIcon = null; @@ -162,28 +181,35 @@ * @return {Element} Returns an installable clone of the SVG element * matching `id`. */ - _cloneIcon: function(id) { + _cloneIcon: function(id, mirrorAllowed) { // create the icon map on-demand, since the iconset itself has no discrete // signal to know when it's children are fully parsed this._icons = this._icons || this._createIconMap(); - return this._prepareSvgClone(this._icons[id], this.size); + return this._prepareSvgClone(this._icons[id], this.size, mirrorAllowed); }, /** * @param {Element} sourceSvg * @param {number} size + * @param {Boolean} mirrorAllowed * @return {Element} */ - _prepareSvgClone: function(sourceSvg, size) { + _prepareSvgClone: function(sourceSvg, size, mirrorAllowed) { if (sourceSvg) { var content = sourceSvg.cloneNode(true), svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - viewBox = content.getAttribute('viewBox') || '0 0 ' + size + ' ' + size; + viewBox = content.getAttribute('viewBox') || '0 0 ' + size + ' ' + size, + cssText = 'pointer-events: none; display: block; width: 100%; height: 100%;'; + + if (mirrorAllowed && content.hasAttribute('mirror-in-rtl')) { + cssText += '-webkit-transform:scale(-1,1);transform:scale(-1,1);'; + } + svg.setAttribute('viewBox', viewBox); svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); // TODO(dfreedm): `pointer-events: none` works around https://crbug.com/370136 // TODO(sjmiles): inline style may not be ideal, but avoids requiring a shadow-root - svg.style.cssText = 'pointer-events: none; display: block; width: 100%; height: 100%;'; + svg.style.cssText = cssText; svg.appendChild(content).removeAttribute('id'); return svg; } @@ -191,4 +217,5 @@ } }); + diff --git a/lib/iron-iconset-svg/test/index.html b/lib/iron-iconset-svg/test/index.html index db4a3f62..65e4abfd 100644 --- a/lib/iron-iconset-svg/test/index.html +++ b/lib/iron-iconset-svg/test/index.html @@ -1,15 +1,12 @@ - - - - - +--> Tests @@ -19,12 +16,12 @@ - - + + + diff --git a/lib/iron-iconset-svg/test/iron-iconset-svg.html b/lib/iron-iconset-svg/test/iron-iconset-svg.html index aa7bae9f..d9bc0768 100644 --- a/lib/iron-iconset-svg/test/iron-iconset-svg.html +++ b/lib/iron-iconset-svg/test/iron-iconset-svg.html @@ -22,6 +22,7 @@ + @@ -35,6 +36,23 @@ + + + + + + + + @@ -89,6 +108,32 @@ }); }); + suite('when stamping in an RTL context', function() { + var iconset; + var rtlContainer; + + setup(function() { + iconset = fixture('MirroredIconsetSvg'); + rtlContainer = fixture('RtlContainer'); + }); + + test('icons marked as mirror-in-rtl are mirrored', function() { + iconset.applyIcon(rtlContainer, 'rect'); + var svg = rtlContainer.firstElementChild; + var computedStyle = window.getComputedStyle(svg); + var transform = computedStyle.transform || computedStyle.webkitTransform; + expect(transform).to.be.eql('matrix(-1, 0, 0, 1, 0, 0)'); + }); + + test('icons not marked as mirror-in-rtl are not mirrored', function() { + iconset.applyIcon(rtlContainer, 'circle'); + var svg = rtlContainer.firstElementChild; + var computedStyle = window.getComputedStyle(svg); + var transform = computedStyle.transform || computedStyle.webkitTransform; + expect(transform).to.be.eql('none'); + }); + }); + suite('when paired with a size and SVG definition', function () { var iconset; var div; @@ -104,7 +149,7 @@ expect(rect.width).to.be.equal(0); expect(rect.height).to.be.equal(0); }); - + test('appends a child to the target element', function () { expect(div.firstElementChild).to.not.be.ok; iconset.applyIcon(div, 'circle'); @@ -134,6 +179,38 @@ iconset.applyIcon(div, 'circle'); expect(div.firstElementChild.getAttribute('viewBox')).to.be.equal('0 0 20 20'); }); + }); + + suite('Adding / removal from iron-icon', function () { + var iconset; + var div; + var ironIcon; + + setup(function () { + var elements = fixture('StandardIconsetSvg'); + iconset = elements[0]; + div = elements[1]; + ironIcon = elements[2]; + }); + + test('be able to remove an iconset from a standard DOM element', function () { + iconset.applyIcon(div, 'circle'); + Polymer.dom.flush(); + expect(div.children.length).to.be.equal(1); + iconset.removeIcon(div); + Polymer.dom.flush(); + expect(div.children.length).to.be.equal(0); + }); + + test('be able to remove an iconset from a Polymer element', function () { + var baseLength = Polymer.dom(ironIcon.root).children.length; + iconset.applyIcon(ironIcon, 'circle'); + Polymer.dom.flush(); + expect(Polymer.dom(ironIcon.root).children.length - baseLength).to.be.equal(1); + iconset.removeIcon(ironIcon); + Polymer.dom.flush(); + expect(Polymer.dom(ironIcon.root).children.length - baseLength).to.be.equal(0); + }); }); diff --git a/lib/iron-iconset/.bower.json b/lib/iron-iconset/.bower.json index 854a5e4d..fce3a639 100644 --- a/lib/iron-iconset/.bower.json +++ b/lib/iron-iconset/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-iconset", - "version": "1.0.4", + "version": "1.0.5", "license": "http://polymer.github.io/LICENSE.txt", "description": "Represents a set of icons", "authors": [ @@ -25,15 +25,17 @@ "iron-icon": "polymerelements/iron-icon#^1.0.0", "promise-polyfill": "polymerlabs/promise-polyfill#^1.0.0", "test-fixture": "PolymerElements/test-fixture#^1.0.0", - "web-component-tester": "*", + "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, + "main": "iron-iconset.html", + "ignore": [], "homepage": "https://github.com/PolymerElements/iron-iconset", - "_release": "1.0.4", + "_release": "1.0.5", "_resolution": { "type": "version", - "tag": "v1.0.4", - "commit": "97898a86053923b2787bac86c6e8133bb3f34566" + "tag": "v1.0.5", + "commit": "f21752e5879eb1d610d57934422de995f7d43572" }, "_source": "git://github.com/PolymerElements/iron-iconset.git", "_target": "^1.0.0", diff --git a/lib/iron-iconset/.github/ISSUE_TEMPLATE.md b/lib/iron-iconset/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..9865b681 --- /dev/null +++ b/lib/iron-iconset/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,33 @@ + +### Description + + +### Expected outcome + + + +### Actual outcome + + + +### Live Demo + + +### Steps to reproduce + + + +### Browsers Affected + +- [ ] Chrome +- [ ] Firefox +- [ ] Safari 9 +- [ ] Safari 8 +- [ ] Safari 7 +- [ ] Edge +- [ ] IE 11 +- [ ] IE 10 diff --git a/lib/iron-iconset/.travis.yml b/lib/iron-iconset/.travis.yml new file mode 100644 index 00000000..cc603caf --- /dev/null +++ b/lib/iron-iconset/.travis.yml @@ -0,0 +1,23 @@ +language: node_js +sudo: required +before_script: +- npm install -g bower polylint web-component-tester +- bower install +- polylint +env: + global: + - secure: GxvXlxKDmRGzwhPyK3BvuI0u5bd5Gu9zER/VWII5vhw9OXnt4tP6BQ0tpxeI6j8i6eCJhY3rXJ3pTyoBNs2QH5X0aqJhNSx1+xT5gYEgD8E9300+rO9/dXyzsmAjqZhFkzry4GJoAwGwqfNUUCiw2xpUxuIsdP4co1ybG5jD56Y= + - secure: VgpcpN2FotC2Ei4OsF1U19kqs++a6DqZ89xowrgdQXaXa7ipLLD6qeov2H2nmvcscXxoiGy2CQFnQr/XNso5LYU85+MXL/f0KhhUwXlCxZm/cCTGWX3j6CYASWjwNffFlLagK7mGEa7l7OMrjVHElxvgDgThI3gJOiuvYwu8ypk= +node_js: stable +addons: + firefox: '46.0' + apt: + sources: + - google-chrome + packages: + - google-chrome-stable + sauce_connect: true +script: +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi +dist: trusty diff --git a/lib/iron-iconset/CONTRIBUTING.md b/lib/iron-iconset/CONTRIBUTING.md new file mode 100644 index 00000000..093090d4 --- /dev/null +++ b/lib/iron-iconset/CONTRIBUTING.md @@ -0,0 +1,77 @@ + + +# Polymer Elements +## Guide for Contributors + +Polymer Elements are built in the open, and the Polymer authors eagerly encourage any and all forms of community contribution. When contributing, please follow these guidelines: + +### Filing Issues + +**If you are filing an issue to request a feature**, please provide a clear description of the feature. It can be helpful to describe answers to the following questions: + + 1. **Who will use the feature?** _“As someone filling out a form…”_ + 2. **When will they use the feature?** _“When I enter an invalid value…”_ + 3. **What is the user’s goal?** _“I want to be visually notified that the value needs to be corrected…”_ + +**If you are filing an issue to report a bug**, please provide: + + 1. **A clear description of the bug and related expectations.** Consider using the following example template for reporting a bug: + + ```markdown + The `paper-foo` element causes the page to turn pink when clicked. + + ## Expected outcome + + The page stays the same color. + + ## Actual outcome + + The page turns pink. + + ## Steps to reproduce + + 1. Put a `paper-foo` element in the page. + 2. Open the page in a web browser. + 3. Click the `paper-foo` element. + ``` + + 2. **A reduced test case that demonstrates the problem.** If possible, please include the test case as a JSBin. Start with this template to easily import and use relevant Polymer Elements: [https://jsbin.com/cagaye/edit?html,output](https://jsbin.com/cagaye/edit?html,output). + + 3. **A list of browsers where the problem occurs.** This can be skipped if the problem is the same across all browsers. + +### Submitting Pull Requests + +**Before creating a pull request**, please ensure that an issue exists for the corresponding change in the pull request that you intend to make. **If an issue does not exist, please create one per the guidelines above**. The goal is to discuss the design and necessity of the proposed change with Polymer authors and community before diving into a pull request. + +When submitting pull requests, please provide: + + 1. **A reference to the corresponding issue** or issues that will be closed by the pull request. Please refer to these issues in the pull request description using the following syntax: + + ```markdown + (For a single issue) + Fixes #20 + + (For multiple issues) + Fixes #32, fixes #40 + ``` + + 2. **A succinct description of the design** used to fix any related issues. For example: + + ```markdown + This fixes #20 by removing styles that leaked which would cause the page to turn pink whenever `paper-foo` is clicked. + ``` + + 3. **At least one test for each bug fixed or feature added** as part of the pull request. Pull requests that fix bugs or add features without accompanying tests will not be considered. + +If a proposed change contains multiple commits, please [squash commits](https://www.google.com/url?q=http://blog.steveklabnik.com/posts/2012-11-08-how-to-squash-commits-in-a-github-pull-request) to as few as is necessary to succinctly express the change. A Polymer author can help you squash commits, so don’t be afraid to ask us if you need help with that! diff --git a/lib/iron-iconset/bower.json b/lib/iron-iconset/bower.json index 2c65f468..8cc1c769 100644 --- a/lib/iron-iconset/bower.json +++ b/lib/iron-iconset/bower.json @@ -1,6 +1,6 @@ { "name": "iron-iconset", - "version": "1.0.4", + "version": "1.0.5", "license": "http://polymer.github.io/LICENSE.txt", "description": "Represents a set of icons", "authors": [ @@ -25,7 +25,9 @@ "iron-icon": "polymerelements/iron-icon#^1.0.0", "promise-polyfill": "polymerlabs/promise-polyfill#^1.0.0", "test-fixture": "PolymerElements/test-fixture#^1.0.0", - "web-component-tester": "*", + "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" - } + }, + "main": "iron-iconset.html", + "ignore": [] } diff --git a/lib/iron-iconset/demo/index.html b/lib/iron-iconset/demo/index.html index 400488d8..36c5f231 100644 --- a/lib/iron-iconset/demo/index.html +++ b/lib/iron-iconset/demo/index.html @@ -1,5 +1,6 @@ - - - + + + diff --git a/lib/iron-list/.bower.json b/lib/iron-list/.bower.json index be1fac3c..4ef3a9a9 100644 --- a/lib/iron-list/.bower.json +++ b/lib/iron-list/.bower.json @@ -7,7 +7,7 @@ "list", "virtual-list" ], - "version": "1.3.9", + "version": "1.3.11", "homepage": "https://github.com/PolymerElements/iron-list", "authors": [ "The Polymer Authors" @@ -23,7 +23,7 @@ "polymer": "Polymer/polymer#^1.1.0", "iron-resizable-behavior": "polymerelements/iron-resizable-behavior#^1.0.0", "iron-a11y-keys-behavior": "polymerelements/iron-a11y-keys-behavior#^1.0.0", - "iron-scroll-target-behavior": "PolymerElements/iron-scroll-target-behavior#^1.0.0" + "iron-scroll-target-behavior": "PolymerElements/iron-scroll-target-behavior#^1.1.0" }, "devDependencies": { "app-layout": "polymerelements/app-layout#^0.10.0", @@ -45,11 +45,11 @@ "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.2", "web-component-tester": "^4.0.0" }, - "_release": "1.3.9", + "_release": "1.3.11", "_resolution": { "type": "version", - "tag": "v1.3.9", - "commit": "0c89f3c9f9e5f25618f730d81f397c93080029a6" + "tag": "v1.3.11", + "commit": "889f62a3dbecc79f903b10e5f4a1a8f84a0436d8" }, "_source": "git://github.com/PolymerElements/iron-list.git", "_target": "^1.0.0", diff --git a/lib/iron-list/bower.json b/lib/iron-list/bower.json index a59ffc18..8bd21dfe 100644 --- a/lib/iron-list/bower.json +++ b/lib/iron-list/bower.json @@ -7,7 +7,7 @@ "list", "virtual-list" ], - "version": "1.3.9", + "version": "1.3.11", "homepage": "https://github.com/PolymerElements/iron-list", "authors": [ "The Polymer Authors" @@ -23,7 +23,7 @@ "polymer": "Polymer/polymer#^1.1.0", "iron-resizable-behavior": "polymerelements/iron-resizable-behavior#^1.0.0", "iron-a11y-keys-behavior": "polymerelements/iron-a11y-keys-behavior#^1.0.0", - "iron-scroll-target-behavior": "PolymerElements/iron-scroll-target-behavior#^1.0.0" + "iron-scroll-target-behavior": "PolymerElements/iron-scroll-target-behavior#^1.1.0" }, "devDependencies": { "app-layout": "polymerelements/app-layout#^0.10.0", diff --git a/lib/iron-list/iron-list.html b/lib/iron-list/iron-list.html index 9802501f..e24df719 100644 --- a/lib/iron-list/iron-list.html +++ b/lib/iron-list/iron-list.html @@ -278,7 +278,8 @@ var IOS_TOUCH_SCROLLING = IOS && IOS[1] >= 8; var DEFAULT_PHYSICAL_COUNT = 3; var HIDDEN_Y = '-10000px'; - var DEFAULT_GRID_SIZE = 200; + var ITEM_WIDTH = 0; + var ITEM_HEIGHT = 1; var SECRET_TABINDEX = -100; Polymer({ @@ -510,7 +511,7 @@ /** * The max number of pages to render. One page is equivalent to the height of the list. */ - _maxPages: 3, + _maxPages: 2, /** * The currently focused physical item. @@ -665,10 +666,6 @@ return this._viewportHeight * this._maxPages; }, - get _optPhysicalCount() { - return this._estRowsInView * this._itemsPerRow * this._maxPages; - }, - /** * True if the current list is visible. */ @@ -748,7 +745,6 @@ }, attached: function() { - this.updateViewportBoundaries(); if (this._physicalCount === 0) { this._debounceTemplate(this._render); } @@ -778,119 +774,108 @@ updateViewportBoundaries: function() { this._scrollerPaddingTop = this.scrollTarget === this ? 0 : parseInt(window.getComputedStyle(this)['padding-top'], 10); - + this._viewportWidth = this.$.items.offsetWidth; this._viewportHeight = this._scrollTargetHeight; - if (this.grid) { - this._updateGridMetrics(); - } + this.grid && this._updateGridMetrics(); }, /** - * Update the models, the position of the - * items in the viewport and recycle tiles as needed. + * Recycles the physical items when needed. */ _scrollHandler: function() { - // clamp the `scrollTop` value var scrollTop = Math.max(0, Math.min(this._maxScrollTop, this._scrollTop)); var delta = scrollTop - this._scrollPosition; - var tileHeight, tileTop, kth, recycledTileSet, scrollBottom, physicalBottom; - var ratio = this._ratio; - var recycledTiles = 0; - var hiddenContentSize = this._hiddenContentSize; - var currentRatio = ratio; - var movingUp = []; - - // track the last `scrollTop` + var isScrollingDown = delta >= 0; + // Track the current scroll position. this._scrollPosition = scrollTop; - - // clear cached visible indexes + // Clear indexes. this._firstVisibleIndexVal = null; this._lastVisibleIndexVal = null; - scrollBottom = this._scrollBottom; - physicalBottom = this._physicalBottom; - - // random access + // Random access. if (Math.abs(delta) > this._physicalSize) { - this._physicalTop += delta; - recycledTiles = Math.round(delta / this._physicalAverage); - } - // scroll up - else if (delta < 0) { - var topSpace = scrollTop - this._physicalTop; - var virtualStart = this._virtualStart; - - recycledTileSet = []; - - kth = this._physicalEnd; - currentRatio = topSpace / hiddenContentSize; - - // move tiles from bottom to top - while ( - // approximate `currentRatio` to `ratio` - currentRatio < ratio && - // recycle less physical items than the total - recycledTiles < this._physicalCount && - // ensure that these recycled tiles are needed - virtualStart - recycledTiles > 0 && - // ensure that the tile is not visible - physicalBottom - this._getPhysicalSizeIncrement(kth) > scrollBottom - ) { - - tileHeight = this._getPhysicalSizeIncrement(kth); - currentRatio += tileHeight / hiddenContentSize; - physicalBottom -= tileHeight; - recycledTileSet.push(kth); - recycledTiles++; - kth = (kth === 0) ? this._physicalCount - 1 : kth - 1; + var idxAdjustment = Math.round(delta / this._physicalAverage) * this._itemsPerRow + this._physicalTop = this._physicalTop + delta; + this._virtualStart = this._virtualStart + idxAdjustment; + this._physicalStart = this._physicalStart + idxAdjustment; + this._update(); + } else { + var reusables = this._getReusables(isScrollingDown); + if (isScrollingDown) { + this._physicalTop = reusables.physicalTop; + this._virtualStart = this._virtualStart + reusables.indexes.length; + this._physicalStart = this._physicalStart + reusables.indexes.length; + } else { + this._virtualStart = this._virtualStart - reusables.indexes.length; + this._physicalStart = this._physicalStart - reusables.indexes.length; } - - movingUp = recycledTileSet; - recycledTiles = -recycledTiles; - } - // scroll down - else if (delta > 0) { - var bottomSpace = physicalBottom - scrollBottom; - var virtualEnd = this._virtualEnd; - var lastVirtualItemIndex = this._virtualCount-1; - - recycledTileSet = []; - - kth = this._physicalStart; - currentRatio = bottomSpace / hiddenContentSize; - - // move tiles from top to bottom - while ( - // approximate `currentRatio` to `ratio` - currentRatio < ratio && - // recycle less physical items than the total - recycledTiles < this._physicalCount && - // ensure that these recycled tiles are needed - virtualEnd + recycledTiles < lastVirtualItemIndex && - // ensure that the tile is not visible - this._physicalTop + this._getPhysicalSizeIncrement(kth) < scrollTop - ) { - - tileHeight = this._getPhysicalSizeIncrement(kth); - currentRatio += tileHeight / hiddenContentSize; - - this._physicalTop += tileHeight; - recycledTileSet.push(kth); - recycledTiles++; - kth = (kth + 1) % this._physicalCount; + if (reusables.indexes.length === 0) { + this._increasePoolIfNeeded(); + } else { + this._update(reusables.indexes, isScrollingDown ? null : reusables.indexes); } } + }, - if (recycledTiles === 0) { - // Try to increase the pool if the list's client isn't filled up with physical items - if (physicalBottom < scrollBottom || this._physicalTop > scrollTop) { - this._increasePoolIfNeeded(); - } + /** + * Returns an object that contains the indexes of the physical items + * that might be reused and the physicalTop. + * + * @param {boolean} fromTop If the potential reusable items are above the scrolling region. + */ + _getReusables: function(fromTop) { + var ith, lastIth, offsetContent, physicalItemHeight; + var idxs = []; + var protectedOffsetContent = this._hiddenContentSize * this._ratio; + var virtualStart = this._virtualStart; + var virtualEnd = this._virtualEnd; + var physicalCount = this._physicalCount; + var physicalTop = this._physicalTop + this._scrollerPaddingTop; + var scrollTop = this._scrollTop; + var scrollBottom = this._scrollBottom; + + if (fromTop) { + ith = this._physicalStart; + lastIth = this._physicalEnd; + offsetContent = scrollTop - physicalTop; } else { - this._virtualStart = this._virtualStart + recycledTiles; - this._physicalStart = this._physicalStart + recycledTiles; - this._update(recycledTileSet, movingUp); + ith = this._physicalEnd; + lastIth = this._physicalStart; + offsetContent = this._physicalBottom - scrollBottom; + } + while (true) { + physicalItemHeight = this._getPhysicalSizeIncrement(ith); + offsetContent = offsetContent - physicalItemHeight; + if (idxs.length >= physicalCount || offsetContent <= protectedOffsetContent) { + break; + } + if (fromTop) { + // Check that index is within the valid range. + if (virtualEnd + idxs.length + 1 >= this._virtualCount) { + break; + } + // Check that the index is not visible. + if (physicalTop + physicalItemHeight >= scrollTop) { + break; + } + idxs.push(ith); + physicalTop = physicalTop + physicalItemHeight; + ith = (ith + 1) % physicalCount; + } else { + // Check that index is within the valid range. + if (virtualStart - idxs.length <= 0) { + break; + } + // Check that the index is not visible. + if (physicalTop + this._physicalSize - physicalItemHeight <= scrollBottom) { + break; + } + idxs.push(ith); + physicalTop = physicalTop - physicalItemHeight; + ith = (ith === 0) ? physicalCount - 1 : ith - 1; + } } + return { indexes: idxs, physicalTop: physicalTop - this._scrollerPaddingTop }; }, /** @@ -899,6 +884,9 @@ * @param {!Array=} movingUp */ _update: function(itemSet, movingUp) { + if (itemSet && itemSet.length === 0) { + return; + } this._manageFocus(); this._assignModels(itemSet); this._updateMetrics(itemSet); @@ -1010,13 +998,20 @@ }, /** - * Render a new list of items. + * Renders the a new list. */ _render: function() { if (this.isAttached && this._isVisible) { if (this._physicalCount === 0) { + this.updateViewportBoundaries(); this._increasePool(DEFAULT_PHYSICAL_COUNT); } else { + // Try to recycle nodes + var reusables = this._getReusables(true); + this._physicalTop = reusables.physicalTop; + this._virtualStart = this._virtualStart + reusables.indexes.length; + this._physicalStart = this._physicalStart + reusables.indexes.length; + this._update(reusables.indexes); this._update(); } } @@ -1152,6 +1147,7 @@ } else if (change.path === 'items.splices') { this._adjustVirtualIndex(change.value.indexSplices); this._virtualCount = this.items ? this.items.length : 0; + this._debounceTemplate(this._render); } else { @@ -1246,7 +1242,6 @@ var el = this._physicalItems[pidx]; var inst = el._templateInstance; var item = this.items && this.items[vidx]; - if (item != null) { inst[this.as] = item; inst.__key__ = this._collection.getKey(item); @@ -1278,22 +1273,18 @@ var prevPhysicalAvg = this._physicalAverage; this._iterateItems(function(pidx, vidx) { - oldPhysicalSize += this._physicalSizes[pidx] || 0; this._physicalSizes[pidx] = this._physicalItems[pidx].offsetHeight; newPhysicalSize += this._physicalSizes[pidx]; this._physicalAverageCount += this._physicalSizes[pidx] ? 1 : 0; - }, itemSet); - this._viewportHeight = this._scrollTargetHeight; if (this.grid) { this._updateGridMetrics(); this._physicalSize = Math.ceil(this._physicalCount / this._itemsPerRow) * this._rowHeight; } else { this._physicalSize = this._physicalSize + newPhysicalSize - oldPhysicalSize; } - // Update the average if it measured something. if (this._physicalAverageCount !== prevAvgCount) { this._physicalAverage = Math.round( @@ -1303,12 +1294,8 @@ }, _updateGridMetrics: function() { - this._viewportWidth = this.$.items.offsetWidth; - // Set item width to the value of the _physicalItems offsetWidth - this._itemWidth = this._physicalCount > 0 ? this._physicalItems[0].getBoundingClientRect().width : DEFAULT_GRID_SIZE; - // Set row height to the value of the _physicalItems offsetHeight - this._rowHeight = this._physicalCount > 0 ? this._physicalItems[0].offsetHeight : DEFAULT_GRID_SIZE; - // If in grid mode compute how many items with exist in each row + this._itemWidth = this._physicalCount > 0 ? this._physicalItems[0].getBoundingClientRect().width : 200; + this._rowHeight = this._physicalCount > 0 ? this._physicalItems[0].offsetHeight : 200; this._itemsPerRow = this._itemWidth ? Math.floor(this._viewportWidth / this._itemWidth) : this._itemsPerRow; }, @@ -1493,10 +1480,14 @@ Polymer.dom.addDebouncer(this.debounce('_debounceTemplate', function() { this.updateViewportBoundaries(); this._render(); - - if (this._physicalCount > 0 && this._isVisible) { - this._resetAverage(); - this.scrollToIndex(this.firstVisibleIndex); + if (this._isVisible) { + this.toggleScrollListener(true); + if (this._physicalCount > 0) { + this._resetAverage(); + this.scrollToIndex(this.firstVisibleIndex); + } + } else { + this.toggleScrollListener(false); } }.bind(this), 1)); }, @@ -1639,7 +1630,6 @@ model.tabIndex = SECRET_TABINDEX; activeElTabIndex = activeEl ? activeEl.tabIndex : -1; model.tabIndex = modelTabIndex; - // Only select the item if the tap wasn't on a focusable child // or the element bound to `tabIndex` if (activeEl && physicalItem !== activeEl && physicalItem.contains(activeEl) && activeElTabIndex !== SECRET_TABINDEX) { @@ -1720,7 +1710,6 @@ var physicalItem = this._physicalItems[this._getPhysicalIndex(idx)]; var model = physicalItem._templateInstance; var focusable; - // set a secret tab index model.tabIndex = SECRET_TABINDEX; // check if focusable element is the physical item diff --git a/lib/iron-list/test/basic.html b/lib/iron-list/test/basic.html index 1076c842..fb95d12e 100644 --- a/lib/iron-list/test/basic.html +++ b/lib/iron-list/test/basic.html @@ -121,33 +121,31 @@ assert.equal(list.lastVisibleIndex, ((list._scrollTop + container.listHeight) / container.itemHeight) - 1); }); - test('scroll to index', function(done) { + test('scroll to index', function() { list.items = buildDataSet(100); - setTimeout(function() { - list.scrollToIndex(30); - assert.equal(list.firstVisibleIndex, 30); + Polymer.dom.flush(); + list.scrollToIndex(30); + assert.equal(list.firstVisibleIndex, 30); - list.scrollToIndex(0); - assert.equal(list.firstVisibleIndex, 0); + list.scrollToIndex(0); + assert.equal(list.firstVisibleIndex, 0); - var rowHeight = getFirstItemFromList(list).offsetHeight; - var viewportHeight = list.offsetHeight; - var itemsPerViewport = Math.floor(viewportHeight/rowHeight); + var rowHeight = getFirstItemFromList(list).offsetHeight; + var viewportHeight = list.offsetHeight; + var itemsPerViewport = Math.floor(viewportHeight/rowHeight); - list.scrollToIndex(99); - assert.equal(list.firstVisibleIndex, list.items.length - itemsPerViewport); + list.scrollToIndex(99); + assert.equal(list.firstVisibleIndex, list.items.length - itemsPerViewport); - // make the height of the viewport same as the height of the row - // and scroll to the last item - list.style.height = list._physicalItems[0].offsetHeight + 'px'; + // make the height of the viewport same as the height of the row + // and scroll to the last item + list.style.height = list._physicalItems[0].offsetHeight + 'px'; + list.fire('iron-resize'); + Polymer.dom.flush(); + list.scrollToIndex(99); - setTimeout(function() { - list.scrollToIndex(99); - assert.equal(list.firstVisibleIndex, 99); - done(); - }, 100); - }, 100); + assert.equal(list.firstVisibleIndex, 99); }); test('scroll to index while not attached', function() { @@ -159,33 +157,30 @@ assert.equal(tmpList._virtualStart, 0); }); - test('scroll to item', function(done) { + test('scroll to item', function() { list.items = buildDataSet(100); - setTimeout(function() { - list.scrollToItem(list.items[30]); - assert.equal(list.firstVisibleIndex, 30); - - list.scrollToItem(list.items[0]); - assert.equal(list.firstVisibleIndex, 0); + Polymer.dom.flush(); + list.scrollToItem(list.items[30]); + assert.equal(list.firstVisibleIndex, 30); - var rowHeight = getFirstItemFromList(list).offsetHeight; - var viewportHeight = list.offsetHeight; - var itemsPerViewport = Math.floor(viewportHeight/rowHeight); + list.scrollToItem(list.items[0]); + assert.equal(list.firstVisibleIndex, 0); - list.scrollToItem(list.items[99]); - assert.equal(list.firstVisibleIndex, list.items.length - itemsPerViewport); + var rowHeight = getFirstItemFromList(list).offsetHeight; + var viewportHeight = list.offsetHeight; + var itemsPerViewport = Math.floor(viewportHeight/rowHeight); - // make the height of the viewport same as the height of the row - // and scroll to the last item - list.style.height = list._physicalItems[0].offsetHeight + 'px'; + list.scrollToItem(list.items[99]); + assert.equal(list.firstVisibleIndex, list.items.length - itemsPerViewport); - setTimeout(function() { - list.scrollToItem(list.items[99]); - assert.equal(list.firstVisibleIndex, 99); - done(); - }, 100); - }, 100); + // make the height of the viewport same as the height of the row + // and scroll to the last item + list.style.height = list._physicalItems[0].offsetHeight + 'px'; + list.fire('iron-resize'); + Polymer.dom.flush(); + list.scrollToItem(list.items[99]); + assert.equal(list.firstVisibleIndex, 99); }); test('scroll to top', function(done) { @@ -242,6 +237,45 @@ assert.isTrue(list._isVisible); }); + test('should not called the scroll handler if the list is not rendered', function(done) { + var scrollerSpy = sinon.spy(list, '_update'); + var test = 1; + list.items = buildDataSet(100); + list.scrollTarget = document.documentElement; + document.body.style.height = '10000px'; + Polymer.dom.flush(); + + window.addEventListener('scroll', function() { + setTimeout(function() { + if (test == 1) { + assert.isTrue(scrollerSpy.called, 'should call the scroll handler when the list is rendered 1'); + scrollerSpy.reset(); + // hide the list + list.style.display = 'none'; + list.fire('iron-resize'); + Polymer.dom.flush(); + window.scrollTo(0, 4000); + test = 2; + } else if (test == 2) { + assert.isFalse(scrollerSpy.called, 'should not call the scroll handler when the list is not rendered'); + // show the list again + list.style.display = ''; + list.fire('iron-resize'); + Polymer.dom.flush(); + window.scrollTo(0, 5000); + test = 3; + } else { + assert.isTrue(scrollerSpy.called, 'should call the scroll handler when the list is rendered 2'); + document.body.style.height = ''; + window.scrollTo(0, 0); + done(); + } + }); + }); + window.scrollTo(0, 1); + test = 1; + }); + }); diff --git a/lib/iron-list/test/different-heights.html b/lib/iron-list/test/different-heights.html index 65be9835..4bb72c59 100644 --- a/lib/iron-list/test/different-heights.html +++ b/lib/iron-list/test/different-heights.html @@ -63,9 +63,8 @@ target: 100000, onScrollEnd: done, onScroll: function() { - list.debounce('scroll', function() { - assert.isTrue(isFullOfItems(list)); - }); + Polymer.dom.flush(); + assert.isTrue(isFullOfItems(list)); } }); }); @@ -87,9 +86,8 @@ target: 100000, onScrollEnd: done, onScroll: function() { - list.debounce('scroll', function() { - assert.equal(isFullOfItems(list), true); - }); + Polymer.dom.flush(); + assert.equal(isFullOfItems(list), true); } }); }); @@ -109,9 +107,8 @@ target: 100000, onScrollEnd: done, onScroll: function() { - list.debounce('scroll', function() { - assert.isTrue(isFullOfItems(list)); - }); + Polymer.dom.flush(); + assert.isTrue(isFullOfItems(list)); } }); }); diff --git a/lib/iron-list/test/grid.html b/lib/iron-list/test/grid.html index 46800032..a0170655 100644 --- a/lib/iron-list/test/grid.html +++ b/lib/iron-list/test/grid.html @@ -104,37 +104,30 @@ }); }); - test('scroll to index', function(done) { + test('scroll to index', function() { list.items = buildDataSet(100); + Polymer.dom.flush(); + list.scrollToIndex(30); + assert.equal(list.firstVisibleIndex, 30); - flush(function() { - list.scrollToIndex(30); - assert.equal(list.firstVisibleIndex, 30); - - list.scrollToIndex(0); - assert.equal(list.firstVisibleIndex, 0); + list.scrollToIndex(0); + assert.equal(list.firstVisibleIndex, 0); - list.scrollToIndex(60); - assert.equal(list.firstVisibleIndex, 60); - - var rowHeight = getNthItemFromGrid(list, 0).offsetHeight; - var viewportHeight = list.offsetHeight; - var itemsPerViewport = Math.floor(viewportHeight/rowHeight) * list._itemsPerRow; + list.scrollToIndex(60); + assert.equal(list.firstVisibleIndex, 60); - list.scrollToIndex(99); - // assert.equal(list.firstVisibleIndex, list.items.length - 7); + var rowHeight = getNthItemFromGrid(list, 0).offsetHeight; + var viewportHeight = list.offsetHeight; + var itemsPerViewport = Math.floor(viewportHeight/rowHeight) * list._itemsPerRow; - // make the height of the viewport same as the height of the row - // and scroll to the last item - list.style.height = list._physicalItems[0].offsetHeight + 'px'; + list.scrollToIndex(99); + // make the height of the viewport same as the height of the row + // and scroll to the last item + list.style.height = list._physicalItems[0].offsetHeight + 'px'; + list.fire('iron-resize'); - flush(function() { - var idx = 99; - list.scrollToIndex(idx); - assert.equal(list.firstVisibleIndex, idx); - done(); - }); - }); + list.scrollToIndex(99); + assert.equal(list.firstVisibleIndex, 99); }); test('reset items', function(done) { diff --git a/lib/iron-list/test/smoke/debugging.html b/lib/iron-list/test/smoke/debugging.html new file mode 100644 index 00000000..d5cacff1 --- /dev/null +++ b/lib/iron-list/test/smoke/debugging.html @@ -0,0 +1,163 @@ + + + + + + + debugging + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/iron-list/test/smoke/history.html b/lib/iron-list/test/smoke/history.html new file mode 100644 index 00000000..d9ff1531 --- /dev/null +++ b/lib/iron-list/test/smoke/history.html @@ -0,0 +1,112 @@ + + + + + + + history use case + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/iron-list/test/smoke/index.html b/lib/iron-list/test/smoke/index.html index 783c2c10..9da366a4 100644 --- a/lib/iron-list/test/smoke/index.html +++ b/lib/iron-list/test/smoke/index.html @@ -20,7 +20,7 @@ - + diff --git a/lib/iron-list/test/smoke/physical-count.html b/lib/iron-list/test/smoke/physical-count.html deleted file mode 100644 index 3bdbfc62..00000000 --- a/lib/iron-list/test/smoke/physical-count.html +++ /dev/null @@ -1,296 +0,0 @@ - - - - - - - physical count - - - - - - - - - - - - - - - - - - - - - - - diff --git a/lib/iron-list/test/x-list.html b/lib/iron-list/test/x-list.html index 811249ab..b0d56827 100644 --- a/lib/iron-list/test/x-list.html +++ b/lib/iron-list/test/x-list.html @@ -36,6 +36,7 @@ iron-list { overflow: hidden; + background-color: black; } diff --git a/lib/iron-location/.bower.json b/lib/iron-location/.bower.json index 62c1279f..5d651f8e 100644 --- a/lib/iron-location/.bower.json +++ b/lib/iron-location/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-location", - "version": "0.8.8", + "version": "0.8.9", "description": "Bidirectional data binding into the page's URL.", "private": true, "authors": [ @@ -37,11 +37,11 @@ "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0", "iron-demo-helpers": "PolymerElements/iron-demo-helpers#^1.2.3" }, - "_release": "0.8.8", + "_release": "0.8.9", "_resolution": { "type": "version", - "tag": "v0.8.8", - "commit": "ab65525d349f13c467653a200711202eeae17ff0" + "tag": "v0.8.9", + "commit": "0af111e75cb029b836143f448193ed6646478837" }, "_source": "git://github.com/PolymerElements/iron-location.git", "_target": "^0.8.0", diff --git a/lib/iron-location/bower.json b/lib/iron-location/bower.json index f246e4a6..cf06f7ec 100644 --- a/lib/iron-location/bower.json +++ b/lib/iron-location/bower.json @@ -1,6 +1,6 @@ { "name": "iron-location", - "version": "0.8.8", + "version": "0.8.9", "description": "Bidirectional data binding into the page's URL.", "private": true, "authors": [ diff --git a/lib/iron-location/iron-location.html b/lib/iron-location/iron-location.html index a13b0709..eda14063 100644 --- a/lib/iron-location/iron-location.html +++ b/lib/iron-location/iron-location.html @@ -73,7 +73,7 @@ type: String, notify: true, value: function() { - return window.decodeURIComponent(window.location.search.slice(1)); + return window.location.search.slice(1); } }, /** @@ -172,8 +172,7 @@ this._dontUpdateUrl = true; this._hashChanged(); this.path = window.decodeURIComponent(window.location.pathname); - this.query = window.decodeURIComponent( - window.location.search.substring(1)); + this.query = window.location.search.substring(1); this._dontUpdateUrl = false; this._updateUrl(); }, @@ -182,8 +181,7 @@ this.path).replace(/\#/g, '%23').replace(/\?/g, '%3F'); var partiallyEncodedQuery = ''; if (this.query) { - partiallyEncodedQuery = '?' + window.encodeURI( - this.query).replace(/\#/g, '%23'); + partiallyEncodedQuery = '?' + this.query.replace(/\#/g, '%23'); } var partiallyEncodedHash = ''; if (this.hash) { @@ -197,8 +195,7 @@ return; } if (this.path === window.decodeURIComponent(window.location.pathname) && - this.query === window.decodeURIComponent( - window.location.search.substring(1)) && + this.query === window.location.search.substring(1) && this.hash === window.decodeURIComponent( window.location.hash.substring(1))) { // Nothing to do, the current URL is a representation of our properties. diff --git a/lib/iron-location/iron-query-params.html b/lib/iron-location/iron-query-params.html index e627261a..30907470 100644 --- a/lib/iron-location/iron-query-params.html +++ b/lib/iron-location/iron-query-params.html @@ -49,7 +49,8 @@ if (this._dontReact) { return; } - this.paramsString = this._encodeParams(this.paramsObject); + this.paramsString = this._encodeParams(this.paramsObject) + .replace(/%3F/g, '?').replace(/%2F/g, '/'); }, _encodeParams: function(params) { var encodedParams = []; diff --git a/lib/iron-location/test/index.html b/lib/iron-location/test/index.html index 83e5250b..ce67fdf3 100644 --- a/lib/iron-location/test/index.html +++ b/lib/iron-location/test/index.html @@ -19,7 +19,8 @@ WCT.loadSuites([ 'iron-location.html', 'iron-query-params.html', - 'initialization-tests.html' + 'initialization-tests.html', + 'integration.html' ]); diff --git a/lib/iron-location/test/integration.html b/lib/iron-location/test/integration.html new file mode 100644 index 00000000..9518d175 --- /dev/null +++ b/lib/iron-location/test/integration.html @@ -0,0 +1,135 @@ + + + + + iron-location + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/iron-location/test/iron-location.html b/lib/iron-location/test/iron-location.html index dc8c0044..4eebc611 100644 --- a/lib/iron-location/test/iron-location.html +++ b/lib/iron-location/test/iron-location.html @@ -12,7 +12,7 @@ iron-location - + @@ -201,18 +201,30 @@ 'foo#bar': '?foo%23bar', 'foo?bar': '?foo?bar', '/foo\'bar\'baz': ['?/foo%27bar%27baz', '?/foo\'bar\'baz'], + 'foo/bar/baz': '?foo/bar/baz' }; for (var plainTextQuery in queryEncodingExamples) { var encodedQueries = queryEncodingExamples[plainTextQuery]; if (typeof encodedQueries === 'string') { encodedQueries = [encodedQueries]; } + + var ironLocationQuery = encodedQueries.map(function(value) { + return value.substring(1); + }); expect(urlElem._initialized).to.be.eq(true); urlElem.query = plainTextQuery; expect(encodedQueries).to.contain(window.location.search); - expect(urlElem.query).to.be.equal(plainTextQuery); - expect(makeTemporaryIronLocation().query).to.be.equal(plainTextQuery); + expect(ironLocationQuery).to.contain(urlElem.query); + expect(ironLocationQuery).to.contain(makeTemporaryIronLocation().query); + + urlElem.query = 'dummyValue'; + urlElem.query = ironLocationQuery[0]; + + expect(encodedQueries).to.contain(window.location.search); + expect(ironLocationQuery).to.contain(urlElem.query); + expect(ironLocationQuery).to.contain(makeTemporaryIronLocation().query); } }); test('assigning to a relative path URL', function() { diff --git a/lib/iron-location/test/iron-query-params.html b/lib/iron-location/test/iron-query-params.html index cb69a9b3..3ffef2ee 100644 --- a/lib/iron-location/test/iron-query-params.html +++ b/lib/iron-location/test/iron-query-params.html @@ -12,7 +12,7 @@ iron-location - + @@ -67,7 +67,7 @@ object: {'monster kid:': '😿'} }, { - string: 'yes%2C%20ok%3F%20what%20is%20up%20with%20%CB%9Athiiis%CB%9A=%E2%98%83', + string: 'yes%2C%20ok?%20what%20is%20up%20with%20%CB%9Athiiis%CB%9A=%E2%98%83', object: {'yes, ok? what is up with ˚thiiis˚': '☃'} }, ]; diff --git a/lib/iron-menu-behavior/.bower.json b/lib/iron-menu-behavior/.bower.json index 753a4835..edba5ce7 100644 --- a/lib/iron-menu-behavior/.bower.json +++ b/lib/iron-menu-behavior/.bower.json @@ -1,6 +1,6 @@ { "name": "iron-menu-behavior", - "version": "1.1.10", + "version": "1.2.0", "description": "Provides accessible menu behavior", "authors": "The Polymer Authors", "keywords": [ @@ -34,11 +34,11 @@ "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, - "_release": "1.1.10", + "_release": "1.2.0", "_resolution": { "type": "version", - "tag": "v1.1.10", - "commit": "a0c185a39ef85f96a0316223db4d34f067fcb7f4" + "tag": "v1.2.0", + "commit": "038b48d9bdda3740d9701b4aea903b4ba0e45e2b" }, "_source": "git://github.com/PolymerElements/iron-menu-behavior.git", "_target": "^1.0.0", diff --git a/lib/iron-menu-behavior/bower.json b/lib/iron-menu-behavior/bower.json index 464b1418..6fd4434a 100644 --- a/lib/iron-menu-behavior/bower.json +++ b/lib/iron-menu-behavior/bower.json @@ -1,6 +1,6 @@ { "name": "iron-menu-behavior", - "version": "1.1.10", + "version": "1.2.0", "description": "Provides accessible menu behavior", "authors": "The Polymer Authors", "keywords": [ diff --git a/lib/iron-menu-behavior/iron-menu-behavior.html b/lib/iron-menu-behavior/iron-menu-behavior.html index a2703015..ac546996 100644 --- a/lib/iron-menu-behavior/iron-menu-behavior.html +++ b/lib/iron-menu-behavior/iron-menu-behavior.html @@ -44,6 +44,8 @@ } }, + _SEARCH_RESET_TIMEOUT_MS: 1000, + hostAttributes: { 'role': 'menu', 'tabindex': '0' @@ -124,16 +126,40 @@ * @param {KeyboardEvent} event A KeyboardEvent. */ _focusWithKeyboardEvent: function(event) { + this.cancelDebouncer('_clearSearchText'); + + var searchText = this._searchText || ''; + var key = event.key && event.key.length == 1 ? event.key : + String.fromCharCode(event.keyCode); + searchText += key.toLocaleLowerCase(); + + var searchLength = searchText.length; + for (var i = 0, item; item = this.items[i]; i++) { + if (item.hasAttribute('disabled')) { + continue; + } + var attr = this.attrForItemTitle || 'textContent'; - var title = item[attr] || item.getAttribute(attr); + var title = (item[attr] || item.getAttribute(attr) || '').trim(); - if (!item.hasAttribute('disabled') && title && - title.trim().charAt(0).toLowerCase() === String.fromCharCode(event.keyCode).toLowerCase()) { + if (title.length < searchLength) { + continue; + } + + if (title.slice(0, searchLength).toLocaleLowerCase() == searchText) { this._setFocusedItem(item); break; } } + + this._searchText = searchText; + this.debounce('_clearSearchText', this._clearSearchText, + this._SEARCH_RESET_TIMEOUT_MS); + }, + + _clearSearchText: function() { + this._searchText = ''; }, /** diff --git a/lib/iron-menu-behavior/test/iron-menu-behavior.html b/lib/iron-menu-behavior/test/iron-menu-behavior.html index fa36c52d..ea1322a9 100644 --- a/lib/iron-menu-behavior/test/iron-menu-behavior.html +++ b/lib/iron-menu-behavior/test/iron-menu-behavior.html @@ -120,6 +120,24 @@ + + + + + + + + diff --git a/lib/iron-scroll-target-behavior/test/basic.html b/lib/iron-scroll-target-behavior/test/basic.html index 5ca98b59..d3a04e67 100644 --- a/lib/iron-scroll-target-behavior/test/basic.html +++ b/lib/iron-scroll-target-behavior/test/basic.html @@ -94,6 +94,25 @@ done(); }); }); + + test('toggleScrollListener', function(done) { + flush(function() { + xScroll._scrollHandler = sinon.spy(); + xScroll.scrollTarget = 'temporaryScrollingRegion'; + xScroll.scroll(0, 100); + xScroll.toggleScrollListener(true); + setTimeout(function() { + assert.isTrue(xScroll._scrollHandler.called, '_scrollHandler should be called'); + xScroll._scrollHandler.reset(); + xScroll.toggleScrollListener(false); + xScroll.scroll(0, 200); + setTimeout(function() { + assert.isFalse(xScroll._scrollHandler.called, '_scrollHandler should not be called'); + done(); + }, 100); + }, 100); + }); + }); }); suite('scrolling region', function() { diff --git a/lib/marked-element/.bower.json b/lib/marked-element/.bower.json index ac63c57f..d3806d97 100644 --- a/lib/marked-element/.bower.json +++ b/lib/marked-element/.bower.json @@ -32,14 +32,14 @@ "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, "ignore": [], - "homepage": "https://github.com/PolymerElements/marked-element", + "homepage": "https://github.com/polymerelements/marked-element", "_release": "1.2.0", "_resolution": { "type": "version", "tag": "v1.2.0", "commit": "ea1a9bec29dad638f49be4f1e2f8831593ac3bc9" }, - "_source": "git://github.com/PolymerElements/marked-element.git", + "_source": "git://github.com/polymerelements/marked-element.git", "_target": "^1.0.0", - "_originalSource": "PolymerElements/marked-element" + "_originalSource": "polymerelements/marked-element" } \ No newline at end of file diff --git a/lib/paper-badge/.bower.json b/lib/paper-badge/.bower.json index 55101f94..9b58d437 100644 --- a/lib/paper-badge/.bower.json +++ b/lib/paper-badge/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-badge", - "version": "1.1.3", + "version": "1.1.4", "description": "Material design status message for elements", "authors": [ "The Polymer Authors" @@ -22,7 +22,9 @@ "dependencies": { "polymer": "Polymer/polymer#^1.1.0", "iron-resizable-behavior": "PolymerElements/iron-resizable-behavior#^1.0.0", - "paper-styles": "PolymerElements/paper-styles#^1.0.0" + "paper-styles": "PolymerElements/paper-styles#^1.0.0", + "iron-icon": "PolymerElements/iron-icon#^1.0.0", + "iron-flex-layout": "PolymerElements/iron-flex-layout#^1.0.0" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0", @@ -32,11 +34,11 @@ "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, - "_release": "1.1.3", + "_release": "1.1.4", "_resolution": { "type": "version", - "tag": "v1.1.3", - "commit": "1685ba12eb5d06358efb72814b445cbb9f570877" + "tag": "v1.1.4", + "commit": "f34ba1f4594c9d0bdffa8e94311bee47cad9c684" }, "_source": "git://github.com/PolymerElements/paper-badge.git", "_target": "^1.0.0", diff --git a/lib/paper-badge/bower.json b/lib/paper-badge/bower.json index 72d7d2be..5b21cae3 100644 --- a/lib/paper-badge/bower.json +++ b/lib/paper-badge/bower.json @@ -1,6 +1,6 @@ { "name": "paper-badge", - "version": "1.1.3", + "version": "1.1.4", "description": "Material design status message for elements", "authors": [ "The Polymer Authors" @@ -22,7 +22,9 @@ "dependencies": { "polymer": "Polymer/polymer#^1.1.0", "iron-resizable-behavior": "PolymerElements/iron-resizable-behavior#^1.0.0", - "paper-styles": "PolymerElements/paper-styles#^1.0.0" + "paper-styles": "PolymerElements/paper-styles#^1.0.0", + "iron-icon": "PolymerElements/iron-icon#^1.0.0", + "iron-flex-layout": "PolymerElements/iron-flex-layout#^1.0.0" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0", diff --git a/lib/paper-card/.bower.json b/lib/paper-card/.bower.json index 13afd25f..c69924e7 100644 --- a/lib/paper-card/.bower.json +++ b/lib/paper-card/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-card", - "version": "1.1.2", + "version": "1.1.4", "description": "Material design piece of paper with unique related data", "authors": [ "The Polymer Authors" @@ -11,7 +11,6 @@ "card" ], "main": "paper-card.html", - "private": true, "repository": { "type": "git", "url": "git://github.com/PolymerElements/paper-card.git" @@ -38,11 +37,11 @@ "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, - "_release": "1.1.2", + "_release": "1.1.4", "_resolution": { "type": "version", - "tag": "v1.1.2", - "commit": "eef34e36fe62ed4c7c64390c09cc064771b607e4" + "tag": "v1.1.4", + "commit": "e6a2a22dca735baa84ec098952c03dcc13e60e50" }, "_source": "git://github.com/PolymerElements/paper-card.git", "_target": "^1.0.0", diff --git a/lib/paper-card/README.md b/lib/paper-card/README.md index c16cb51d..3e477c98 100644 --- a/lib/paper-card/README.md +++ b/lib/paper-card/README.md @@ -1,65 +1,79 @@ - - - [![Build status](https://travis-ci.org/PolymerElements/paper-card.svg?branch=master)](https://travis-ci.org/PolymerElements/paper-card) -_[Demo and API docs](https://elements.polymer-project.org/elements/paper-card)_ - - ##<paper-card> Material design: [Cards](https://www.google.com/design/spec/components/cards.html) `paper-card` is a container with a drop shadow. -Example: - + ```html - - ... + +
+
Cafe Basilico +
+ + 250ft +
+
+
+ + + + + +
+

$・Italian, Cafe

+

Small plates, salads & sandwiches in an intimate setting.

+
+
+
+ + 5:30PM + 7:30PM + 9:00PM + Reserve +
+
``` - -### Accessibility - -By default, the `aria-label` will be set to the value of the `heading` attribute. - -### Styling - -The following custom properties and mixins are available for styling: - -| Custom property | Description | Default | -| --- | --- | --- | -| `--paper-card-background-color` | The background color of the card | `--primary-background-color` | -| `--paper-card-header-color` | The color of the header text | `#000` | -| `--paper-card-header` | Mixin applied to the card header section | `{}` | -| `--paper-card-header-text` | Mixin applied to the title in the card header section | `{}` | -| `--paper-card-header-image` | Mixin applied to the image in the card header section | `{}` | -| `--paper-card-header-image-text` | Mixin applied to the text overlapping the image in the card header section | `{}` | -| `--paper-card-content` | Mixin applied to the card content section | `{}` | -| `--paper-card-actions` | Mixin applied to the card action section | `{}` | -| `--paper-card` | Mixin applied to the card | `{}` | - - diff --git a/lib/paper-card/bower.json b/lib/paper-card/bower.json index a42ed3c2..1498f991 100644 --- a/lib/paper-card/bower.json +++ b/lib/paper-card/bower.json @@ -1,6 +1,6 @@ { "name": "paper-card", - "version": "1.1.2", + "version": "1.1.4", "description": "Material design piece of paper with unique related data", "authors": [ "The Polymer Authors" @@ -11,7 +11,6 @@ "card" ], "main": "paper-card.html", - "private": true, "repository": { "type": "git", "url": "git://github.com/PolymerElements/paper-card.git" diff --git a/lib/paper-card/paper-card.html b/lib/paper-card/paper-card.html index 25020315..e3c0b239 100644 --- a/lib/paper-card/paper-card.html +++ b/lib/paper-card/paper-card.html @@ -131,12 +131,13 @@
-
[[heading]]
+
[[heading]]
@@ -227,6 +228,14 @@ computed: '_computeAnimated(animatedShadow)' } }, + + /** + * Format function for aria-hidden. Use the ! operator results in the + * empty string when given a falsy value. + */ + _isHidden: function(image) { + return image ? 'false' : 'true'; + }, _headingChanged: function(heading) { var label = this.getAttribute('aria-label'); @@ -234,10 +243,7 @@ }, _computeHeadingClass: function(image) { - var cls = 'title-text'; - if (image) - cls += ' over-image'; - return cls; + return image ? ' over-image' : ''; }, _computeAnimated: function(animatedShadow) { diff --git a/lib/paper-card/test/basic.html b/lib/paper-card/test/basic.html index 2f35c114..525225b9 100644 --- a/lib/paper-card/test/basic.html +++ b/lib/paper-card/test/basic.html @@ -36,9 +36,10 @@ + diff --git a/lib/paper-header-panel/paper-header-panel.html b/lib/paper-header-panel/paper-header-panel.html index 6b41eb6d..66cb89af 100644 --- a/lib/paper-header-panel/paper-header-panel.html +++ b/lib/paper-header-panel/paper-header-panel.html @@ -87,6 +87,13 @@ }; } +To change the panel container: + + paper-header-panel { + --paper-header-panel-container: { + border: 1px solid gray; + }; + To change the panel container in different modes: paper-header-panel { @@ -121,6 +128,7 @@ ----------------|-------------|---------- `--paper-header-panel` | Mixin applied to the element | `{}` `--paper-header-panel-body` | Mixin applied to the element's body (i.e. everything below the toolbar) | `{}` +`--paper-header-panel-container` | Mixin applied to the container in any mode | `{}` `--paper-header-panel-scroll-container` | Mixin applied to the container when in scroll mode | `{}` `--paper-header-panel-cover-container` | Mixin applied to the container when in cover mode | `{}` `--paper-header-panel-standard-container` | Mixin applied to the container when in standard mode | `{}` @@ -166,6 +174,10 @@ @apply(--paper-header-panel-body); } + #mainContainer { + @apply(--paper-header-panel-container); + } + /* * mode: scroll */ diff --git a/lib/paper-icon-button/.bower.json b/lib/paper-icon-button/.bower.json index abf5a6ac..509aa3d1 100644 --- a/lib/paper-icon-button/.bower.json +++ b/lib/paper-icon-button/.bower.json @@ -1,7 +1,7 @@ { "name": "paper-icon-button", "private": true, - "version": "1.1.2", + "version": "1.1.3", "license": "http://polymer.github.io/LICENSE.txt", "description": "A material design icon button", "main": [ @@ -38,11 +38,11 @@ }, "ignore": [], "homepage": "https://github.com/PolymerElements/paper-icon-button", - "_release": "1.1.2", + "_release": "1.1.3", "_resolution": { "type": "version", - "tag": "v1.1.2", - "commit": "0a6c65f73765d6f6ae6cfe90ddc9905a2cf45f20" + "tag": "v1.1.3", + "commit": "5f96407aaaae68940b9073f0f7695d68acbaff53" }, "_source": "git://github.com/PolymerElements/paper-icon-button.git", "_target": "^1.0.0", diff --git a/lib/paper-icon-button/.travis.yml b/lib/paper-icon-button/.travis.yml index 82fb60bd..237feb1c 100644 --- a/lib/paper-icon-button/.travis.yml +++ b/lib/paper-icon-button/.travis.yml @@ -1,23 +1,23 @@ language: node_js sudo: required before_script: - - npm install -g bower polylint web-component-tester - - bower install - - polylint +- npm install -g bower polylint web-component-tester +- bower install +- polylint env: global: - - secure: A+iEL5FUMQWkkaOduE26bo0jW49LYKxDwWGZOty9H9fCDpBNQSADOhIvLzScGtjE7Rr3jVmowVsDN0XfVSRpJneEIvj7+tHAXUFoVey8vDVklOmhlR25IH2OczEmCkOS+sAKRiSF54aptdPeJhmpbMH0FyZfuX+jJfhdonJ+YQg= - - secure: Ps1Hy0fzmYRYF/ur2Myg7ol43HpzpooCoDvqzpMbIBWkXjXcN0KlPoNc6lEFlhjSpjddMFavdajKYIO0j9adAjZA7HYlf+BglhxV45lz13o04+QlNbDSADNyAlKJLrIvFacn9DE3VXlvBwBu83m+ndHUN/uMyHyZo0VE1/ad9Iw= + - secure: HdHTMNdAamEtP+Nl5/mL2X7IKba4p2+ljpDSnvkA6gyoLzrWRZAyUjJxGjVRutQejTa8ZLOGXnBYKugSIMrGv8cblvngbhEmIHd2HBnPjd140KNwtsCtzPRDMdJMrvekVOXgpCkecmGq9G/j0WOoOnYY9oJrHB5dFy0y7LfPy6w= + - secure: XjZRR/HW23UneacknoaYle/dg2Diupr9p9UOWLR7w6ejvwIP99nUF0Bh4trZkUiXBBt29HOBoETwBTMizDHNg8vKe544EgR26Fq4Lwk5EuEHy3xeyroiHlwc56ZC9Obye1kdM3QjU6rzJ7F9NuRL2E0ttgZjt/OnM+vKx3kqGOY= node_js: stable addons: firefox: '46.0' apt: sources: - - google-chrome + - google-chrome packages: - - google-chrome-stable + - google-chrome-stable sauce_connect: true script: - - xvfb-run wct - - "if [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ]; then wct -s 'default'; fi" +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi dist: trusty diff --git a/lib/paper-icon-button/README.md b/lib/paper-icon-button/README.md index b48be667..089c4c7b 100644 --- a/lib/paper-icon-button/README.md +++ b/lib/paper-icon-button/README.md @@ -27,8 +27,22 @@ the button, a ripple effect emanates from the center of the button. `paper-icon-button` includes a default icon set. Use `icon` to specify which icon from the icon set to use. + +```html + + ``` See [`iron-iconset`](iron-iconset) for more information about diff --git a/lib/paper-icon-button/bower.json b/lib/paper-icon-button/bower.json index ab58e4c2..3d7262b1 100644 --- a/lib/paper-icon-button/bower.json +++ b/lib/paper-icon-button/bower.json @@ -1,7 +1,7 @@ { "name": "paper-icon-button", "private": true, - "version": "1.1.2", + "version": "1.1.3", "license": "http://polymer.github.io/LICENSE.txt", "description": "A material design icon button", "main": [ diff --git a/lib/paper-input/.bower.json b/lib/paper-input/.bower.json index 9f502222..a6350325 100644 --- a/lib/paper-input/.bower.json +++ b/lib/paper-input/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-input", - "version": "1.1.19", + "version": "1.1.20", "description": "Material design text fields", "authors": [ "The Polymer Authors" @@ -48,11 +48,11 @@ "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, - "_release": "1.1.19", + "_release": "1.1.20", "_resolution": { "type": "version", - "tag": "v1.1.19", - "commit": "d248dad17af3ee46a0701a664e0f304c1619770d" + "tag": "v1.1.20", + "commit": "1c0fc5d8c5b1d2f2d49b500f91e8ae577804fa1f" }, "_source": "git://github.com/PolymerElements/paper-input.git", "_target": "^1.0.0", diff --git a/lib/paper-input/bower.json b/lib/paper-input/bower.json index 514ace3e..5df0d38f 100644 --- a/lib/paper-input/bower.json +++ b/lib/paper-input/bower.json @@ -1,6 +1,6 @@ { "name": "paper-input", - "version": "1.1.19", + "version": "1.1.20", "description": "Material design text fields", "authors": [ "The Polymer Authors" diff --git a/lib/paper-input/paper-textarea.html b/lib/paper-input/paper-textarea.html index 2b5c58d1..e4f4ee1e 100644 --- a/lib/paper-input/paper-textarea.html +++ b/lib/paper-input/paper-textarea.html @@ -64,6 +64,7 @@ placeholder$="[[placeholder]]" readonly$="[[readonly]]" required$="[[required]]" + minlength$="[[minlength]]" maxlength$="[[maxlength]]" autocapitalize$="[[autocapitalize]]" rows$="[[rows]]" diff --git a/lib/paper-progress/.bower.json b/lib/paper-progress/.bower.json index 010b4b31..4e8dcece 100644 --- a/lib/paper-progress/.bower.json +++ b/lib/paper-progress/.bower.json @@ -1,13 +1,14 @@ { "name": "paper-progress", - "version": "1.0.10", + "version": "1.0.11", "license": "http://polymer.github.io/LICENSE.txt", "description": "A material design progress bar", "authors": "The Polymer Authors", "keywords": [ "web-components", "polymer", - "progress" + "progress", + "loading" ], "main": "paper-progress.html", "repository": { @@ -30,11 +31,11 @@ }, "ignore": [], "homepage": "https://github.com/PolymerElements/paper-progress", - "_release": "1.0.10", + "_release": "1.0.11", "_resolution": { "type": "version", - "tag": "v1.0.10", - "commit": "dfdde2b02947fb2dfd3f2d303ec17f7f4919348c" + "tag": "v1.0.11", + "commit": "2caf19f08173955253c10bb889740b034808b482" }, "_source": "git://github.com/PolymerElements/paper-progress.git", "_target": "^1.0.0", diff --git a/lib/paper-progress/README.md b/lib/paper-progress/README.md index ece4fd18..f2278de0 100644 --- a/lib/paper-progress/README.md +++ b/lib/paper-progress/README.md @@ -1,103 +1,49 @@ - - - [![Build status](https://travis-ci.org/PolymerElements/paper-progress.svg?branch=master)](https://travis-ci.org/PolymerElements/paper-progress) -_[Demo and API docs](https://elements.polymer-project.org/elements/paper-progress)_ - - ##<paper-progress> Material design: [Progress & activity](https://www.google.com/design/spec/components/progress-activity.html) + +```html + + + +``` + The progress bars are for situations where the percentage completed can be determined. They give users a quick sense of how much longer an operation will take. -Example: - -```html - -``` - There is also a secondary progress which is useful for displaying intermediate progress, such as the buffer level during a streaming playback progress bar. -Example: - -```html - -``` - -### Styling progress bar: - -To change the active progress bar color: - -```css -paper-progress { - --paper-progress-active-color: #e91e63; -} -``` - -To change the secondary progress bar color: - -```css -paper-progress { - --paper-progress-secondary-color: #f8bbd0; -} -``` - -To change the progress bar background color: - -```css -paper-progress { - --paper-progress-container-color: #64ffda; -} -``` - -Add the class `transiting` to a paper-progress to animate the progress bar when -the value changed. You can also customize the transition: - -```css -paper-progress { - --paper-progress-transition-duration: 0.08s; - --paper-progress-transition-timing-function: ease; - --paper-progress-transition-transition-delay: 0s; -} -``` - -To change the duration of the indeterminate cycle: - -```css -paper-progress { - --paper-progress-indeterminate-cycle-duration: 2s; -} -``` - -The following mixins are available for styling: - -| Custom property | Description | Default | -| --- | --- | --- | -| `--paper-progress-container-color` | Mixin applied to container | `--google-grey-300` | -| `--paper-progress-transition-duration` | Duration of the transition | `0.008s` | -| `--paper-progress-transition-timing-function` | The timing function for the transition | `ease` | -| `--paper-progress-transition-delay` | delay for the transition | `0s` | -| `--paper-progress-active-color` | The color of the active bar | `--google-green-500` | -| `--paper-progress-secondary-color` | The color of the secondary bar | `--google-green-100` | -| `--paper-progress-disabled-active-color` | The color of the active bar if disabled | `--google-grey-500` | -| `--paper-progress-disabled-secondary-color` | The color of the secondary bar if disabled | `--google-grey-300` | -| `--paper-progress-height` | The height of the progress bar | `4px` | -| `--paper-progress-indeterminate-cycle-duration` | Duration of an indeterminate cycle | `2s` | - - diff --git a/lib/paper-progress/bower.json b/lib/paper-progress/bower.json index 017624b3..fc9e9810 100644 --- a/lib/paper-progress/bower.json +++ b/lib/paper-progress/bower.json @@ -7,7 +7,8 @@ "keywords": [ "web-components", "polymer", - "progress" + "progress", + "loading" ], "main": "paper-progress.html", "repository": { diff --git a/lib/paper-radio-group/.bower.json b/lib/paper-radio-group/.bower.json index 05336267..f9c59c67 100644 --- a/lib/paper-radio-group/.bower.json +++ b/lib/paper-radio-group/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-radio-group", - "version": "1.2.0", + "version": "1.2.1", "description": "A group of material design radio buttons", "authors": [ "The Polymer Authors" @@ -21,24 +21,25 @@ "ignore": [], "dependencies": { "polymer": "Polymer/polymer#^1.1.0", - "iron-menu-behavior": "PolymerElements/iron-menu-behavior#^1.1.7" + "iron-a11y-keys-behavior": "PolymerElements/iron-a11y-keys-behavior#^1.0.0", + "iron-menu-behavior": "PolymerElements/iron-menu-behavior#^1.1.7", + "paper-radio-button": "PolymerElements/paper-radio-button#^1.0.0" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0", "iron-demo-helpers": "PolymerElements/iron-demo-helpers#^1.0.0", "iron-test-helpers": "PolymerElements/iron-test-helpers#^1.0.0", - "paper-radio-button": "PolymerElements/paper-radio-button#^1.0.0", "paper-styles": "PolymerElements/paper-styles#^1.0.0", "test-fixture": "PolymerElements/test-fixture#^1.0.0", "web-component-tester": "^4.0.0", "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, "main": "paper-radio-group.html", - "_release": "1.2.0", + "_release": "1.2.1", "_resolution": { "type": "version", - "tag": "v1.2.0", - "commit": "1505d1a57fbeabcb779de3e9f0e9857acd8b5f13" + "tag": "v1.2.1", + "commit": "ce1a1090130ee3ab21f706cc39310edfe33388f2" }, "_source": "git://github.com/PolymerElements/paper-radio-group.git", "_target": "^1.0.0", diff --git a/lib/paper-radio-group/.travis.yml b/lib/paper-radio-group/.travis.yml index 6e7ba820..51df875d 100644 --- a/lib/paper-radio-group/.travis.yml +++ b/lib/paper-radio-group/.travis.yml @@ -1,23 +1,23 @@ language: node_js sudo: required before_script: - - npm install -g bower polylint web-component-tester - - bower install - - polylint +- npm install -g bower polylint web-component-tester +- bower install +- polylint env: global: - - secure: fuljRoGGYqpPmvGA/f/nsqHWRmAFSu0BpeXS838DmXDZGe2l6liTQM3WOg/zsbQimo62bzyfaX7RI0LEPv3kcdIAjxF78/0y+Gb092YOlWjBDf8+Kwz4UuxwEHQ9FRv4T0CiZnp81oo/J9DgBNUIuIKNoycVfp/GQNM7VH8NvYM= - - secure: ibwd66QS2gTWqIW57liwNiDZE1GHmS4lJ62T4cJ1lLUV41B6pONB62fzAVtvJhLfAyQeR3cX0+grCFJtc2v94r5DhVoTAdxuM3MrYQuM+p1XNpK/UUjEkRZkSP2GxHIztXDwePe96W5DqX/C9E/KC3G00NF5/rdtTkoEe6sn0wA= + - secure: MERTTM+t9rMsIccJ4em6ocmNYm1w1r2Zy9qRxhdM1ya0xT2dAlV7UZY7t1jZ4MEdvqtTro1oEzfUr0zgD/mwBJUxLAB0RLRIbYAJEAfngaUUMgbbIgj3yLUZ/bZCvPtfhDPA1W/VsyldhUGCxojzgJthWgAoqWRj6jFX6X+QeWw= + - secure: FvMxnNJsGlUg31KGuGjb0PpWHYFlMf9UPFzmLcFQAbc0kiWVoOl5adCfnv3yySf9EAKnolO02zR3K8KcCBQJ0SpWBlQ1pIgEdOxTXtWQRhlKHttKkj5L2X+qYAw4q5z0sy7lvb0VIjIOceabhvTTcnYmaF+OcrrVxd90ZpIckvk= node_js: stable addons: - firefox: latest + firefox: '46.0' apt: sources: - - google-chrome + - google-chrome packages: - - google-chrome-stable + - google-chrome-stable sauce_connect: true script: - - xvfb-run wct - - "if [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ]; then wct -s 'default'; fi" +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi dist: trusty diff --git a/lib/paper-radio-group/bower.json b/lib/paper-radio-group/bower.json index a26b81f2..9e59068d 100644 --- a/lib/paper-radio-group/bower.json +++ b/lib/paper-radio-group/bower.json @@ -1,6 +1,6 @@ { "name": "paper-radio-group", - "version": "1.2.0", + "version": "1.2.1", "description": "A group of material design radio buttons", "authors": [ "The Polymer Authors" @@ -21,13 +21,14 @@ "ignore": [], "dependencies": { "polymer": "Polymer/polymer#^1.1.0", - "iron-menu-behavior": "PolymerElements/iron-menu-behavior#^1.1.7" + "iron-a11y-keys-behavior": "PolymerElements/iron-a11y-keys-behavior#^1.0.0", + "iron-menu-behavior": "PolymerElements/iron-menu-behavior#^1.1.7", + "paper-radio-button": "PolymerElements/paper-radio-button#^1.0.0" }, "devDependencies": { "iron-component-page": "PolymerElements/iron-component-page#^1.0.0", "iron-demo-helpers": "PolymerElements/iron-demo-helpers#^1.0.0", "iron-test-helpers": "PolymerElements/iron-test-helpers#^1.0.0", - "paper-radio-button": "PolymerElements/paper-radio-button#^1.0.0", "paper-styles": "PolymerElements/paper-styles#^1.0.0", "test-fixture": "PolymerElements/test-fixture#^1.0.0", "web-component-tester": "^4.0.0", diff --git a/lib/paper-radio-group/paper-radio-group.html b/lib/paper-radio-group/paper-radio-group.html index da89be94..5027e11d 100644 --- a/lib/paper-radio-group/paper-radio-group.html +++ b/lib/paper-radio-group/paper-radio-group.html @@ -126,7 +126,7 @@ /** * Selects the given value. */ - select: function(value) { + select: function(value) { var newItem = this._valueToItem(value); if (newItem && newItem.hasAttribute('disabled')) { return; diff --git a/lib/paper-ripple/.bower.json b/lib/paper-ripple/.bower.json index fc0feff6..b77a084d 100644 --- a/lib/paper-ripple/.bower.json +++ b/lib/paper-ripple/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-ripple", - "version": "1.0.8", + "version": "1.0.10", "license": "http://polymer.github.io/LICENSE.txt", "description": "Adds a material design ripple to any container", "private": true, @@ -33,11 +33,11 @@ }, "ignore": [], "homepage": "https://github.com/PolymerElements/paper-ripple", - "_release": "1.0.8", + "_release": "1.0.10", "_resolution": { "type": "version", - "tag": "v1.0.8", - "commit": "eb1c01cac162b7ce7e78760d5c0df61c9a5c2974" + "tag": "v1.0.10", + "commit": "6fef0ee16db4b7eec81f270efaf6b55b6ea53aa2" }, "_source": "git://github.com/PolymerElements/paper-ripple.git", "_target": "^1.0.0", diff --git a/lib/paper-ripple/.travis.yml b/lib/paper-ripple/.travis.yml index c4c91b4e..787deed9 100644 --- a/lib/paper-ripple/.travis.yml +++ b/lib/paper-ripple/.travis.yml @@ -1,23 +1,23 @@ language: node_js sudo: required before_script: - - npm install -g bower polylint web-component-tester - - bower install - - polylint +- npm install -g bower polylint web-component-tester +- bower install +- polylint env: global: - - secure: YrC5bTrJwlszZQWfnRwDbLaZNLf+KnWXTAfzvul7eij21W3/v+E0wp9pFTLQj/G3bZWgOEZSsoXxASNcNu1JUmJRyLXpJgTps25IlS/VJTRHoK7jUjt5pJG1CbcgTixQblyOVtPqT6j0V23V0d3mhQ3H2xFBbcl87iYO1w+6nmQ= - - secure: NZv74uwtibMbmarEOWRUNkEwjz/2akWEIe2JDxglag2JUECWrcAKJIQUqYsO0KNUIg09xJEqWLWED4fN73p3z27Jl/z99ssVMvPQt8duoxwZ6UwcjVWUQNjgXKN6JDZCf+3hJsmU51Lp6mpzj0Y5m8nCjhh7/bBnJahH+VRm7bA= + - secure: eLNXQngbn6nHUirBVQAroarZUJHGZAj8sqSJaxRBqaL08//nzaOpnzuavYUeNSJ1fOnbL95jS5yZJy8+oCUW0a6BCXZUHJCrj/N6ywG4KpgPYQnUZVnpvsLdXZJuq4L4l5jYL1GsPydMePfAlrDpSu+QzEc1+C0q7sprxsbHbbQ= + - secure: YLIZR4/tqr25Ty+daEdTInLVXoV/lSwagZCGMfT84SgHj94UYHr9u9Te3tNDeI8I83Kq1PSUn1kKE6ptT+EjuGhTDsyLx2IboVDtNlngDIo5GTSO1RBBzIlHRIb2eMS6om9cfLiOEWM3gFS/Mos/VYO3/A3ZSLE5BcNFagij724= node_js: stable addons: firefox: '46.0' apt: sources: - - google-chrome + - google-chrome packages: - - google-chrome-stable + - google-chrome-stable sauce_connect: true script: - - xvfb-run wct - - "if [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ]; then wct -s 'default'; fi" +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi dist: trusty diff --git a/lib/paper-ripple/README.md b/lib/paper-ripple/README.md index 359b1319..6d3fa5a4 100644 --- a/lib/paper-ripple/README.md +++ b/lib/paper-ripple/README.md @@ -1,22 +1,5 @@ - - - [![Build status](https://travis-ci.org/PolymerElements/paper-ripple.svg?branch=master)](https://travis-ci.org/PolymerElements/paper-ripple) -_[Demo and API docs](https://elements.polymer-project.org/elements/paper-ripple)_ - - ##<paper-ripple> Material design: [Surface reaction](https://www.google.com/design/spec/animation/responsive-interaction.html#responsive-interaction-surface-reaction) @@ -25,66 +8,33 @@ Material design: [Surface reaction](https://www.google.com/design/spec/animation use to simulate a rippling effect emanating from the point of contact. The effect can be visualized as a concentric circle with motion. -Example: - -```html -
- -
-``` - -Note, it's important that the parent container of the ripple be relative position, otherwise -the ripple will emanate outside of the desired container. - -`paper-ripple` listens to "mousedown" and "mouseup" events so it would display ripple -effect when touches on it. You can also defeat the default behavior and -manually route the down and up actions to the ripple element. Note that it is -important if you call `downAction()` you will have to make sure to call -`upAction()` so that `paper-ripple` would end the animation loop. - -Example: - -```html - -... -downAction: function(e) { - this.$.ripple.downAction({detail: {x: e.x, y: e.y}}); -}, -upAction: function(e) { - this.$.ripple.upAction(); -} + ```html - +
+ +
-``` diff --git a/lib/paper-ripple/bower.json b/lib/paper-ripple/bower.json index 1fce5584..f5e3dceb 100644 --- a/lib/paper-ripple/bower.json +++ b/lib/paper-ripple/bower.json @@ -1,6 +1,6 @@ { "name": "paper-ripple", - "version": "1.0.8", + "version": "1.0.9", "license": "http://polymer.github.io/LICENSE.txt", "description": "Adds a material design ripple to any container", "private": true, diff --git a/lib/paper-ripple/paper-ripple.html b/lib/paper-ripple/paper-ripple.html index c0d74e6e..3fb18a37 100644 --- a/lib/paper-ripple/paper-ripple.html +++ b/lib/paper-ripple/paper-ripple.html @@ -693,6 +693,11 @@ } }, + /** + * This conflicts with Element#antimate(). + * https://developer.mozilla.org/en-US/docs/Web/API/Element/animate + * @suppress {checkTypes} + */ animate: function() { if (!this._animating) { return; diff --git a/lib/paper-spinner/.bower.json b/lib/paper-spinner/.bower.json index 38dad0d7..cc28d746 100644 --- a/lib/paper-spinner/.bower.json +++ b/lib/paper-spinner/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-spinner", - "version": "1.2.0", + "version": "1.2.1", "description": "A material design spinner", "authors": [ "The Polymer Authors" @@ -35,11 +35,11 @@ "paper-spinner.html", "paper-spinner-lite.html" ], - "_release": "1.2.0", + "_release": "1.2.1", "_resolution": { "type": "version", - "tag": "v1.2.0", - "commit": "66dc50a940aa9a3a067137defe1712aa85de6f35" + "tag": "v1.2.1", + "commit": "b858c85867bb6e2f9fa00ab335ea9ee496fa14b8" }, "_source": "git://github.com/PolymerElements/paper-spinner.git", "_target": "^1.0.0", diff --git a/lib/paper-spinner/.travis.yml b/lib/paper-spinner/.travis.yml index 2f5e400e..ff38c72d 100644 --- a/lib/paper-spinner/.travis.yml +++ b/lib/paper-spinner/.travis.yml @@ -1,23 +1,23 @@ language: node_js sudo: required before_script: - - npm install -g bower polylint web-component-tester - - bower install - - polylint +- npm install -g bower polylint web-component-tester +- bower install +- polylint env: global: - - secure: dpHtK5BMl68o/D6cQO9VsQWBPVuTrFPC56NT6kBLbiQtmxG2E2FD8dN4cHuEWafZopwYSsLLmEIIK77FMaonTSmzos5EixIQyqGxWTyNTpthg0Jenzc+6vZEs3h+3LDodFjdZSu8FgKyxU8SFLLGjAsSy8aegUNBszy7/SY8FAM= - - secure: EASvFsWb/njjh3DOLD5Oz3nw4QPl4aIhDAIhU2qelb2UCp8Q/KGniU7VjNoQ7OSN05jh2ooz8Pu3cAhLmrWumJn2atXEXvRPKtT/+1Ciy3xFcvgmqM0RHB+7qSSOUwgvPW9bwdzVxxMjAW7Oqb7w3nVn9/mEv2sMPNSv7iEbiUI= + - secure: dIA8M55rHJN07lbp0VCU9RkN4CWlbkVdU6cP4wFZabuJJusISThMZVrZeGtbdErvQ8oiSexrE8iCZ7A/OcLnVNCrVBZX5YwJlfbex4I4uG6L8zw1E3oOX1MmdcTx2sI8MffDyG1pnXzwP5lzPItKiscEpepGY9+V0JP1j5z9qVg= + - secure: KvttUgmPIlCz4WU2WIpse5s/1SVXHoS+snGDkNqYLOVXscRjJoncXYbdvLltf7SPrU7gK4HuEuEVRthhDGtuvgrXUlIOS/gaK8dWI3kuVYPppOU1DnlXgAtj/3quGZG1dNw07IGzOEW4Taq/5KdU8LRqb9clvK+jyoBQZKIXbtg= node_js: stable addons: - firefox: latest + firefox: '46.0' apt: sources: - - google-chrome + - google-chrome packages: - - google-chrome-stable + - google-chrome-stable sauce_connect: true script: - - xvfb-run wct - - "if [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ]; then wct -s 'default'; fi" +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi dist: trusty diff --git a/lib/paper-spinner/README.md b/lib/paper-spinner/README.md index ad57a2fc..e913ae5b 100644 --- a/lib/paper-spinner/README.md +++ b/lib/paper-spinner/README.md @@ -1,93 +1,49 @@ - - - [![Build status](https://travis-ci.org/PolymerElements/paper-spinner.svg?branch=master)](https://travis-ci.org/PolymerElements/paper-spinner) -_[Demo and API docs](https://elements.polymer-project.org/elements/paper-spinner)_ - - ##<paper-spinner> Material design: [Progress & activity](https://www.google.com/design/spec/components/progress-activity.html) Element providing a multiple color material design circular spinner. -```html - -``` - -The default spinner cycles between four layers of colors; by default they are -blue, red, yellow and green. It can be customized to cycle between four different -colors. Use for single color spinners. - -### Accessibility - -Alt attribute should be set to provide adequate context for accessibility. If not provided, -it defaults to 'loading'. -Empty alt can be provided to mark the element as decorative if alternative content is provided -in another form (e.g. a text block following the spinner). - -```html - + ```html - +... + + + + ``` - -### Styling - -The following custom properties and mixins are available for styling: - -| Custom property | Description | Default | -| --- | --- | --- | -| `--paper-spinner-color` | Color of the spinner | `--google-blue-500` | -| `--paper-spinner-stroke-width` | The width of the spinner stroke | 3px | - - - - diff --git a/lib/paper-styles/.bower.json b/lib/paper-styles/.bower.json index ae677ef3..7dbddd34 100644 --- a/lib/paper-styles/.bower.json +++ b/lib/paper-styles/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-styles", - "version": "1.1.4", + "version": "1.1.5", "description": "Common (global) styles for Material Design elements.", "authors": [ "The Polymer Authors" @@ -30,11 +30,11 @@ "iron-component-page": "polymerelements/iron-component-page#^1.0.0", "web-component-tester": "^4.0.0" }, - "_release": "1.1.4", + "_release": "1.1.5", "_resolution": { "type": "version", - "tag": "v1.1.4", - "commit": "885bbd74db88dab4fb5dc229cdf994c55fb2b31b" + "tag": "v1.1.5", + "commit": "4b26a4e50db27c53425f61a0dc9148b73691970a" }, "_source": "git://github.com/PolymerElements/paper-styles.git", "_target": "^1.0.0", diff --git a/lib/paper-styles/CONTRIBUTING.md b/lib/paper-styles/CONTRIBUTING.md index f147978a..093090d4 100644 --- a/lib/paper-styles/CONTRIBUTING.md +++ b/lib/paper-styles/CONTRIBUTING.md @@ -1,4 +1,3 @@ - + # Polymer Elements ## Guide for Contributors diff --git a/lib/paper-styles/bower.json b/lib/paper-styles/bower.json index f3330c3c..83a51a6a 100644 --- a/lib/paper-styles/bower.json +++ b/lib/paper-styles/bower.json @@ -1,6 +1,6 @@ { "name": "paper-styles", - "version": "1.1.4", + "version": "1.1.5", "description": "Common (global) styles for Material Design elements.", "authors": [ "The Polymer Authors" diff --git a/lib/paper-styles/classes/shadow-layout.html b/lib/paper-styles/classes/shadow-layout.html index fe55ec80..196df284 100644 --- a/lib/paper-styles/classes/shadow-layout.html +++ b/lib/paper-styles/classes/shadow-layout.html @@ -7,6 +7,11 @@ Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> + + + diff --git a/lib/paper-toggle-button/.bower.json b/lib/paper-toggle-button/.bower.json index 77c711e6..eed9ab61 100644 --- a/lib/paper-toggle-button/.bower.json +++ b/lib/paper-toggle-button/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-toggle-button", - "version": "1.2.0", + "version": "1.2.1", "description": "A material design toggle button control", "authors": [ "The Polymer Authors" @@ -35,11 +35,11 @@ "webcomponentsjs": "webcomponents/webcomponentsjs#^0.7.0" }, "main": "paper-toggle-button.html", - "_release": "1.2.0", + "_release": "1.2.1", "_resolution": { "type": "version", - "tag": "v1.2.0", - "commit": "6aab07244c07f9598584e6dbce366574f96072a3" + "tag": "v1.2.1", + "commit": "f76bf2b79aff6ce4ba74df1411d371c3c4dd26f3" }, "_source": "git://github.com/PolymerElements/paper-toggle-button.git", "_target": "^1.0.0", diff --git a/lib/paper-toggle-button/README.md b/lib/paper-toggle-button/README.md index 8fee54f6..9741b123 100644 --- a/lib/paper-toggle-button/README.md +++ b/lib/paper-toggle-button/README.md @@ -1,22 +1,5 @@ - - - [![Build status](https://travis-ci.org/PolymerElements/paper-toggle-button.svg?branch=master)](https://travis-ci.org/PolymerElements/paper-toggle-button) -_[Demo and API docs](https://elements.polymer-project.org/elements/paper-toggle-button)_ - - ##<paper-toggle-button> Material design: [Switch](https://www.google.com/design/spec/components/selection-controls.html#selection-controls-switch) @@ -24,32 +7,26 @@ Material design: [Switch](https://www.google.com/design/spec/components/selectio `paper-toggle-button` provides a ON/OFF switch that user can toggle the state by tapping or by dragging the switch. -Example: - + ```html - + + ``` - -### Styling - -The following custom properties and mixins are available for styling: - -| Custom property | Description | Default | -| --- | --- | --- | -| `--paper-toggle-button-unchecked-bar-color` | Slider color when the input is not checked | `#000000` | -| `--paper-toggle-button-unchecked-button-color` | Button color when the input is not checked | `--paper-grey-50` | -| `--paper-toggle-button-unchecked-ink-color` | Selected/focus ripple color when the input is not checked | `--dark-primary-color` | -| `--paper-toggle-button-checked-bar-color` | Slider button color when the input is checked | `--primary-color` | -| `--paper-toggle-button-checked-button-color` | Button color when the input is checked | `--primary-color` | -| `--paper-toggle-button-checked-ink-color` | Selected/focus ripple color when the input is checked | `--primary-color` | -| `--paper-toggle-button-unchecked-bar` | Mixin applied to the slider when the input is not checked | `{}` | -| `--paper-toggle-button-unchecked-button` | Mixin applied to the slider button when the input is not checked | `{}` | -| `--paper-toggle-button-checked-bar` | Mixin applied to the slider when the input is checked | `{}` | -| `--paper-toggle-button-checked-button` | Mixin applied to the slider button when the input is checked | `{}` | -| `--paper-toggle-button-label-color` | Label color | `--primary-text-color` | -| `--paper-toggle-button-label-spacing` | Spacing between the label and the button | `8px` | - -This element applies the mixin `--paper-font-common-base` but does not import `paper-styles/typography.html`. -In order to apply the `Roboto` font to this element, make sure you've imported `paper-styles/typography.html`. - - diff --git a/lib/paper-toolbar/.bower.json b/lib/paper-toolbar/.bower.json index aabfdbe3..aa5c0f4c 100644 --- a/lib/paper-toolbar/.bower.json +++ b/lib/paper-toolbar/.bower.json @@ -1,6 +1,6 @@ { "name": "paper-toolbar", - "version": "1.1.6", + "version": "1.1.7", "license": "http://polymer.github.io/LICENSE.txt", "description": "A material design toolbar that is easily customizable", "private": true, @@ -35,11 +35,11 @@ }, "ignore": [], "homepage": "https://github.com/PolymerElements/paper-toolbar", - "_release": "1.1.6", + "_release": "1.1.7", "_resolution": { "type": "version", - "tag": "v1.1.6", - "commit": "39b8ad381bd4ba7834ed8f30a938b49810b9204f" + "tag": "v1.1.7", + "commit": "e727b200910c9f4850e9b12d23420aeece018bd8" }, "_source": "git://github.com/PolymerElements/paper-toolbar.git", "_target": "^1.0.0", diff --git a/lib/paper-toolbar/.travis.yml b/lib/paper-toolbar/.travis.yml index 5947fe98..b1654f68 100644 --- a/lib/paper-toolbar/.travis.yml +++ b/lib/paper-toolbar/.travis.yml @@ -1,23 +1,23 @@ language: node_js sudo: required before_script: - - npm install -g bower polylint web-component-tester - - bower install - - polylint +- npm install -g bower polylint web-component-tester +- bower install +- polylint env: global: - - secure: K2cuhKpShJ9cc0XCnsHbLpw1qCXTRWiJqkn6hFrt3T7L+1bDSsMtzmZvfk7Pp4VbJCgEKmtgMitbr7gdTjxLpIr7qQv7SmErnbcoT+wEyOTfyK96YSkAOCIIafgWHWSHrwiDdqXvFlYe3sP4JPP8yH6kuIjYzphQ2H7k0yXnW04= - - secure: Til0DgFyTBk2pkrG5WrQ64g8ckN6Rbdqxm/F+HGbzG/hVXO6/fHqetlNKxvxotoI3LBb/iYFr7GXuNTgIYaH4qGVeV1MsOj7NUnFDYUJVcx/WhZO66CY+dno7UffBDV0wgd4mpsK8iLG4+Eitf1FcMBbY5esX4mFy3fFM8/6LyE= + - secure: YhDTyZvC5P5rhCWlBTeIhKJx2izTUgaBPbWWCtVE/ukYfXeO0HY49emFYSOBJe3oKLLlipuTFehbtyZ4QPWmfa7QKEtnyYSfyCnOA3mJFzoMDDt/RVqDfWpa+fjpIdVR045ySCQE7NAbD47i8gAVwmlQ10k/yU+BA9uGxVHPSwo= + - secure: GvWTJBajnq7yHfbx+Ud7jmG6ZNXf79U7i3UhTsXkDhotqzJr//MlJGzZFBZjbk2Qsgcx+x4cT10ieZR4oixn/ipiz/NfKvIbHl4+0sLauum+5lDd8TmKspJULzSeDkYcVl8tEVKn2vdCTBaTRQituXvDlipat1drAu4Zx3EtmxI= node_js: stable addons: firefox: '46.0' apt: sources: - - google-chrome + - google-chrome packages: - - google-chrome-stable + - google-chrome-stable sauce_connect: true script: - - xvfb-run wct - - "if [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ]; then wct -s 'default'; fi" +- xvfb-run wct +- if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then wct -s 'default'; fi dist: trusty diff --git a/lib/paper-toolbar/README.md b/lib/paper-toolbar/README.md index a93e3aea..86265181 100644 --- a/lib/paper-toolbar/README.md +++ b/lib/paper-toolbar/README.md @@ -79,8 +79,8 @@ with `bottom`. ``` -When inside a `paper-header-panel` element, the class `.animate` is toggled to animate -the height change in the toolbar. +When inside a `paper-header-panel` element with `mode="waterfall-tall"`, +the class `.animate` is toggled to animate the height change in the toolbar. ### Styling diff --git a/lib/paper-toolbar/bower.json b/lib/paper-toolbar/bower.json index 1fc3b4e3..7ab13e4b 100644 --- a/lib/paper-toolbar/bower.json +++ b/lib/paper-toolbar/bower.json @@ -1,6 +1,6 @@ { "name": "paper-toolbar", - "version": "1.1.6", + "version": "1.1.7", "license": "http://polymer.github.io/LICENSE.txt", "description": "A material design toolbar that is easily customizable", "private": true, diff --git a/lib/paper-toolbar/paper-toolbar.html b/lib/paper-toolbar/paper-toolbar.html index ff1e2e30..452fbd29 100644 --- a/lib/paper-toolbar/paper-toolbar.html +++ b/lib/paper-toolbar/paper-toolbar.html @@ -74,8 +74,8 @@ ``` -When inside a `paper-header-panel` element, the class `.animate` is toggled to animate -the height change in the toolbar. +When inside a `paper-header-panel` element with `mode="waterfall-tall"`, +the class `.animate` is toggled to animate the height change in the toolbar. ### Styling diff --git a/lib/platinum-bluetooth/.bower.json b/lib/platinum-bluetooth/.bower.json index 6b2c1757..b3fc99e3 100644 --- a/lib/platinum-bluetooth/.bower.json +++ b/lib/platinum-bluetooth/.bower.json @@ -1,6 +1,6 @@ { "name": "platinum-bluetooth", - "version": "2.1.1", + "version": "2.1.2", "private": true, "license": "http://polymer.github.io/LICENSE.txt", "authors": [ @@ -34,11 +34,11 @@ "paper-styles": "PolymerElements/paper-styles#^1.0.0", "web-component-tester": "^4.0.0" }, - "_release": "2.1.1", + "_release": "2.1.2", "_resolution": { "type": "version", - "tag": "v2.1.1", - "commit": "331d7f03c61ec645ec09db5b416ac92d8a9a2db2" + "tag": "v2.1.2", + "commit": "f0d5e6e52ab308e9a553034a15f4bd71f2143125" }, "_source": "git://github.com/PolymerElements/platinum-bluetooth.git", "_target": "^2.0.0", diff --git a/lib/platinum-bluetooth/README.md b/lib/platinum-bluetooth/README.md index 2c5931b4..9a32ac3f 100644 --- a/lib/platinum-bluetooth/README.md +++ b/lib/platinum-bluetooth/README.md @@ -149,7 +149,7 @@ You can also use changes in `value` to drive characteristic writes when + auto-write> diff --git a/lib/platinum-bluetooth/bower.json b/lib/platinum-bluetooth/bower.json index 0f5562af..ffa4662a 100644 --- a/lib/platinum-bluetooth/bower.json +++ b/lib/platinum-bluetooth/bower.json @@ -1,6 +1,6 @@ { "name": "platinum-bluetooth", - "version": "2.1.1", + "version": "2.1.2", "private": true, "license": "http://polymer.github.io/LICENSE.txt", "authors": [ diff --git a/lib/platinum-bluetooth/platinum-bluetooth-characteristic.html b/lib/platinum-bluetooth/platinum-bluetooth-characteristic.html index 01c3c468..f5e7e3a1 100644 --- a/lib/platinum-bluetooth/platinum-bluetooth-characteristic.html +++ b/lib/platinum-bluetooth/platinum-bluetooth-characteristic.html @@ -19,22 +19,22 @@ window.BluetoothDevice = {}; } - // This allows us to use BluetoothGATTRemoteServer related attributes type + // This allows us to use BluetoothRemoteGATTServer related attributes type // in browsers where it is not defined. - if (!('BluetoothGATTRemoteServer' in window)) { - window.BluetoothGATTRemoteServer = {}; + if (!('BluetoothRemoteGATTServer' in window)) { + window.BluetoothRemoteGATTServer = {}; } - // This allows us to use BluetoothGATTService related attributes type in + // This allows us to use BluetoothRemoteGATTService related attributes type in // browsers where it is not defined. - if (!('BluetoothGATTService' in window)) { - window.BluetoothGATTService = {}; + if (!('BluetoothRemoteGATTService' in window)) { + window.BluetoothRemoteGATTService = {}; } - // This allows us to use BluetoothGATTCharacteristic related attributes + // This allows us to use BluetoothRemoteGATTCharacteristic related attributes // type in browsers where it is not defined. - if (!('BluetoothGATTCharacteristic' in window)) { - window.BluetoothGATTCharacteristic = {}; + if (!('BluetoothRemoteGATTCharacteristic' in window)) { + window.BluetoothRemoteGATTCharacteristic = {}; } /** @@ -165,7 +165,7 @@ * * * + * auto-write> * * * @@ -244,7 +244,7 @@ */ _server: { readOnly: true, - type: BluetoothGATTRemoteServer + type: BluetoothRemoteGATTServer }, /** @@ -252,7 +252,7 @@ */ _service: { readOnly: true, - type: BluetoothGATTService + type: BluetoothRemoteGATTService }, /** @@ -260,7 +260,7 @@ */ _characteristic: { readOnly: true, - type: BluetoothGATTCharacteristic + type: BluetoothRemoteGATTCharacteristic } }, @@ -283,13 +283,9 @@ * Returns a promise that will resolve when bluetooth device picked by * user is connected. * - * @return {Promise} + * @return {Promise} */ _connectToDevice: function() { - if (this._server && this._server.connected) { - // Resolve promise if device is already connected. - return Promise.resolve(this._server); - } if (!this._device) { return Promise.reject(new Error('Bluetooth device is not connected.')); } @@ -305,14 +301,9 @@ * Returns a promise that will resolve when Bluetooth GATT Primary * Service is discovered. * - * @return {Promise} + * @return {Promise} */ _getPrimaryService: function() { - if (this._server && this._server.connected && this._service && - this._service.uuid === BluetoothUUID.getService(this.service)) { - // Resolve promise if primary service is already discovered. - return Promise.resolve(this._service); - } if (!this._server || !this._server.connected) { return Promise.reject(new Error('Bluetooth GATT Remote server is not connected.')); } @@ -331,14 +322,9 @@ * Returns a promise that will resolve when Bluetooth GATT Characteristic * is discovered. * - * @return {Promise} + * @return {Promise} */ _getCharacteristic: function() { - if (this._characteristic && - this._characteristic.uuid === BluetoothUUID.getCharacteristic(this.characteristic)) { - // Resolve promise if characteristic is already _. - return Promise.resolve(this._characteristic); - } if (!this._service) { return Promise.reject(new Error('Bluetooth GATT Primary Service is not connected.')); } @@ -367,8 +353,6 @@ var self = this; return this._characteristic.readValue() .then(function(value) { - // In Chrome 50+, a DataView is returned instead of an ArrayBuffer. - value = value.buffer ? value : new DataView(value); self.value = value; return self.value; }); @@ -392,8 +376,7 @@ * Save value when characteristic value changed in a notification session. **/ _handleValueChanged: function(event) { - // In Chrome 50+, a DataView is returned instead of an ArrayBuffer. - this.value = event.target.value.buffer ? event.target.value : new DataView(event.target.value); + this.value = event.target.value; }, /** diff --git a/lib/platinum-bluetooth/platinum-bluetooth-device.html b/lib/platinum-bluetooth/platinum-bluetooth-device.html index 52f4bb1b..b1442d7c 100644 --- a/lib/platinum-bluetooth/platinum-bluetooth-device.html +++ b/lib/platinum-bluetooth/platinum-bluetooth-device.html @@ -160,12 +160,22 @@ */ device: { type: BluetoothDevice, + notify: true, readOnly: true, observer: '_deviceChanged' } }, + + /** + * Fired when Bluetooth device picked by user gets updated. + * + * @event device-changed + * @param {BluetoothDevice} The device + */ + + /** * Update all services when device changes. */ diff --git a/lib/polymer/.bower.json b/lib/polymer/.bower.json index b60c3598..fb5c5ace 100644 --- a/lib/polymer/.bower.json +++ b/lib/polymer/.bower.json @@ -1,6 +1,6 @@ { "name": "polymer", - "version": "1.6.1", + "version": "1.7.0", "main": [ "polymer.html", "polymer-mini.html", @@ -33,13 +33,13 @@ }, "private": true, "homepage": "https://github.com/Polymer/polymer", - "_release": "1.6.1", + "_release": "1.7.0", "_resolution": { "type": "version", - "tag": "v1.6.1", - "commit": "1f197d9d7874b1e5808b2a5c26f34446a7d912fc" + "tag": "v1.7.0", + "commit": "43f094996410368cc29b429d0bea689933486934" }, "_source": "git://github.com/Polymer/polymer.git", - "_target": "^1.2.4", + "_target": "^1.6.0", "_originalSource": "Polymer/polymer" } \ No newline at end of file diff --git a/lib/polymer/bower.json b/lib/polymer/bower.json index f0b22f06..0dd998c1 100644 --- a/lib/polymer/bower.json +++ b/lib/polymer/bower.json @@ -1,6 +1,6 @@ { "name": "polymer", - "version": "1.6.1", + "version": "1.7.0", "main": [ "polymer.html", "polymer-mini.html", diff --git a/lib/polymer/build.log b/lib/polymer/build.log index 149dff6f..b10d62f5 100644 --- a/lib/polymer/build.log +++ b/lib/polymer/build.log @@ -1,117 +1,127 @@ BUILD LOG --------- -Build Time: 2016-08-01T11:30:14-0700 +Build Time: 2016-09-28T12:22:02-0700 NODEJS INFORMATION ================== -nodejs: v6.3.1 -abbrev: 1.0.7 +nodejs: v6.6.0 +abbrev: 1.0.9 accepts: 1.3.3 -accessibility-developer-tools: 2.10.0 +accessibility-developer-tools: 2.11.0 +acorn: 4.0.3 acorn-jsx: 3.0.1 adm-zip: 0.4.7 after: 0.8.1 +ajv-keywords: 1.1.1 +ajv: 4.7.4 agent-base: 2.0.1 -align-text: 0.1.4 amdefine: 1.0.0 ansi-cyan: 0.1.1 ansi-escapes: 1.4.0 +align-text: 0.1.4 ansi-red: 0.1.1 ansi-regex: 2.0.0 -ansi-styles: 2.2.0 +ansi-styles: 2.2.1 ansi-wrap: 0.1.0 append-field: 0.1.0 -archiver: 0.14.4 archy: 1.0.0 argparse: 1.0.7 -arr-diff: 1.1.0 arr-flatten: 1.0.1 arr-union: 2.1.0 array-differ: 1.0.0 -array-find-index: 1.0.1 +arr-diff: 2.0.0 +archiver: 0.14.4 array-flatten: 1.1.1 +array-find-index: 1.0.1 array-slice: 0.2.3 +array-uniq: 1.0.3 array-union: 1.0.2 -array-uniq: 1.0.2 arraybuffer.slice: 0.0.6 +array-unique: 0.2.1 arrify: 1.0.1 -asap: 2.0.3 +asap: 2.0.5 asn1: 0.1.11 assert-plus: 0.1.5 -assertion-error: 1.0.2 async: 0.9.2 +asynckit: 0.4.0 aws-sign2: 0.5.0 +assertion-error: 1.0.2 +babel-polyfill: 6.13.0 aws4: 1.4.1 -babel-polyfill: 6.7.2 -babel-regenerator-runtime: 6.5.0 -babel-runtime: 5.8.35 -backo2: 1.0.2 +babel-runtime: 6.11.6 backoff: 2.5.0 -balanced-match: 0.3.0 -base64-js: 0.0.8 +balanced-match: 0.4.2 +backo2: 1.0.2 base64-arraybuffer: 0.1.2 +base64-js: 1.1.2 base64id: 0.1.0 +bcrypt-pbkdf: 1.0.0 beeper: 1.1.0 benchmark: 1.0.0 +binaryextensions: 1.0.1 better-assert: 1.0.2 -binaryextensions: 1.0.0 -bl: 0.9.5 blob: 0.0.4 -bluebird: 3.4.1 +bluebird: 2.11.0 +bl: 0.9.5 body-parser: 1.15.2 boom: 0.4.2 +brace-expansion: 1.1.6 +braces: 1.8.5 boxen: 0.3.1 -brace-expansion: 1.1.3 -browserstack: 1.5.0 buffer-crc32: 0.2.5 +buffer-shims: 1.0.0 bufferstreams: 1.1.1 -builtin-modules: 1.1.1 +browserstack: 1.5.0 +bunyan: 1.8.1 busboy: 0.2.13 bytes: 2.4.0 caller-path: 0.1.0 callsite: 1.0.0 callsites: 0.2.0 camelcase: 2.1.1 +builtin-modules: 1.1.1 camelcase-keys: 2.1.0 capture-stack-trace: 1.0.0 caseless: 0.8.0 center-align: 0.1.3 -chai: 3.5.0 -chalk: 1.1.1 +chalk: 1.1.3 circular-json: 0.3.1 cleankill: 1.0.3 -cli-cursor: 1.0.2 +chai: 3.5.0 cli-width: 2.1.0 cliui: 2.1.0 clone: 1.0.2 clone-stats: 0.0.1 +co: 4.6.0 +cli-cursor: 1.0.2 code-point-at: 1.0.0 -color-convert: 1.0.0 combined-stream: 0.0.7 -commander: 2.3.0 component-bind: 1.0.0 component-emitter: 1.1.2 -component-inherit: 0.0.3 +commander: 2.3.0 compress-commons: 0.2.9 concat-map: 0.0.1 -concat-stream: 1.5.1 -configstore: 2.0.0 +concat-stream: 1.5.2 +component-inherit: 0.0.3 content-disposition: 0.5.1 -content-type: 1.0.2 cookie: 0.3.1 +content-type: 1.0.2 cookie-signature: 1.0.6 -core-js: 2.2.0 +core-js: 2.4.1 core-util-is: 1.0.2 crc: 3.2.1 +configstore: 2.1.0 +create-error-class: 3.0.2 crc32-stream: 0.3.4 -create-error-class: 2.0.1 -cryptiles: 0.2.2 csv: 0.4.6 csv-generate: 0.0.6 csv-parse: 1.1.7 csv-stringify: 0.0.8 +cryptiles: 0.2.2 ctype: 0.5.3 +currently-unhandled: 0.4.1 d: 0.1.1 +dateformat: 1.0.12 dashdash: 1.14.0 debug: 2.2.0 debuglog: 1.0.1 @@ -120,180 +130,213 @@ deep-eql: 0.1.3 deep-extend: 0.4.1 deep-is: 0.1.3 defaults: 1.0.3 -del: 2.2.1 -delayed-stream: 0.0.5 +del: 2.2.2 depd: 1.1.0 deprecated: 0.0.1 +delayed-stream: 0.0.5 destroy: 1.0.4 +detect-file: 0.1.0 dezalgo: 1.0.3 dicer: 0.2.5 diff: 1.4.0 -doctrine: 1.2.2 -dom-serializer: 0.1.0 -dom5: 1.3.1 +doctrine: 1.4.0 +dom5: 1.3.6 domelementtype: 1.3.0 domhandler: 2.3.0 +dom-serializer: 0.1.0 domutils: 1.5.1 -dot-prop: 2.4.0 dtrace-provider: 0.6.0 duplexer: 0.1.1 duplexer2: 0.0.2 ecc-jsbn: 0.1.1 ee-first: 1.1.1 -encodeurl: 1.0.1 +dot-prop: 3.0.0 end-of-stream: 0.1.5 engine.io: 1.6.11 +encodeurl: 1.0.1 engine.io-client: 1.6.11 engine.io-parser: 1.2.4 entities: 1.1.1 +es5-ext: 0.10.12 error-ex: 1.3.0 -es5-ext: 0.10.11 -es6-iterator: 2.0.0 es6-map: 0.1.4 es6-promise: 2.3.0 es6-set: 0.1.4 -es6-symbol: 3.0.2 +es6-symbol: 3.1.0 es6-weak-map: 2.0.1 +es6-iterator: 2.0.0 escape-html: 1.0.3 -escape-regexp-component: 1.0.2 escape-string-regexp: 1.0.5 +escodegen: 1.8.1 escope: 3.6.0 -eslint-plugin-html: 1.5.1 -espree: 3.1.7 +eslint: 3.6.1 +escape-regexp-component: 1.0.2 +eslint-plugin-html: 1.5.3 +espree: 3.3.1 esrecurse: 4.1.0 estraverse: 4.2.0 esutils: 2.0.2 etag: 1.7.0 -event-emitter: 0.3.4 +esprima: 2.7.3 exit-hook: 1.1.1 +event-emitter: 0.3.4 +expand-range: 1.8.2 +expand-tilde: 1.2.2 express: 4.14.0 -extend: 2.0.1 +expand-brackets: 0.1.5 extend-shallow: 1.1.4 +extend: 3.0.0 extsprintf: 1.2.0 +extglob: 0.3.2 fancy-log: 1.2.0 -fast-levenshtein: 1.1.3 +fast-levenshtein: 2.0.4 fd-slicer: 1.0.1 -figures: 1.7.0 -file-entry-cache: 1.3.1 +file-entry-cache: 2.0.0 +filename-regex: 2.0.0 +fill-range: 2.2.3 filled-array: 1.1.0 -find-index: 0.1.1 finalhandler: 0.5.0 +find-index: 0.1.1 find-up: 1.1.2 +figures: 1.7.0 +findup-sync: 0.4.2 +fined: 1.0.1 first-chunk-stream: 1.0.0 -findup-sync: 0.3.0 -flagged-respawn: 0.3.1 -forever-agent: 0.5.2 +flagged-respawn: 0.3.2 flat-cache: 1.2.1 +for-own: 0.1.4 +forever-agent: 0.5.2 +for-in: 0.1.6 form-data: 0.2.0 formatio: 1.1.1 formidable: 1.0.17 forwarded: 0.1.0 -freeport: 1.0.5 fresh: 0.3.0 -fs.realpath: 1.0.0 +freeport: 1.0.5 gaze: 0.5.2 +fs.realpath: 1.0.0 generate-function: 2.0.0 generate-object-property: 1.2.0 -get-stdin: 4.0.1 +fs-exists-sync: 0.1.0 getpass: 0.1.6 github-url-from-git: 1.4.0 github-url-from-username-repo: 1.0.2 -glob: 7.0.5 +glob: 7.1.0 +get-stdin: 4.0.1 +glob-base: 0.3.0 +glob-parent: 2.0.0 glob-stream: 3.1.18 glob-watcher: 0.0.6 glob2base: 0.0.12 -globals: 9.9.0 +global-modules: 0.2.3 +globals: 9.10.0 globby: 5.0.0 globule: 0.1.0 +global-prefix: 0.1.4 glogg: 1.0.0 -got: 5.5.0 -graceful-fs: 4.1.3 +got: 5.6.0 +graceful-fs: 4.1.8 graceful-readlink: 1.0.1 growl: 1.9.2 +gulp: 3.9.1 gulp-audit: 1.0.0 -gulp-eslint: 2.1.0 +gulp-eslint: 3.0.1 gulp-rename: 1.2.2 gulp-replace: 0.5.4 gulp-util: 3.0.7 gulp-vulcanize: 6.1.0 -gulplog: 1.0.0 -handle-thing: 1.2.4 +handle-thing: 1.2.5 +har-validator: 2.0.6 has-ansi: 2.0.0 +gulplog: 1.0.0 has-binary: 0.1.7 has-color: 0.1.7 has-cors: 1.1.0 has-gulplog: 0.1.0 hoek: 0.9.1 -hpack.js: 2.1.4 -htmlparser2: 3.9.1 -hosted-git-info: 2.1.4 +hosted-git-info: 2.1.5 hawk: 1.1.1 +hpack.js: 2.1.6 +htmlparser2: 3.9.1 http-deceiver: 1.2.7 -http-errors: 1.5.0 http-signature: 0.11.0 -https-proxy-agent: 1.0.0 -hydrolysis: 1.23.1 +http-errors: 1.5.0 +hydrolysis: 1.24.1 iconv-lite: 0.4.13 -ignore: 3.1.3 +ignore: 3.1.5 imurmurhash: 0.1.4 -indent-string: 2.1.0 +https-proxy-agent: 1.0.0 indexof: 0.0.1 -inflight: 1.0.4 -inherits: 2.0.1 +inflight: 1.0.5 +inherits: 2.0.3 ini: 1.3.4 inquirer: 0.12.0 -interpret: 1.0.0 -ipaddr.js: 1.1.1 -is-absolute: 0.1.7 +indent-string: 2.1.0 +interpret: 1.0.1 +is-absolute: 0.2.5 is-arrayish: 0.2.1 -is-buffer: 1.1.3 +is-buffer: 1.1.4 is-builtin-module: 1.0.0 +is-dotfile: 1.0.2 +is-equal-shallow: 0.1.3 +is-extendable: 0.1.1 +is-extglob: 1.0.0 is-finite: 1.0.1 is-fullwidth-code-point: 1.0.0 -is-my-json-valid: 2.13.1 +is-glob: 2.0.1 +ipaddr.js: 1.1.1 +is-my-json-valid: 2.14.0 is-npm: 1.0.0 -is-obj: 1.0.0 -is-path-cwd: 1.0.0 +is-number: 2.1.0 +is-obj: 1.0.1 is-path-in-cwd: 1.0.0 is-path-inside: 1.0.0 is-plain-obj: 1.1.0 +is-path-cwd: 1.0.0 +is-posix-bracket: 0.1.1 +is-primitive: 2.0.0 is-property: 1.0.2 is-redirect: 1.0.0 -is-relative: 0.1.3 +is-relative: 0.2.1 is-resolvable: 1.0.0 -is-retry-allowed: 1.0.0 -is-stream: 1.0.1 +is-retry-allowed: 1.1.0 is-typedarray: 1.0.0 +is-stream: 1.1.0 +is-unc-path: 0.1.1 is-utf8: 0.2.1 +is-windows: 0.2.0 isarray: 1.0.0 isexe: 1.1.2 +isobject: 2.1.0 isstream: 0.1.2 istextorbinary: 1.0.2 +jade: 0.26.3 jju: 1.3.0 +js-yaml: 3.6.1 jodid25519: 1.0.2 jsbn: 0.1.0 json-parse-helpfulerror: 1.0.3 -json-schema: 0.2.2 +json-schema: 0.2.3 json-stable-stringify: 1.0.1 json-stringify-safe: 5.0.1 -json3: 3.2.6 jsonify: 0.0.0 jsonpointer: 2.0.0 -jsprim: 1.3.0 +jsprim: 1.3.1 +json3: 3.2.6 keep-alive-agent: 0.0.1 -kind-of: 1.1.0 +kind-of: 3.0.4 latest-version: 2.0.0 -launchpad: 0.5.3 -lazy-cache: 1.0.3 +lazy-cache: 1.0.4 lazypipe: 1.0.1 lazystream: 0.1.0 levn: 0.3.0 -liftoff: 2.2.0 +liftoff: 2.3.0 load-json-file: 1.1.0 lodash: 1.0.2 lodash._basecopy: 3.0.1 lodash._basetostring: 3.0.1 lodash._basevalues: 3.0.0 +launchpad: 0.5.4 lodash._getnative: 3.9.1 lodash._isiterateecall: 3.0.9 lodash._reescape: 3.0.0 @@ -301,56 +344,76 @@ lodash._reevaluate: 3.0.0 lodash._reinterpolate: 3.0.0 lodash._root: 3.0.1 lodash.escape: 3.2.0 -lodash.isarguments: 3.0.8 +lodash.isarguments: 3.1.0 lodash.isarray: 3.0.4 +lodash.isempty: 4.4.0 +lodash.assignwith: 4.2.0 +lodash.isstring: 4.0.1 lodash.keys: 3.1.2 +lodash.mapvalues: 4.6.0 +lodash.pick: 4.4.0 lodash.restparam: 3.6.1 lodash.template: 3.6.2 -lodash.templatesettings: 3.1.1 lolex: 1.3.2 +lodash.templatesettings: 3.1.1 +lodash.isplainobject: 4.0.6 longest: 1.0.1 -loud-rejection: 1.3.0 +loud-rejection: 1.6.0 lowercase-keys: 1.0.0 lru-cache: 2.7.3 +map-cache: 0.2.2 map-obj: 1.0.1 media-typer: 0.3.0 -meow: 3.7.0 merge-descriptors: 1.0.1 methods: 1.1.2 -mime-db: 1.23.0 -mime-types: 2.1.11 +meow: 3.7.0 +micromatch: 2.3.11 +mime: 1.3.4 +mime-db: 1.24.0 +mime-types: 2.1.12 minimalistic-assert: 1.0.0 -minimatch: 3.0.0 +minimatch: 3.0.3 minimist: 1.2.0 -moment: 2.14.1 +mkdirp: 0.5.1 ms: 0.7.1 +moment: 2.15.1 +multer: 1.2.0 multipipe: 0.1.2 -multer: 1.1.0 -mute-stream: 0.0.5 +mocha: 2.5.3 mv: 2.1.1 +mute-stream: 0.0.5 +natives: 1.1.0 nan: 2.4.0 +natural-compare: 1.4.0 negotiator: 0.6.1 node-int64: 0.3.3 +ncp: 2.0.0 +node-uuid: 1.4.7 node-status-codes: 1.0.0 nodegit-promise: 4.0.0 nomnom: 1.8.1 -normalize-package-data: 2.3.5 +nopt: 3.0.6 +normalize-path: 2.0.1 number-is-nan: 1.0.0 oauth-sign: 0.5.0 -object-assign: 4.0.1 +object-assign: 4.1.0 object-component: 0.0.3 +normalize-package-data: 2.3.5 +object.omit: 2.0.0 obuf: 1.1.1 on-finished: 2.3.0 -once: 1.3.3 +once: 1.4.0 onetime: 1.1.0 -optionator: 0.8.1 +optionator: 0.8.2 options: 0.0.6 orchestrator: 0.3.7 ordered-read-streams: 0.1.0 os-homedir: 1.0.1 os-tmpdir: 1.0.1 +package-json: 2.4.0 osenv: 0.1.3 -package-json: 2.3.1 +parse-filepath: 1.0.1 +parse-glob: 3.0.4 parse-json: 2.2.0 parse5: 1.5.1 parsejson: 0.0.1 @@ -359,204 +422,205 @@ parseuri: 0.0.4 parseurl: 1.3.1 path-exists: 2.1.0 path-is-absolute: 1.0.0 -path-is-inside: 1.0.1 +path-is-inside: 1.0.2 path-posix: 1.0.0 -path-to-regexp: 0.1.7 +path-root: 0.1.1 +path-root-regex: 0.1.2 path-type: 1.1.0 pend: 1.2.0 pify: 2.3.0 pinkie: 2.0.4 -pinkie-promise: 2.0.0 -plist: 1.2.0 +pinkie-promise: 2.0.1 +plist: 2.0.1 +path-to-regexp: 0.1.7 plugin-error: 0.1.2 pluralize: 1.2.1 -polyclean: 1.3.1 precond: 0.2.3 prelude-ls: 1.1.2 -prepend-http: 1.0.3 +prepend-http: 1.0.4 +preserve: 0.2.0 +polyclean: 1.3.1 pretty-hrtime: 1.0.2 -process-nextick-args: 1.0.6 -progress: 1.1.8 +process-nextick-args: 1.0.7 promisify-node: 0.4.0 -proxy-addr: 1.1.2 +progress: 1.1.8 pseudomap: 1.0.2 -q: 1.4.1 +proxy-addr: 1.1.2 qs: 6.2.0 +randomatic: 1.1.5 range-parser: 1.2.0 +rc: 1.1.6 raw-body: 2.1.7 read-all-stream: 3.1.0 read-installed: 3.1.5 read-package-json: 1.3.3 read-pkg: 1.1.0 read-pkg-up: 1.0.1 -readable-stream: 2.0.6 +readable-stream: 2.1.5 readdir-scoped-modules: 1.0.2 readline2: 1.0.1 +q: 1.4.1 rechoir: 0.6.2 redent: 1.0.0 -registry-url: 3.0.3 +regenerator-runtime: 0.9.5 +regex-cache: 0.4.3 +registry-auth-token: 3.0.1 +registry-url: 3.1.0 +repeat-element: 1.1.2 repeat-string: 1.5.4 -repeating: 2.0.0 +repeating: 2.0.1 replace-ext: 0.0.1 -replacestream: 4.0.0 +replacestream: 4.0.2 request: 2.51.0 require-uncached: 1.0.2 resolve: 1.1.7 +resolve-dir: 0.1.1 resolve-from: 1.0.1 -restore-cursor: 1.0.1 +restify: 4.1.1 right-align: 0.1.3 -run-async: 0.1.0 +restore-cursor: 1.0.1 +rimraf: 2.5.4 run-sequence: 1.2.2 +run-async: 0.1.0 safe-json-stringify: 1.0.3 rx-lite: 3.1.2 samsam: 1.1.2 -sauce-connect-launcher: 0.14.0 select-hose: 2.0.0 -semver-diff: 2.1.0 +sauce-connect-launcher: 0.14.0 +semver: 4.3.6 +selenium-standalone: 5.7.2 send: 0.11.1 sequencify: 0.0.7 +semver-diff: 2.1.0 serve-static: 1.11.1 serve-waterfall: 1.1.1 server-destroy: 1.0.1 setprototypeof: 1.0.1 sigmund: 1.0.1 -signal-exit: 2.1.2 -sinon: 1.17.5 +shelljs: 0.6.1 +sinon: 1.17.6 sinon-chai: 2.8.0 -slice-ansi: 0.0.4 +signal-exit: 3.0.1 slide: 1.1.6 +slice-ansi: 0.0.4 sntp: 0.2.4 -socket.io: 1.4.8 socket.io-adapter: 0.4.0 -socket.io-parser: 2.2.6 +socket.io-client: 1.4.8 +socket.io: 1.4.8 source-map: 0.2.0 sparkles: 1.0.0 spdx-correct: 1.0.2 -spdx-exceptions: 1.0.4 -spdx-expression-parse: 1.0.2 -socket.io-client: 1.4.8 -spdx-license-ids: 1.2.0 -spdy: 3.3.4 -spdy-transport: 2.0.11 +spdx-expression-parse: 1.0.3 +spdx-license-ids: 1.2.2 +socket.io-parser: 2.2.6 +spdy-transport: 2.0.15 sprintf-js: 1.0.3 +sshpk: 1.10.0 +spdy: 3.4.2 stacky: 1.3.1 statuses: 1.3.0 stream-combiner: 0.2.2 stream-consume: 0.1.0 stream-transform: 0.1.1 +string-width: 1.0.2 streamsearch: 0.1.2 -string-width: 1.0.1 string_decoder: 0.10.31 -stringstream: 0.0.5 strip-ansi: 3.0.1 +stringstream: 0.0.5 strip-bom: 2.0.0 +strip-indent: 1.0.1 +strip-json-comments: 1.0.4 supports-color: 2.0.0 -table: 3.7.8 -tar-stream: 1.1.5 +tar-stream: 1.5.2 temp: 0.8.3 test-fixture: 1.1.1 text-table: 0.2.0 -textextensions: 1.0.1 +textextensions: 1.0.2 through: 2.3.8 through2: 2.0.1 -tildify: 1.1.2 -time-stamp: 1.0.0 +tildify: 1.2.0 +time-stamp: 1.0.1 timed-out: 2.0.0 to-array: 0.1.4 -to-iso-string: 0.0.2 +table: 3.8.0 tough-cookie: 2.3.1 trim-newlines: 1.0.0 +to-iso-string: 0.0.2 tryit: 1.0.2 tunnel-agent: 0.4.3 -tv4: 1.2.7 -tweetnacl: 0.13.3 type-check: 0.3.2 +tweetnacl: 0.13.3 type-detect: 1.0.0 type-is: 1.6.13 typedarray: 0.0.6 +uglify-js: 2.7.3 uglify-to-browserify: 1.0.2 ultron: 1.0.2 +unc-path-regex: 0.1.2 underscore: 1.6.0 -underscore.string: 3.0.3 unique-stream: 1.0.0 unpipe: 1.0.0 -unzip-response: 1.0.0 +unzip-response: 1.0.1 +underscore.string: 3.0.3 update-notifier: 0.6.3 -urijs: 1.16.1 url-parse-lax: 1.0.0 -utf8: 2.1.0 +user-home: 1.1.1 +urijs: 1.16.1 util: 0.10.3 util-deprecate: 1.0.2 util-extend: 1.0.3 +utf8: 2.1.0 utils-merge: 1.0.0 -uuid: 2.0.1 +uuid: 2.0.3 v8flags: 2.0.11 validate-npm-package-license: 3.0.1 vargs: 0.1.0 vary: 1.1.0 vasync: 1.6.3 -verror: 1.6.1 +verror: 1.8.1 vinyl: 0.5.3 vinyl-fs: 0.3.14 +vulcanize: 1.14.8 +wct-local: 2.0.11 wbuf: 1.7.2 -wct-local: 2.0.8 -wct-sauce: 1.8.4 +wd: 0.3.12 +web-component-tester: 4.3.4 +which: 1.2.11 widest-line: 1.0.0 window-size: 0.1.0 wordwrap: 1.0.0 -wrappy: 1.0.1 +wrappy: 1.0.2 write: 0.2.1 -write-file-atomic: 1.1.4 +write-file-atomic: 1.2.0 +wct-sauce: 1.8.4 ws: 1.1.0 xdg-basedir: 2.0.0 -xmlbuilder: 4.0.0 -xmldom: 0.1.22 +xmlbuilder: 8.2.2 xmlhttprequest-ssl: 1.5.1 -xregexp: 3.1.1 +xmldom: 0.1.22 xtend: 4.0.1 yallist: 2.0.0 yargs: 3.10.0 yauzl: 2.6.0 yeast: 0.1.2 zip-stream: 0.5.2 -acorn: 3.3.0 -bunyan: 1.8.1 -dateformat: 1.0.12 -escodegen: 1.8.0 -eslint: 2.13.1 -esprima: 2.7.2 -gulp: 3.9.1 -har-validator: 2.0.6 -jade: 0.26.3 -js-yaml: 3.6.1 -mime: 1.3.4 -mkdirp: 0.5.1 -mocha: 2.5.3 -ncp: 2.0.0 -node-uuid: 1.4.7 -nopt: 3.0.6 -rc: 1.1.6 -restify: 4.1.1 -rimraf: 2.5.4 -selenium-standalone: 5.5.0 -semver: 4.3.6 -shelljs: 0.6.0 -sshpk: 1.9.2 -strip-indent: 1.0.1 -strip-json-comments: 1.0.4 -uglify-js: 2.6.2 -user-home: 1.1.1 -vulcanize: 1.14.7 -wd: 0.3.12 -web-component-tester: 4.3.1 -which: 1.2.10 +@types/chalk: 0.4.30 +@types/express: 4.0.33 +@types/clone: 0.1.30 +@types/freeport: 1.0.20 +@types/mime: 0.0.29 +@types/node: 4.0.30 +@types/express-serve-static-core: 4.0.36 +@types/parse5: 0.0.31 +@types/serve-static: 1.7.31 +@types/which: 1.0.28 REPO REVISIONS ============== -polymer: 4abd53c716e32de2bbac4f87f5b01ce007119f04 +polymer: e6ad8c92edf8ea2de18cc49d868360c89ed032c7 BUILD HASHES ============ polymer-mini.html: 7b55678ec0ca21f4a1af9423262f367d87a9b739 -polymer-micro.html: ff9824cb1fb68b011f3fe0de7b54474e65b52da7 -polymer.html: 2df3f2cd58aef56f63fc472e70c61d646adf801e \ No newline at end of file +polymer-micro.html: 70d9d3d40db1fdc42d933a0fca275b9bd4bbd64f +polymer.html: bcd7bc9cc9f3dbc6dbb112a55447201b0822f01d \ No newline at end of file diff --git a/lib/polymer/polymer-micro.html b/lib/polymer/polymer-micro.html index c1012591..42461228 100644 --- a/lib/polymer/polymer-micro.html +++ b/lib/polymer/polymer-micro.html @@ -700,7 +700,7 @@ return value != null ? value : undefined; } } -});Polymer.version = "1.6.1";Polymer.Base._addFeature({ +});Polymer.version = "1.7.0";Polymer.Base._addFeature({ _registerFeatures: function () { this._prepIs(); this._prepBehaviors(); diff --git a/lib/polymer/polymer.html b/lib/polymer/polymer.html index 8a6f3276..1cbf2dcc 100644 --- a/lib/polymer/polymer.html +++ b/lib/polymer/polymer.html @@ -136,6 +136,9 @@ if (node.localName === 'template' && !node.hasAttribute('preserve-content')) { this._parseTemplate(node, i, list, annote); } +if (node.localName == 'slot') { +node = this._replaceSlotWithContent(node); +} if (node.nodeType === Node.TEXT_NODE) { var n = next; while (n && n.nodeType === Node.TEXT_NODE) { @@ -161,6 +164,22 @@ } } }, +_replaceSlotWithContent: function (slot) { +var content = slot.ownerDocument.createElement('content'); +while (slot.firstChild) { +content.appendChild(slot.firstChild); +} +var attrs = slot.attributes; +for (var i = 0; i < attrs.length; i++) { +var attr = attrs[i]; +content.setAttribute(attr.name, attr.value); +} +var name = slot.getAttribute('name'); +var select = name ? '[slot=\'' + name + '\']' : ':not([slot])'; +content.setAttribute('select', select); +slot.parentNode.replaceChild(content, slot); +return content; +}, _parseTemplate: function (node, index, list, parent) { var content = document.createDocumentFragment(); content._notes = this.parseAnnotations(node); @@ -294,7 +313,30 @@ resolveAttrs: resolveAttrs, resolveUrl: resolveUrl }; -}());Polymer.Base._addFeature({ +}());Polymer.Path = { +root: function (path) { +var dotIndex = path.indexOf('.'); +if (dotIndex === -1) { +return path; +} +return path.slice(0, dotIndex); +}, +isDeep: function (path) { +return path.indexOf('.') !== -1; +}, +isAncestor: function (base, path) { +return base.indexOf(path + '.') === 0; +}, +isDescendant: function (base, path) { +return path.indexOf(base + '.') === 0; +}, +translate: function (base, newBase, path) { +return newBase + path.slice(base.length); +}, +matches: function (base, wildcard, path) { +return base === path || this.isAncestor(base, path) || Boolean(wildcard) && this.isDescendant(base, path); +} +};Polymer.Base._addFeature({ _prepAnnotations: function () { if (!this._template) { this._notes = []; @@ -324,7 +366,7 @@ if (signature) { p.signature = signature; } else { -p.model = this._modelForPath(p.value); +p.model = Polymer.Path.root(p.value); } } } @@ -587,8 +629,9 @@ } }; function setupTeardownMouseCanceller(setup) { -for (var i = 0, en; i < MOUSE_EVENTS.length; i++) { -en = MOUSE_EVENTS[i]; +var events = IS_TOUCH_ONLY ? ['click'] : MOUSE_EVENTS; +for (var i = 0, en; i < events.length; i++) { +en = events[i]; if (setup) { document.addEventListener(en, mouseCanceller, true); } else { @@ -597,9 +640,6 @@ } } function ignoreMouse() { -if (IS_TOUCH_ONLY) { -return; -} if (!POINTERSTATE.mouse.mouseIgnoreJob) { setupTeardownMouseCanceller(true); } @@ -792,7 +832,7 @@ } for (var i = 0, dep, gd; i < deps.length; i++) { dep = deps[i]; -if (IS_TOUCH_ONLY && MOUSE_EVENTS.indexOf(dep) > -1) { +if (IS_TOUCH_ONLY && MOUSE_EVENTS.indexOf(dep) > -1 && dep !== 'click') { continue; } gd = gobj[dep]; @@ -1451,7 +1491,7 @@ }, _clearPath: function (path) { for (var prop in this.__data__) { -if (prop.indexOf(path + '.') === 0) { +if (Polymer.Path.isDescendant(path, prop)) { this.__data__[prop] = undefined; } } @@ -1528,7 +1568,7 @@ if (!model._bindListeners) { model._bindListeners = []; } -var fn = this._notedListenerFactory(property, path, this._isStructured(path), negated); +var fn = this._notedListenerFactory(property, path, Polymer.Path.isDeep(path), negated); var eventName = event || Polymer.CaseMap.camelToDashCase(property) + '-changed'; model._bindListeners.push({ index: index, @@ -1538,16 +1578,14 @@ event: eventName }); }, -_isStructured: function (path) { -return path.indexOf('.') > 0; -}, _isEventBogus: function (e, target) { return e.path && e.path[0] !== target; }, _notedListenerFactory: function (property, path, isStructured, negated) { return function (target, value, targetPath) { if (targetPath) { -this._notifyPath(this._fixPath(path, property, targetPath), value); +var newPath = Polymer.Path.translate(property, path, targetPath); +this._notifyPath(newPath, value); } else { value = target[property]; if (negated) { @@ -1669,7 +1707,7 @@ return; } if (arg.wildcard) { -var matches = path.indexOf(name + '.') === 0; +var matches = Polymer.Path.isAncestor(path, name); values[i] = { path: matches ? path : name, value: matches ? value : v, @@ -1896,8 +1934,8 @@ break; } if (!a.literal) { -a.model = this._modelForPath(arg); -a.structured = arg.indexOf('.') > 0; +a.model = Polymer.Path.root(arg); +a.structured = Polymer.Path.isDeep(arg); if (a.structured) { a.wildcard = arg.slice(-2) == '.*'; if (a.wildcard) { @@ -2087,6 +2125,7 @@ }); }());(function () { 'use strict'; +var Path = Polymer.Path; Polymer.Base._addFeature({ notifyPath: function (path, value, fromAbove) { var info = {}; @@ -2194,7 +2233,7 @@ return prop; }, _pathEffector: function (path, value) { -var model = this._modelForPath(path); +var model = Path.root(path); var fx$ = this._propertyEffects && this._propertyEffects[model]; if (fx$) { for (var i = 0, fx; i < fx$.length && (fx = fx$[i]); i++) { @@ -2209,35 +2248,31 @@ } }, _annotationPathEffect: function (path, value, effect) { -if (effect.value === path || effect.value.indexOf(path + '.') === 0) { +if (Path.matches(effect.value, false, path)) { Polymer.Bind._annotationEffect.call(this, path, value, effect); -} else if (path.indexOf(effect.value + '.') === 0 && !effect.negate) { +} else if (!effect.negate && Path.isDescendant(effect.value, path)) { var node = this._nodes[effect.index]; if (node && node._notifyPath) { -var p = this._fixPath(effect.name, effect.value, path); -node._notifyPath(p, value, true); +var newPath = Path.translate(effect.value, effect.name, path); +node._notifyPath(newPath, value, true); } } }, _complexObserverPathEffect: function (path, value, effect) { -if (this._pathMatchesEffect(path, effect)) { +if (Path.matches(effect.trigger.name, effect.trigger.wildcard, path)) { Polymer.Bind._complexObserverEffect.call(this, path, value, effect); } }, _computePathEffect: function (path, value, effect) { -if (this._pathMatchesEffect(path, effect)) { +if (Path.matches(effect.trigger.name, effect.trigger.wildcard, path)) { Polymer.Bind._computeEffect.call(this, path, value, effect); } }, _annotatedComputationPathEffect: function (path, value, effect) { -if (this._pathMatchesEffect(path, effect)) { +if (Path.matches(effect.trigger.name, effect.trigger.wildcard, path)) { Polymer.Bind._annotatedComputationEffect.call(this, path, value, effect); } }, -_pathMatchesEffect: function (path, effect) { -var effectArg = effect.trigger.name; -return effectArg == path || effectArg.indexOf(path + '.') === 0 || effect.trigger.wildcard && path.indexOf(effectArg + '.') === 0; -}, linkPaths: function (to, from) { this._boundPaths = this._boundPaths || {}; if (from) { @@ -2254,18 +2289,15 @@ _notifyBoundPaths: function (path, value) { for (var a in this._boundPaths) { var b = this._boundPaths[a]; -if (path.indexOf(a + '.') == 0) { -this._notifyPath(this._fixPath(b, a, path), value); -} else if (path.indexOf(b + '.') == 0) { -this._notifyPath(this._fixPath(a, b, path), value); +if (Path.isDescendant(a, path)) { +this._notifyPath(Path.translate(a, b, path), value); +} else if (Path.isDescendant(b, path)) { +this._notifyPath(Path.translate(b, a, path), value); } } }, -_fixPath: function (property, root, path) { -return property + path.slice(root.length); -}, _notifyPathUp: function (path, value) { -var rootName = this._modelForPath(path); +var rootName = Path.root(path); var dashCaseName = Polymer.CaseMap.camelToDashCase(rootName); var eventName = dashCaseName + this._EVENT_CHANGED; this.fire(eventName, { @@ -2276,10 +2308,6 @@ _useCache: true }); }, -_modelForPath: function (path) { -var dot = path.indexOf('.'); -return dot < 0 ? path : path.slice(0, dot); -}, _EVENT_CHANGED: '-changed', notifySplices: function (path, splices) { var info = {}; @@ -2385,8 +2413,6 @@ _complexObserverPathEffect: Polymer.Base._complexObserverPathEffect, _annotatedComputationPathEffect: Polymer.Base._annotatedComputationPathEffect, _computePathEffect: Polymer.Base._computePathEffect, -_modelForPath: Polymer.Base._modelForPath, -_pathMatchesEffect: Polymer.Base._pathMatchesEffect, _notifyBoundPaths: Polymer.Base._notifyBoundPaths, _getPathParts: Polymer.Base._getPathParts }); @@ -2680,7 +2706,9 @@ for (var i = 0, e; i < e$.length; i++) { e = e$[i]; if (e.localName === 'template') { +if (!e.hasAttribute('preserve-content')) { cssText += this.cssFromElement(e); +} } else { if (e.localName === 'style') { var include = e.getAttribute(this.INCLUDE_ATTR); @@ -2807,9 +2835,21 @@ var styles = element._styles; var cssText = ''; var cssBuildType = element.__cssBuild; +var passthrough = settings.useNativeShadow || cssBuildType === 'shady'; +var cb; +if (passthrough) { +var self = this; +cb = function (rule) { +rule.selector = self._slottedToContent(rule.selector); +rule.selector = rule.selector.replace(ROOT, ':host > *'); +if (callback) { +callback(rule); +} +}; +} for (var i = 0, l = styles.length, s; i < l && (s = styles[i]); i++) { var rules = styleUtil.rulesForStyle(s); -cssText += settings.useNativeShadow || cssBuildType === 'shady' ? styleUtil.toCssText(rules, callback) : this.css(rules, element.is, element.extends, callback, element._scopeCssViaAttr) + '\n\n'; +cssText += passthrough ? styleUtil.toCssText(rules, cb) : this.css(rules, element.is, element.extends, callback, element._scopeCssViaAttr) + '\n\n'; } return cssText.trim(); }, @@ -2857,6 +2897,8 @@ var hostContext = false; var self = this; selector = selector.trim(); +selector = this._slottedToContent(selector); +selector = selector.replace(ROOT, ':host > *'); selector = selector.replace(CONTENT_START, HOST + ' $1'); selector = selector.replace(SIMPLE_SELECTOR_SEP, function (m, c, s) { if (!stop) { @@ -2935,13 +2977,14 @@ } }, normalizeRootSelector: function (rule) { -if (rule.selector === ROOT) { -rule.selector = 'html'; -} +rule.selector = rule.selector.replace(ROOT, 'html'); }, _transformDocumentSelector: function (selector) { return selector.match(SCOPE_JUMP) ? this._transformComplexSelector(selector, SCOPE_DOC_SELECTOR) : this._transformSimpleSelector(selector.trim(), SCOPE_DOC_SELECTOR); }, +_slottedToContent: function (cssText) { +return cssText.replace(SLOTTED_PAREN, CONTENT + '> $1'); +}, SCOPE_NAME: 'style-scope' }; var SCOPE_NAME = api.SCOPE_NAME; @@ -2963,6 +3006,7 @@ var CLASS = 'class'; var CONTENT_START = new RegExp('^(' + CONTENT + ')'); var SELECTOR_NO_MATCH = 'should_not_match'; +var SLOTTED_PAREN = /(?:::slotted)(?:\(((?:\([^)(]*\)|[^)(]*)+?)\))/g; return api; }();Polymer.StyleExtends = function () { var styleUtil = Polymer.StyleUtil; @@ -3140,7 +3184,7 @@ return prefix + out.join('; ') + ';'; } function fixVars(matchText, varA, varB) { -return 'var(' + varA + ',' + 'var(' + varB + '));'; +return 'var(' + varA + ',' + 'var(' + varB + '))'; } function atApplyToCssProperties(mixinName, fallbacks) { mixinName = mixinName.replace(APPLY_NAME_CLEAN, ''); @@ -3201,20 +3245,28 @@ _separator: MIXIN_VAR_SEP, transform: function (styles, elementProto) { this.__currentElementProto = elementProto; -styleUtil.forRulesInStyles(styles, this._boundTransformRule); +styleUtil.forRulesInStyles(styles, this._boundFindDefinitions); +styleUtil.forRulesInStyles(styles, this._boundFindApplications); +if (elementProto) { elementProto.__applyShimInvalid = false; +} this.__currentElementProto = null; }, -transformRule: function (rule) { -rule.cssText = this.transformCssText(rule.parsedCssText); +_findDefinitions: function (rule) { +var cssText = rule.parsedCssText; +cssText = cssText.replace(BAD_VAR, fixVars); +cssText = cssText.replace(VAR_ASSIGN, produceCssProperties); +rule.cssText = cssText; if (rule.selector === ':root') { rule.selector = ':host > *'; } }, -transformCssText: function (cssText) { -cssText = cssText.replace(BAD_VAR, fixVars); -cssText = cssText.replace(VAR_ASSIGN, produceCssProperties); -return consumeCssProperties(cssText); +_findApplications: function (rule) { +rule.cssText = consumeCssProperties(rule.cssText); +}, +transformRule: function (rule) { +this._findDefinitions(rule); +this._findApplications(rule); }, _getInitialValueForProperty: function (property) { if (!this._measureElement) { @@ -3226,6 +3278,8 @@ } }; ApplyShim._boundTransformRule = ApplyShim.transformRule.bind(ApplyShim); +ApplyShim._boundFindDefinitions = ApplyShim._findDefinitions.bind(ApplyShim); +ApplyShim._boundFindApplications = ApplyShim._findApplications.bind(ApplyShim); return ApplyShim; }();(function () { var prepElement = Polymer.Base._prepElement; @@ -3536,6 +3590,10 @@ key: o }; }, +_rootSelector: /:root|:host\s*>\s*\*/, +_checkRoot: function (hostScope, selector) { +return Boolean(selector.match(this._rootSelector)) || hostScope === 'html' && selector.indexOf('html') > -1; +}, whenHostOrRootRule: function (scope, rule, style, callback) { if (!rule.propertyInfo) { self.decorateRule(rule); @@ -3545,17 +3603,13 @@ } var hostScope = scope.is ? styleTransformer._calcHostScope(scope.is, scope.extends) : 'html'; var parsedSelector = rule.parsedSelector; -var isRoot = parsedSelector === ':root'; -var isHost = parsedSelector.indexOf(':host') === 0; +var isRoot = this._checkRoot(hostScope, parsedSelector); +var isHost = !isRoot && parsedSelector.indexOf(':host') === 0; var cssBuild = scope.__cssBuild || style.__cssBuild; if (cssBuild === 'shady') { -isRoot = parsedSelector === hostScope + ' > *.' + hostScope || parsedSelector.indexOf('html') !== -1; +isRoot = parsedSelector === hostScope + ' > *.' + hostScope || parsedSelector.indexOf('html') > -1; isHost = !isRoot && parsedSelector.indexOf(hostScope) === 0; } -if (cssBuild === 'shadow') { -isRoot = parsedSelector === ':host > *' || parsedSelector === 'html'; -isHost = isHost && !isRoot; -} if (!isRoot && !isHost) { return; } @@ -3566,6 +3620,9 @@ } selectorToMatch = rule.transformedSelector || rule.parsedSelector; } +if (isRoot && hostScope === 'html') { +selectorToMatch = rule.transformedSelector || rule.parsedSelector; +} callback({ selector: selectorToMatch, isHost: isHost, @@ -3670,6 +3727,9 @@ style = styleUtil.applyCss(cssText, selector, null, element._scopeStyle); } } else if (!style.parentNode) { +if (IS_IE && cssText.indexOf('@media') > -1) { +style.textContent = cssText; +} styleUtil.applyStyle(style, null, element._scopeStyle); } } @@ -3680,9 +3740,6 @@ } element._customStyle = style; } -if (IS_IE) { -style.textContent = style.textContent; -} return style; }, mixinCustomStyle: function (props, customStyle) { @@ -4125,10 +4182,10 @@ if (!targetedBuild) { styleUtil.forEachRule(styleRules, function (rule) { styleTransformer.documentRule(rule); +}); if (settings.useNativeCSSProperties && !buildType) { -applyShim.transformRule(rule); +applyShim.transform([e]); } -}); } if (settings.useNativeCSSProperties) { e.textContent = styleUtil.toCssText(styleRules); @@ -4355,8 +4412,7 @@ }, _notifyPathUpImpl: function (path, value) { var dataHost = this.dataHost; -var dot = path.indexOf('.'); -var root = dot < 0 ? path : path.slice(0, dot); +var root = Polymer.Path.root(path); dataHost._forwardInstancePath.call(dataHost, this, path, value); if (root in dataHost._parentProps) { dataHost._templatized._notifyPath(dataHost._parentPropPrefix + path, value); @@ -4366,7 +4422,7 @@ if (this._forwardParentPath) { if (path.indexOf(this._parentPropPrefix) === 0) { var subPath = path.substring(this._parentPropPrefix.length); -var model = this._modelForPath(subPath); +var model = Polymer.Path.root(subPath); if (model in this._parentProps) { this._forwardParentPath(subPath, value); } @@ -5353,5 +5409,6 @@ + diff --git a/lib/pouchdb/.bower.json b/lib/pouchdb/.bower.json index dec5a42b..3e1b78f7 100644 --- a/lib/pouchdb/.bower.json +++ b/lib/pouchdb/.bower.json @@ -1,6 +1,6 @@ { "name": "pouchdb", - "version": "6.0.4", + "version": "6.0.6", "description": "PouchDB is a pocket-sized database.", "repo": "daleharvey/pouchdb", "keywords": [ @@ -26,11 +26,11 @@ "phantomjsdriver.log" ], "homepage": "https://github.com/pouchdb/pouchdb", - "_release": "6.0.4", + "_release": "6.0.6", "_resolution": { "type": "version", - "tag": "6.0.4", - "commit": "7e13ee2935bffe11302bac5d49f85c3b26111dc3" + "tag": "6.0.6", + "commit": "53917b983aaaa2f6877801a807b27eecccd82438" }, "_source": "https://github.com/pouchdb/pouchdb.git", "_target": "^6.0.4", diff --git a/lib/pouchdb/TESTING.md b/lib/pouchdb/TESTING.md index 65cefac0..233b0f5f 100644 --- a/lib/pouchdb/TESTING.md +++ b/lib/pouchdb/TESTING.md @@ -159,6 +159,12 @@ There's a WebSQL storage quota test available in: Run `npm run dev`, then open it in Safari or iOS. +### Build tests + +To verify that the build was done correctly, there are some tests here: + + npm run verify-build + Adapter plugins and adapter order -------------------------------------- diff --git a/lib/pouchdb/bower.json b/lib/pouchdb/bower.json index c73e789c..1fb098c7 100644 --- a/lib/pouchdb/bower.json +++ b/lib/pouchdb/bower.json @@ -1,6 +1,6 @@ { "name": "pouchdb", - "version": "6.0.4", + "version": "6.0.6", "description": "PouchDB is a pocket-sized database.", "repo": "daleharvey/pouchdb", "keywords": [ diff --git a/lib/pouchdb/component.json b/lib/pouchdb/component.json index 709b89bb..bb1842f2 100644 --- a/lib/pouchdb/component.json +++ b/lib/pouchdb/component.json @@ -1,6 +1,6 @@ { "name": "pouchdb", - "version": "6.0.4", + "version": "6.0.6", "description": "PouchDB is a pocket-sized database.", "repo": "daleharvey/pouchdb", "keywords": [ diff --git a/lib/pouchdb/dist/pouchdb-next.js b/lib/pouchdb/dist/pouchdb-next.js index aeddedbb..1e7cc5cd 100644 --- a/lib/pouchdb/dist/pouchdb-next.js +++ b/lib/pouchdb/dist/pouchdb-next.js @@ -2968,7 +2968,7 @@ function HttpPouch(opts, callback) { // Update/create the document ajax(opts, { method: 'PUT', - url: genDBUrl(host, encodeURIComponent(doc._id)), + url: genDBUrl(host, encodeDocId(doc._id)), body: doc }, function (err, result) { if (err) { @@ -7353,7 +7353,7 @@ PouchDB.defaults = function (defaultOpts) { }; // managed automatically by set-version.js -var version = "6.0.4"; +var version = "6.0.6"; PouchDB.version = version; diff --git a/lib/pouchdb/dist/pouchdb.fruitdown.js b/lib/pouchdb/dist/pouchdb.fruitdown.js index 0e7057be..53e77c50 100644 --- a/lib/pouchdb/dist/pouchdb.fruitdown.js +++ b/lib/pouchdb/dist/pouchdb.fruitdown.js @@ -1,4 +1,4 @@ -// PouchDB fruitdown plugin 6.0.4 +// PouchDB fruitdown plugin 6.0.6 // Based on FruitDOWN: https://github.com/nolanlawson/fruitdown // // (c) 2012-2016 Dale Harvey and the PouchDB team @@ -146,7 +146,7 @@ module.exports = AbstractIterator (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ -var xtend = _dereq_(88) +var xtend = _dereq_(89) , AbstractIterator = _dereq_(2) , AbstractChainedBatch = _dereq_(1) @@ -404,7 +404,7 @@ module.exports.AbstractIterator = AbstractIterator module.exports.AbstractChainedBatch = AbstractChainedBatch }).call(this,{"isBuffer":_dereq_(34)},_dereq_(53)) -},{"1":1,"2":2,"34":34,"53":53,"88":88}],4:[function(_dereq_,module,exports){ +},{"1":1,"2":2,"34":34,"53":53,"89":89}],4:[function(_dereq_,module,exports){ 'use strict'; module.exports = argsArray; @@ -427,6 +427,7 @@ function argsArray(fun) { },{}],5:[function(_dereq_,module,exports){ 'use strict' +exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray @@ -434,23 +435,17 @@ var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array -function init () { - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -init() +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr +function placeHoldersCount (b64) { var len = b64.length - if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } @@ -460,9 +455,19 @@ function toByteArray (b64) { // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} +function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars @@ -3000,7 +3005,7 @@ function coerce(val) { } },{"51":51}],13:[function(_dereq_,module,exports){ -var util = _dereq_(86) +var util = _dereq_(87) , AbstractIterator = _dereq_(18).AbstractIterator @@ -3035,9 +3040,9 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"18":18,"86":86}],14:[function(_dereq_,module,exports){ +},{"18":18,"87":87}],14:[function(_dereq_,module,exports){ (function (Buffer,process){ -var util = _dereq_(86) +var util = _dereq_(87) , AbstractLevelDOWN = _dereq_(18).AbstractLevelDOWN , DeferredIterator = _dereq_(13) @@ -3095,7 +3100,7 @@ module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator }).call(this,{"isBuffer":_dereq_(34)},_dereq_(53)) -},{"13":13,"18":18,"34":34,"53":53,"86":86}],15:[function(_dereq_,module,exports){ +},{"13":13,"18":18,"34":34,"53":53,"87":87}],15:[function(_dereq_,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -5832,8 +5837,8 @@ module.exports = Batch */ var EventEmitter = _dereq_(25).EventEmitter - , inherits = _dereq_(86).inherits - , deprecate = _dereq_(86).deprecate + , inherits = _dereq_(87).inherits + , deprecate = _dereq_(87).deprecate , extend = _dereq_(47) , prr = _dereq_(54) , DeferredLevelDOWN = _dereq_(14) @@ -6226,7 +6231,7 @@ module.exports.repair = deprecate( }).call(this,_dereq_(53)) -},{"14":14,"25":25,"39":39,"40":40,"42":42,"44":44,"45":45,"47":47,"53":53,"54":54,"86":86}],44:[function(_dereq_,module,exports){ +},{"14":14,"25":25,"39":39,"40":40,"42":42,"44":44,"45":45,"47":47,"53":53,"54":54,"87":87}],44:[function(_dereq_,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -6235,7 +6240,7 @@ module.exports.repair = deprecate( var extend = _dereq_(47) , LevelUPError = _dereq_(39).LevelUPError - , format = _dereq_(86).format + , format = _dereq_(87).format , defaultOptions = { createIfMissing : true , errorIfExists : false @@ -6305,7 +6310,7 @@ module.exports = { , isDefined : isDefined } -},{"39":39,"47":47,"48":48,"6":6,"86":86}],45:[function(_dereq_,module,exports){ +},{"39":39,"47":47,"48":48,"6":6,"87":87}],45:[function(_dereq_,module,exports){ arguments[4][37][0].apply(exports,arguments) },{"37":37,"46":46}],46:[function(_dereq_,module,exports){ (function (Buffer){ @@ -13595,7 +13600,7 @@ arguments[4][20][0].apply(exports,arguments) },{"20":20}],82:[function(_dereq_,module,exports){ (function (process){ var Transform = _dereq_(80) - , inherits = _dereq_(86).inherits + , inherits = _dereq_(87).inherits , xtend = _dereq_(81) function DestroyableTransform(opts) { @@ -13692,7 +13697,7 @@ module.exports.obj = through2(function (options, transform, flush) { }) }).call(this,_dereq_(53)) -},{"53":53,"80":80,"81":81,"86":86}],83:[function(_dereq_,module,exports){ +},{"53":53,"80":80,"81":81,"87":87}],83:[function(_dereq_,module,exports){ 'use strict'; // Simple FIFO queue implementation to avoid having to do shift() @@ -13814,13 +13819,15 @@ function config (name) { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],85:[function(_dereq_,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"33":33}],86:[function(_dereq_,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],86:[function(_dereq_,module,exports){ +},{}],87:[function(_dereq_,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14347,7 +14354,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = _dereq_(85); +exports.isBuffer = _dereq_(86); function objectToString(o) { return Object.prototype.toString.call(o); @@ -14391,7 +14398,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = _dereq_(33); +exports.inherits = _dereq_(85); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -14410,7 +14417,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,_dereq_(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"33":33,"53":53,"85":85}],87:[function(_dereq_,module,exports){ +},{"53":53,"85":85,"86":86}],88:[function(_dereq_,module,exports){ 'use strict'; /** @@ -14585,7 +14592,7 @@ exports.parse = function (str) { } }; -},{}],88:[function(_dereq_,module,exports){ +},{}],89:[function(_dereq_,module,exports){ module.exports = extend function extend() { @@ -14604,7 +14611,7 @@ function extend() { return target } -},{}],89:[function(_dereq_,module,exports){ +},{}],90:[function(_dereq_,module,exports){ (function (process,global,Buffer){ 'use strict'; @@ -14623,7 +14630,7 @@ var Deque = _interopDefault(_dereq_(21)); var lie = _interopDefault(_dereq_(49)); var debug = _interopDefault(_dereq_(11)); var Md5 = _interopDefault(_dereq_(62)); -var vuvuzela = _interopDefault(_dereq_(87)); +var vuvuzela = _interopDefault(_dereq_(88)); var jsExtend = _dereq_(36); var fruitdown = _interopDefault(_dereq_(28)); @@ -14758,8 +14765,8 @@ function nut(db, precodec, codec) { }; } -function NotFoundError(reason) { - Error.call(this, reason); +function NotFoundError() { + Error.call(this); } inherits(NotFoundError, Error); @@ -14769,6 +14776,8 @@ NotFoundError.prototype.name = 'NotFoundError'; var EventEmitter$1 = events__default.EventEmitter; var version = "6.5.4"; +var NOT_FOUND_ERROR = new NotFoundError(); + var sublevel = function (nut, prefix, createStream, options) { var emitter = new EventEmitter$1(); emitter.sublevels = {}; @@ -14857,7 +14866,7 @@ var sublevel = function (nut, prefix, createStream, options) { } nut.get(key, prefix, mergeOpts(opts), function (err, value) { if (err) { - cb(new NotFoundError(err)); + cb(NOT_FOUND_ERROR); } else { cb(null, value); } @@ -15060,25 +15069,6 @@ _Set.prototype.has = function (key) { return this.store.has(key); }; -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -16818,8 +16808,8 @@ function LevelPouch(opts, callback) { db._docCount = -1; db._queue = new Deque(); /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationOne(name, db, afterDBCreated); } else { afterDBCreated(); } @@ -16834,19 +16824,26 @@ function LevelPouch(opts, callback) { stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationTwo(db, stores, afterLastMigration); + } else { + afterLastMigration(); + } + } + + function afterLastMigration() { + stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { + if (typeof db._updateSeq === 'undefined') { + db._updateSeq = value || 0; + } + stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { + db._docCount = !err ? value : 0; + stores.metaStore.get(UUID_KEY, function (err, value) { + instanceId = !err ? value : uuid(); + stores.metaStore.put(UUID_KEY, instanceId, function () { + process.nextTick(function () { + callback(null, api); }); }); }); @@ -18135,4 +18132,4 @@ if (!PDB) { FruitdownPouchPlugin(PDB); } }).call(this,_dereq_(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(8).Buffer) -},{"11":11,"21":21,"25":25,"28":28,"33":33,"36":36,"37":37,"4":4,"43":43,"49":49,"50":50,"53":53,"61":61,"62":62,"8":8,"82":82,"87":87,"pouchdb":"pouchdb"}]},{},[89]); +},{"11":11,"21":21,"25":25,"28":28,"33":33,"36":36,"37":37,"4":4,"43":43,"49":49,"50":50,"53":53,"61":61,"62":62,"8":8,"82":82,"88":88,"pouchdb":"pouchdb"}]},{},[90]); diff --git a/lib/pouchdb/dist/pouchdb.fruitdown.min.js b/lib/pouchdb/dist/pouchdb.fruitdown.min.js index c8fea7f5..fdec7e69 100644 --- a/lib/pouchdb/dist/pouchdb.fruitdown.min.js +++ b/lib/pouchdb/dist/pouchdb.fruitdown.min.js @@ -1,14 +1,14 @@ -// PouchDB fruitdown plugin 6.0.4 +// PouchDB fruitdown plugin 6.0.6 // Based on FruitDOWN: https://github.com/nolanlawson/fruitdown // // (c) 2012-2016 Dale Harvey and the PouchDB team // PouchDB may be freely distributed under the Apache license, version 2.0. // For all details and documentation: // http://pouchdb.com -!function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new c(3*s/4-o),r=o>0?s-4:s;var u=0;for(t=0,n=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=f[e.charCodeAt(t)]<<2|f[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=f[e.charCodeAt(t)]<<10|f[e.charCodeAt(t+1)]<<4|f[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}function o(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,n){for(var r,i=[],a=t;ac?c:f+s));return 1===r?(t=e[n-1],i+=u[t>>2],i+=u[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=u[t>>10],i+=u[t>>4&63],i+=u[t<<2&63],i+="="),o.push(i),o.join("")}n.toByteArray=i,n.fromByteArray=s;var u=[],f=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;r()},{}],6:[function(e,t,n){},{}],7:[function(e,t,n){(function(t){"use strict";var r=e(8),i=r.Buffer,o=r.SlowBuffer,a=r.kMaxLength||2147483647;n.alloc=function(e,t,n){if("function"==typeof i.alloc)return i.alloc(e,t,n);if("number"==typeof n)throw new TypeError("encoding must not be number");if("number"!=typeof e)throw new TypeError("size must be a number");if(e>a)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),f=u.length,c=-1;++ca)throw new RangeError("size is too large");return new i(e)},n.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},n.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{8:8}],8:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return Y(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return Y(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var f;if(i){var c=-1;for(f=n;fs&&(n=s-u),f=n;f>=0;f--){for(var l=!0,h=0;hi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,f,c,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],f=e[i+2],128===(192&u)&&128===(192&f)&&(l=(15&o)<<12|(63&u)<<6|63&f,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],f=e[i+2],c=e[i+3],128===(192&u)&&128===(192&f)&&128===(192&c)&&(l=(15&o)<<18|(63&u)<<12|(63&f)<<6|63&c,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function q(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function I(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||P(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function W(e,t,n,r,i){return i||P(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function K(e){return e<16?"0"+e.toString(16):e.toString(16)}function Y(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var X=e(5),Z=e(31),Q=e(35);n.Buffer=a,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return f(null,e,t,n)},a.allocUnsafe=function(e){return c(null,e)},a.allocUnsafeSlow=function(e){return c(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),f=this.slice(r,i),c=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return B(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var i=Math.pow(2,8*n)-1;q(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):I(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);q(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);q(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):I(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return W(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return W(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>2],i=(3&a)<<4;break;case 1:n+=e[i|a>>4],i=(15&a)<<2;break;case 2:n+=e[i|a>>6],n+=e[63&a],i=0}}return r%3&&(n+=e[i]), -n},t.decode=function(e){for(var t=e.length,i=0,o=new r(~~(t/4*3)),a=0,s=0;s>4,a=u<<4&255;break;case 2:o[i++]=a|u>>2,a=u<<6&255;break;case 3:o[i++]=a|u}}return o},t},t.exports(i,t.exports)},{8:8}],11:[function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function s(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(12),n.log=o,n.formatArgs=i,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{12:12}],12:[function(e,t,n){function r(){return n.colors[c++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(f||t);e.diff=o,e.prev=f,e.curr=t,f=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var i=n.formatters[r];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=i.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}r.prototype.toArray=function(){for(var e=this._length,t=new Array(e),n=this._front,r=this._capacity,i=0;i1){var r=this._capacity;if(n+t>r){for(var i=0;i1){var r=this._capacity;if(t+n>r){for(var i=n-1;i>=0;i--){this._checkCapacity(t+1);var r=this._capacity,o=(this._front-1&r-1^r)-r;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=n-1;i>=0;i--){var o=(a-1&r-1^r)-r;this[o]=arguments[i],a=o}return this._front=a,this._length=t+n,t+n}if(0===n)return t;this._checkCapacity(t+1);var r=this._capacity,i=(this._front-1&r-1^r)-r;return this[i]=e,this._length=t+1,this._front=i,t+1},r.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},r.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},r.prototype.get=function(e){var t=e;if(t===(0|t)){var n=this._length;if(t<0&&(t+=n),!(t<0||t>=n))return this[this._front+t&this._capacity-1]}},r.prototype.isEmpty=function(){return 0===this._length},r.prototype.clear=function(){for(var e=this._length,t=this._front,n=this._capacity,r=0;rt){var o=n+r&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=r},{}],22:[function(e,t,n){function r(e,t,n){a(this,{type:e,name:e,cause:"string"!=typeof t?t:n,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),r.call(this,"CustomError",e,t)}function o(e,t,n){var o=function(n,i){r.call(this,t,n,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=n?new n:new i,o}var a=e(24);i.prototype=new Error,t.exports=function(e){var t=function(t,n){return o(e,t,n)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{24:24}],23:[function(e,t,n){var r=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},r.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(22)(t.exports),t.exports.create=t.exports.custom.createError},{22:22}],24:[function(e,t,n){!function(e,n,r){"undefined"!=typeof t&&t.exports?t.exports=r():n[e]=r()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,n){return Object.defineProperty(e,t,n),e}:function(e,t,n){return e[t]=n.value,e},t=function(e,t){var n="object"==typeof t,r=!n&&"string"==typeof t,i=function(e){return n?!!t[e]:!!r&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},n=function(n,r,i,o){var a;if(o=t(i,o),"object"==typeof r){for(a in r)Object.hasOwnProperty.call(r,a)&&(o.value=r[a],e(n,a,o));return n}return e(n,r,o)};return n})},{}],25:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,f;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),f=n.slice(),r=f.length,u=0;u0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],26:[function(e,t,n){(function(e,n){"use strict";function r(e){this._dbName=e}function i(e,t){if(u[e])return s(function(){t(null,u[e])});var n=indexedDB.open(e,1);f[e]=n,n.onupgradeneeded=function(e){var t=e.target.result;1!==e.oldVersion&&t.createObjectStore(a).createIndex("fakeKey","fakeKey")},n.onsuccess=function(n){var r=u[e]=n.target.result;t(null,r)},n.onerror=function(e){var n="Failed to open indexedDB, are you in private browsing mode?";console.error(n),t(e)}}function o(e,t){try{return{txn:e.transaction(a,t)}}catch(e){return{error:e}}}var a="fruitdown",s=n.setImmediate||e.nextTick,u={},f={};r.prototype.getKeys=function(e){i(this._dbName,function(t,n){if(t)return e(t);var r=o(n,"readonly");if(r.error)return e(r.error);var i=r.txn,s=i.objectStore(a);i.onerror=e;var u=[];i.oncomplete=function(){e(null,u.sort())};var f=s.index("fakeKey").openKeyCursor();f.onsuccess=function(e){var t=e.target.result;t&&(u.push(t.primaryKey),t.continue())}})},r.prototype.put=function(e,t,n){i(this._dbName,function(r,i){if(r)return n(r);var s=o(i,"readwrite");if(s.error)return n(s.error);var u=s.txn,f=u.objectStore(a),c="string"==typeof t?t:t.toString();u.onerror=n,u.oncomplete=function(){n()},f.put({value:c,fakeKey:0},e)})},r.prototype.get=function(e,t){i(this._dbName,function(n,r){if(n)return t(n);var i=o(r,"readonly");if(i.error)return t(i.error);var s,u=i.txn,f=u.objectStore(a),c=f.get(e);c.onsuccess=function(e){e.target.result&&(s=e.target.result.value)},u.onerror=t,u.oncomplete=function(){t(null,s)}})},r.prototype.remove=function(e,t){i(this._dbName,function(n,r){if(n)return t(n);var i=o(r,"readwrite");if(i.error)return t(i.error);var s=i.txn,u=s.objectStore(a);u.delete(e),s.onerror=t,s.oncomplete=function(){t()}})},r.destroy=function(e,t){s(function(){f[e]&&f[e].result&&(f[e].result.close(),delete u[e]);var n=indexedDB.deleteDatabase(e);n.onsuccess=function(){f[e]&&(f[e]=null),t(null)},n.onerror=t})},t.exports=r}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{53:53}],27:[function(e,t,n){(function(n){"use strict";function r(e){this._store=new l(e),this._queue=new h}var i="ArrayBuffer:",o=new RegExp("^"+i),a="Uint8Array:",s=new RegExp("^"+a),u="Buff:",f=new RegExp("^"+u),c=e(30),l=e(26),h=e(29),d=e(10);r.prototype.sequentialize=function(e,t){this._queue.add(t,e)},r.prototype.init=function(e){var t=this;t.sequentialize(e,function(e){t._store.getKeys(function(n,r){return n?e(n):(t._keys=r,e())})})},r.prototype.keys=function(e){var t=this;t.sequentialize(e,function(e){e(null,t._keys.slice())})},r.prototype.setItem=function(e,t,r){var i=this;i.sequentialize(r,function(r){n.isBuffer(t)&&(t=u+d.encode(t));var o=c.sortedIndexOf(i._keys,e);i._keys[o]!==e&&i._keys.splice(o,0,e),i._store.put(e,t,r)})},r.prototype.getItem=function(e,t){var n=this;n.sequentialize(t,function(t){n._store.get(e,function(e,n){return e?t(e):"undefined"==typeof n||null===n?t(new Error("NotFound")):("undefined"!=typeof n&&(f.test(n)?n=d.decode(n.substring(u.length)):o.test(n)?(n=n.substring(i.length),n=new ArrayBuffer(atob(n).split("").map(function(e){return e.charCodeAt(0)}))):s.test(n)&&(n=n.substring(a.length),n=new Uint8Array(atob(n).split("").map(function(e){return e.charCodeAt(0)})))),void t(null,n))})})},r.prototype.removeItem=function(e,t){var n=this;n.sequentialize(t,function(t){var r=c.sortedIndexOf(n._keys,e);n._keys[r]===e?(n._keys.splice(r,1),n._store.remove(e,function(e){return e?t(e):void t()})):t()})},r.prototype.length=function(e){var t=this;t.sequentialize(e,function(e){e(null,t._keys.length)})},t.exports=r}).call(this,{isBuffer:e(34)})},{10:10,26:26,29:29,30:30,34:34}],28:[function(e,t,n){(function(n,r,i){"use strict";function o(e,t){c.call(this,e),this._reverse=!!t.reverse,this._endkey=t.end,this._startkey=t.start,this._gt=t.gt,this._gte=t.gte,this._lt=t.lt,this._lte=t.lte,this._exclusiveStart=t.exclusiveStart,this._limit=t.limit,this._count=0,this.onInitCompleteListeners=[]}function a(e){return this instanceof a?(f.call(this,e),void(this.container=new l(e))):new a(e)}function s(e,t){if(null===e||void 0===e)return new Error(t+" cannot be `null` or `undefined`");if(null===e||void 0===e)return new Error(t+" cannot be `null` or `undefined`");if("key"===t){if(e instanceof Boolean)return new Error(t+" cannot be `null` or `undefined`");if(""===e)return new Error(t+" cannot be empty")}if(0===e.toString().indexOf("[object ArrayBuffer]")&&(0===e.byteLength||void 0===e.byteLength))return new Error(t+" cannot be an empty Buffer");if(i.isBuffer(e)){if(0===e.length)return new Error(t+" cannot be an empty Buffer")}else if(""===String(e))return new Error(t+" cannot be an empty String")}var u=e(33),f=e(3).AbstractLevelDOWN,c=e(3).AbstractIterator,l=e(27),h=e(26),d=e(30),p=r.setImmediate||n.nextTick;u(o,c),o.prototype._init=function(e){p(function(){e()})},o.prototype._next=function(e){function t(){if(n._pos===n._keys.length||n._pos<0)return e();var t=n._keys[n._pos];return n._endkey&&(n._reverse?tn._endkey)?e():n._limit&&n._limit>0&&n._count++>=n._limit?e():n._lt&&t>=n._lt||n._lte&&t>n._lte||n._gt&&t<=n._gt||n._gte&&t=n._keys.length||o<0?void 0:n._keys[o];n._pos=o,n._reverse?(n._exclusiveStart||a!==n._startkey)&&n._pos--:n._exclusiveStart&&a===n._startkey&&n._pos++}else n._pos=n._reverse?n._keys.length-1:0;t(),n.initCompleted=!0;for(var s=-1;++s-1){var o=JSON.parse(r);r=o.data}n(null,r)}))},a.prototype._del=function(e,t,n){var r=s(e,"key");return r?p(function(){n(r)}):(i.isBuffer(e)||(e=String(e)),void this.container.removeItem(e,n))},a.prototype._batch=function(e,t,n){var r=this;p(function(){function o(){++l===e.length&&n(c)}var a,u,f,c,l=0;if(Array.isArray(e)&&e.length)for(var h=0;h>>1,e[n]>1,c=-7,l=n?i-1:0,h=n?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-c)-1,d>>=-c,c+=s;c>0;o=256*o+e[t+l],l+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=r;c>0;a=256*a+e[t+l],l+=h,c-=8);if(0===o)o=1-f;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,r),o-=f}return(d?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,u,f=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=c?(s=0,a=c):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,f-=8);e[n+d-p]|=128*g}},{}],32:[function(e,t,n){(function(e){"use strict";function n(){c=!0;for(var e,t,n=l.length;n;){ -for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[r],e):e[r]}),n},r.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(n,r){return{key:t.decodeKey(n,e),value:t.decodeValue(r,e)}}:e.keys?function(n){return t.decodeKey(n,e)}:e.values?function(n,r){return t.decodeValue(r,e)}:function(){}},r.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},r.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{38:38}],38:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},n.id=n.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],39:[function(e,t,n){var r=e(23).create,i=r("LevelUPError"),o=r("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:r("InitializationError",i),OpenError:r("OpenError",i),ReadError:r("ReadError",i),WriteError:r("WriteError",i),NotFoundError:o,EncodingError:r("EncodingError",i)}},{23:23}],40:[function(e,t,n){function r(e,t){return this instanceof r?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new r(e,t)}var i=e(33),o=e(61).Readable,a=e(41),s=e(39).EncodingError;t.exports=r,i(r,o),r.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,n,r){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===n&&void 0===r)e.push(null);else{if(!e._decoder)return e.push({key:n,value:r});try{var r=e._decoder(n,r)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(r)}}})},r.prototype.destroy=r.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{33:33,39:39,41:41,61:61}],41:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],42:[function(e,t,n){function r(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(44),o=e(39).WriteError,a=i.getOptions,s=i.dispatchError;r.prototype.put=function(e,t,n){n=a(n);var r=this._codec.encodeKey(e,n),i=this._codec.encodeValue(t,n);try{this.batch.put(r,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:r,value:i}),this.length++,this},r.prototype.del=function(e,t){t=a(t);var n=this._codec.encodeKey(e,t);try{this.batch.del(n)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:n}),this.length++,this},r.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},r.prototype.write=function(e){var t=this._levelup,n=this.ops;try{this.batch.write(function(r){return r?s(t,new o(r),e):(t.emit("batch",n),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=r},{39:39,44:44}],43:[function(e,t,n){(function(n){function r(e,t){return"function"==typeof e?e:t}function i(e,t,r){if(!(this instanceof i))return new i(e,t,r);var o;if(f.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{},t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e,e=null),"function"==typeof t&&(r=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),r)return n.nextTick(function(){r(o)});throw o}t=B(t),this.options=h(R,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(r)}function o(e,t,n){if(!e._isOpening()&&!e.isOpen())return j(e,new b("Database is not open"),n),!0}function a(e,t,n){j(e,new v(t),n)}function s(e,t,n){j(e,new b(t),n)}function u(e){return function(t,n){A()[e](t,n||function(){})}}var f=e(25).EventEmitter,c=e(86).inherits,l=e(86).deprecate,h=e(47),d=e(54),p=e(14),g=e(40),y=e(39),v=y.WriteError,b=y.ReadError,m=y.NotFoundError,_=y.OpenError,w=y.EncodingError,E=y.InitializationError,k=e(44),S=e(42),x=e(45),B=k.getOptions,R=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;c(i,f),i.prototype.open=function(e){var t,r,i=this;return this.isOpen()?(e&&n.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),r=t(this.location),void r.open(this.options,function(t){return t?j(i,new _(t),e):(i.db.setDb(r),i.db=r,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return n.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,n){var i,a=this;if(n=r(t,n),!o(this,t,n)){if(null===e||void 0===e||"function"!=typeof n)return s(this,"get() requires key and callback arguments",n);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(r,i){if(r)return r=/notfound/i.test(r)||r.notFound?new m("Key not found in database ["+e+"]",r):new b(r),j(a,r,n);if(n){try{i=a._codec.decodeValue(i,t)}catch(e){return n(new w(e))}n(null,i)}})}},i.prototype.put=function(e,t,n,i){var s,u,f=this;return i=r(n,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,n,i)||(n=B(n),s=this._codec.encodeKey(e,n),u=this._codec.encodeValue(t,n),this.db.put(s,u,n,function(n){return n?j(f,new v(n),i):(f.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,n){var i,s=this;return n=r(t,n),null===e||void 0===e?a(this,"del() requires a key argument",n):void(o(this,t,n)||(t=B(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new v(t),n):(s.emit("del",e),void(n&&n()))})))},i.prototype.batch=function(e,t,n){var i,s=this;return arguments.length?(n=r(t,n),Array.isArray(e)?void(o(this,t,n)||(t=B(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new v(t),n):(s.emit("batch",e),void(n&&n()))}))):a(this,"batch() requires an array argument",n)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,n,i){var o,a,u=this;return i=r(n,i),n=B(n),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,n),a=this._codec.encodeKey(t,n),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new _(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(39),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(53))},{14:14,25:25,39:39,40:40,42:42,44:44,45:45,47:47,53:53,54:54,86:86}],44:[function(e,t,n){function r(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,n=e(48).devDependencies.leveldown;try{t=e(6).version}catch(e){throw o(e)}if(!e(6).satisfies(t,n))throw new f("Installed version of LevelDOWN ("+t+") does not match required version ("+n+")");try{return u=e(6)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new f(c(t,e.message))}function a(e,t,n){"function"==typeof n?n(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,f=(e(47),e(39).LevelUPError),c=e(86).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:r,getLevelDOWN:i,dispatchError:a,isDefined:s}},{39:39,47:47,48:48,6:6,86:86}],45:[function(e,t,n){arguments[4][37][0].apply(n,arguments)},{37:37,46:46}],46:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],47:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],48:[function(e,t,n){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],49:[function(e,t,n){"use strict";function r(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=b,this.queue=[],this.outcome=void 0,e!==r&&u(this,e)}function o(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function a(e,t,n){p(function(){var r;try{r=t(n)}catch(t){return g.reject(e,t)}r===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,r)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function n(t){o||(o=!0,g.reject(e,t))}function r(t){o||(o=!0,g.resolve(e,t))}function i(){t(r,n)}var o=!1,a=f(i);"error"===a.status&&n(a.value)}function f(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}function c(e){return e instanceof this?e:g.resolve(new this(r),e)}function l(e){var t=new this(r);return g.reject(t,e)}function h(e){function t(e,t){function r(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(f,a))}n.resolve(e).then(r,function(e){o||(o=!0,g.reject(f,e))})}var n=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,f=new this(r);++un?1:0};var a=n.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=n.lowerBound=function(e){var t=a(e);return t&&e[t]};n.lowerBoundInclusive=function(e){return!t(e,"gt")},n.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=n.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},f=n.upperBoundExclusive=function(e){return!!t(e,"lt")},c=n.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=n.upperBound=function(e){var t=c(e);return t&&e[t]};n.toLtgt=function(e,r,i,a,s){r=r||{},i=i||o;var u=arguments.length>3,f=n.lowerBoundKey(e),c=n.upperBoundKey(e);return f?"gt"===f?r.gt=i(e.gt,!1):r.gte=i(e[f],!1):u&&(r.gte=i(a,!1)),c?"lt"===c?r.lt=i(e.lt,!0):r.lte=i(e[c],!0):u&&(r.lte=i(s,!0)),null!=e.reverse&&(r.reverse=!!e.reverse),t(r,"max")&&delete r.max,t(r,"min")&&delete r.min,t(r,"start")&&delete r.start,t(r,"end")&&delete r.end,r},n.contains=function(e,t,i){i=i||n.compare;var o=s(e);if(r(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var c=l(e);if(r(c)){var a=i(t,c);if(a>0||0===a&&f(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(34)})},{34:34}],51:[function(e,t,n){function r(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*f;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=f?Math.round(e/f)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,c,"day")||a(e,f,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e1)for(var n=1;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||r||(n=t.decoder.write(n)),t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):(t.reading=!1,t.buffer.push(n)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.length>0?l(e):_(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?n.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){p(e,t)}))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(x.listenerCount(e,"data")>0&&b(e))):void(r.ranOut=!0)}function v(){this._readableState.ranOut&&(this._readableState.ranOut=!1,y(this))}function b(e,t){var r=e._readableState;if(r.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=B.prototype.pipe,e.on=e.addListener=B.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?n.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function m(e,t){var n,r=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(a)n=r.shift();else if(!e||e>=i)n=o?r.join(""):S.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return n=null,t.length>0&&t.decoder&&(n=m(e,t),t.length-=n.length),0===t.length&&_(this),n;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(r,t)),n=e>0?m(e,t):null,null===n&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&_(this),n},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){e===c&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),c.removeListener("end",i),c.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){f(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),f()}function u(){e.removeListener("close",s),f()}function f(){c.unpipe(e)}var c=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e]; -break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,d=h?i:o;l.endEmitted?n.nextTick(d):c.once("end",d),e.on("unpipe",r);var p=g(c);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",c),l.flowing||(this.on("readable",v),l.flowing=!0,n.nextTick(function(){y(c)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1;for(var i=0;i>>32-i,n)}function n(e,n,r,i,o,a,s){return t(n&r|~n&i,e,n,o,a,s)}function r(e,n,r,i,o,a,s){return t(n&i|r&~i,e,n,o,a,s)}function i(e,n,r,i,o,a,s){return t(n^r^i,e,n,o,a,s)}function o(e,n,r,i,o,a,s){return t(r^(n|~i),e,n,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],f=e[3];a=n(a,s,u,f,t[0],7,-680876936),f=n(f,a,s,u,t[1],12,-389564586),u=n(u,f,a,s,t[2],17,606105819),s=n(s,u,f,a,t[3],22,-1044525330),a=n(a,s,u,f,t[4],7,-176418897),f=n(f,a,s,u,t[5],12,1200080426),u=n(u,f,a,s,t[6],17,-1473231341),s=n(s,u,f,a,t[7],22,-45705983),a=n(a,s,u,f,t[8],7,1770035416),f=n(f,a,s,u,t[9],12,-1958414417),u=n(u,f,a,s,t[10],17,-42063),s=n(s,u,f,a,t[11],22,-1990404162),a=n(a,s,u,f,t[12],7,1804603682),f=n(f,a,s,u,t[13],12,-40341101),u=n(u,f,a,s,t[14],17,-1502002290),s=n(s,u,f,a,t[15],22,1236535329),a=r(a,s,u,f,t[1],5,-165796510),f=r(f,a,s,u,t[6],9,-1069501632),u=r(u,f,a,s,t[11],14,643717713),s=r(s,u,f,a,t[0],20,-373897302),a=r(a,s,u,f,t[5],5,-701558691),f=r(f,a,s,u,t[10],9,38016083),u=r(u,f,a,s,t[15],14,-660478335),s=r(s,u,f,a,t[4],20,-405537848),a=r(a,s,u,f,t[9],5,568446438),f=r(f,a,s,u,t[14],9,-1019803690),u=r(u,f,a,s,t[3],14,-187363961),s=r(s,u,f,a,t[8],20,1163531501),a=r(a,s,u,f,t[13],5,-1444681467),f=r(f,a,s,u,t[2],9,-51403784),u=r(u,f,a,s,t[7],14,1735328473),s=r(s,u,f,a,t[12],20,-1926607734),a=i(a,s,u,f,t[5],4,-378558),f=i(f,a,s,u,t[8],11,-2022574463),u=i(u,f,a,s,t[11],16,1839030562),s=i(s,u,f,a,t[14],23,-35309556),a=i(a,s,u,f,t[1],4,-1530992060),f=i(f,a,s,u,t[4],11,1272893353),u=i(u,f,a,s,t[7],16,-155497632),s=i(s,u,f,a,t[10],23,-1094730640),a=i(a,s,u,f,t[13],4,681279174),f=i(f,a,s,u,t[0],11,-358537222),u=i(u,f,a,s,t[3],16,-722521979),s=i(s,u,f,a,t[6],23,76029189),a=i(a,s,u,f,t[9],4,-640364487),f=i(f,a,s,u,t[12],11,-421815835),u=i(u,f,a,s,t[15],16,530742520),s=i(s,u,f,a,t[2],23,-995338651),a=o(a,s,u,f,t[0],6,-198630844),f=o(f,a,s,u,t[7],10,1126891415),u=o(u,f,a,s,t[14],15,-1416354905),s=o(s,u,f,a,t[5],21,-57434055),a=o(a,s,u,f,t[12],6,1700485571),f=o(f,a,s,u,t[3],10,-1894986606),u=o(u,f,a,s,t[10],15,-1051523),s=o(s,u,f,a,t[1],21,-2054922799),a=o(a,s,u,f,t[8],6,1873313359),f=o(f,a,s,u,t[15],10,-30611744),u=o(u,f,a,s,t[6],15,-1560198380),s=o(s,u,f,a,t[13],21,1309151649),a=o(a,s,u,f,t[4],6,-145523070),f=o(f,a,s,u,t[11],10,-1120210379),u=o(u,f,a,s,t[2],15,718787259),s=o(s,u,f,a,t[9],21,-343485551),e[0]=m(a,e[0]),e[1]=m(s,e[1]),e[2]=m(u,e[2]),e[3]=m(f,e[3])}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function f(e){var t,n,r,i,o,u,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,r[14]=o,r[15]=u,a(c,r),c}function c(e){var t,n,r,i,o,s,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,r[14]=o,r[15]=s,a(c,r),c}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=_[e>>8*t+4&15]+_[e>>8*t&15];return n}function h(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,a,s,u=this.byteLength,f=t(n,u),c=u;return r!==e&&(c=t(r,u)),f>c?new ArrayBuffer(0):(i=c-f,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,f,i),a.set(s),o)}}(),b.prototype.append=function(e){return this.appendBinary(d(e)),this},b.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},b.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},b.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},b.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},b.prototype._finish=function(e,t){var n,r,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=r,e[15]=i,a(this._hash,e)},b.hash=function(e,t){return b.hashBinary(d(e),t)},b.hashBinary=function(e,t){var n=f(e),r=h(n);return t?v(r):r},b.ArrayBuffer=function(){this.reset()},b.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.ArrayBuffer.prototype.getState=function(){var e=b.prototype.getState.call(this);return e.buff=g(e.buff),e},b.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),b.prototype.setState.call(this,e)},b.ArrayBuffer.prototype.destroy=b.prototype.destroy,b.ArrayBuffer.prototype._finish=b.prototype._finish,b.ArrayBuffer.hash=function(e,t){var n=c(new Uint8Array(e)),r=h(n);return t?v(r):r},b})},{}],63:[function(e,t,n){function r(){i.call(this)}t.exports=r;var i=e(25).EventEmitter,o=e(33);o(r,i),r.Readable=e(72),r.Writable=e(74),r.Duplex=e(64),r.Transform=e(73),r.PassThrough=e(71),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&f.pause&&f.pause()}function r(){f.readable&&f.resume&&f.resume()}function o(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){f.removeListener("data",n),e.removeListener("drain",r),f.removeListener("end",o),f.removeListener("close",a),f.removeListener("error",s),e.removeListener("error",s),f.removeListener("end",u),f.removeListener("close",u),e.removeListener("close",u)}var f=this;f.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(f.on("end",o),f.on("close",a));var c=!1;return f.on("error",s),e.on("error",s),f.on("end",u),f.on("close",u),e.on("close",u),e.emit("pipe",f),e}},{25:25,33:33,64:64,71:71,72:72,73:73,74:74}],64:[function(e,t,n){t.exports=e(65)},{65:65}],65:[function(e,t,n){"use strict";function r(e){return this instanceof r?(f.call(this,e),c.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e(52),u=e(9);u.inherits=e(33);var f=e(67),c=e(69);u.inherits(r,f);for(var l=a(c.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var f;!t.decoder||i||r||(n=t.decoder.write(n),f=!t.objectMode&&0===n.length),i||(t.reading=!1),f||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function c(e,t){var n=null;return L.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(N("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){N("emit readable"),e.emit("readable"),_(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=E(e,t.buffer,t.decoder),n}function E(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=C.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(B,t,e))}function B(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function R(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return N("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;N("need readable",r),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){N("onunpipe"),e===h&&a()}function o(){N("onend"),e.end()}function a(){N("cleanup"),e.removeListener("close",f),e.removeListener("finish",c),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),b=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){N("ondata"),m=!1;var n=e.write(t);!1!==n||m||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!b&&(N("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,m=!0),h.pause())}function u(t){N("onerror",t),l(),e.removeListener("error",u),0===T(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",c),l()}function c(){N("onfinish"),e.removeListener("close",f),l()}function l(){N("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,N("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var v=y(h);e.on("drain",v);var b=!1,m=!1;return h.on("data",s),r(e,"error",u),e.once("close",f),e.once("finish",c),e.emit("pipe",h),d.flowing||(N("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(9);x.inherits=e(33);var B,R={deprecate:e(84)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(25).EventEmitter)}}();var A=e(8).Buffer,j=e(7);x.inherits(a,B);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:R.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{25:25,33:33,52:52,53:53,65:65,7:7,8:8,84:84,9:9}],70:[function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(e(8).Buffer,e(7));t.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},{7:7,8:8}],71:[function(e,t,n){t.exports=e(66)},{66:66}],72:[function(e,t,n){(function(r){var i=function(){try{return e("stream")}catch(e){}}();n=t.exports=e(67),n.Stream=i||n,n.Readable=n,n.Writable=e(69),n.Duplex=e(65),n.Transform=e(68),n.PassThrough=e(66),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(53))},{53:53,65:65,66:66,67:67,68:68,69:69}],73:[function(e,t,n){t.exports=e(68)},{68:68}],74:[function(e,t,n){t.exports=e(69)},{69:69}],75:[function(e,t,n){function r(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(8).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},f=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};f.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},f.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},f.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}},{8:8}],76:[function(e,t,n){arguments[4][65][0].apply(n,arguments)},{33:33,52:52,65:65,77:77,79:79,9:9}],77:[function(e,t,n){(function(n){"use strict";function r(t,n){C=C||e(76),t=t||{},this.objectMode=!!t.objectMode,n instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(L||(L=e(75).StringDecoder),this.decoder=new L(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(76),this instanceof i?(this._readableState=new r(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,n,r,i){var o=f(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,c(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||r||(n=t.decoder.write(n),u=!t.objectMode&&0===n.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=D?e=D:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return R.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(T("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){T("emit readable"),e.emit("readable"),m(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)n=o?r.join(""):1===r.length?r[0]:R.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return T("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;T("need readable",r),(0===t.length||t.length-e0?_(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){T("onunpipe"),e===l&&o()}function i(){T("onend"),e.end()}function o(){T("cleanup"),e.removeListener("close",u),e.removeListener("finish",f),e.removeListener("drain",y),e.removeListener("error",s),e.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),v=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function a(t){T("ondata");var n=e.write(t);!1===n&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||v||(T("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){T("onerror",t),c(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",f),c()}function f(){T("onfinish"),e.removeListener("close",u),c()}function c(){T("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,T("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",r);var y=g(l);e.on("drain",y);var v=!1;return l.on("data",a),e._events&&e._events.error?B(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",f),e.emit("pipe",l),h.flowing||(T("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(8).Buffer;a.WritableState=o;var B=e(9);B.inherits=e(33);var R,A={deprecate:e(84)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(25).EventEmitter)}}();var x=e(8).Buffer;B.inherits(a,R);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{25:25,33:33,52:52,53:53,76:76,8:8,84:84,9:9}],80:[function(e,t,n){arguments[4][73][0].apply(n,arguments)},{73:73,78:78}],81:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],82:[function(e,t,n){(function(n){function r(e){a.call(this,e),this._destroyed=!1}function i(e,t,n){n(null,e)}function o(e){return function(t,n,r){return"function"==typeof t&&(r=n,n=t,t={}),"function"!=typeof n&&(n=i),"function"!=typeof r&&(r=null),e(t,n,r)}}var a=e(80),s=e(86).inherits,u=e(81);s(r,a),r.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;n.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,n){var i=new r(e);return i._transform=t,n&&(i._flush=n),i}),t.exports.ctor=o(function(e,t,n){function i(t){return this instanceof i?(this.options=u(e,t),void r.call(this,this.options)):new i(t)}return s(i,r),i.prototype._transform=t,n&&(i.prototype._flush=n),i}),t.exports.obj=o(function(e,t,n){var i=new r(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,n&&(i._flush=n),i})}).call(this,e(53))},{53:53,80:80,81:81,86:86}],83:[function(e,t,n){"use strict";function r(){this.length=0}r.prototype.push=function(e){var t={item:e};this.last?this.last=this.last.next=t:this.last=this.first=t,this.length++},r.prototype.shift=function(){var e=this.first;if(e)return this.first=e.next,--this.length||(this.last=void 0),e.item},r.prototype.slice=function(e,t){e="undefined"==typeof e?0:e,t="undefined"==typeof t?1/0:t;for(var n=[],r=0,i=this.first;i&&!(--t<0);i=i.next)++r>e&&n.push(i.item);return n},t.exports=r},{}],84:[function(e,t,n){(function(e){function n(e,t){function n(){if(!i){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],85:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],86:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&B(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return m(i)||(i=u(e,i,r)),i}var o=f(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(B(t)){var y=t.name?": "+t.name:"";return e.stylize("[Function"+y+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return c(t)}var v="",b=!1,_=["{","}"];if(p(t)&&(b=!0,_=["[","]"]),B(t)){var w=t.name?": "+t.name:"";v=" [Function"+w+"]"}if(E(t)&&(v=" "+RegExp.prototype.toString.call(t)),S(t)&&(v=" "+Date.prototype.toUTCString.call(t)),x(t)&&(v=" "+c(t)),0===a.length&&(!b||0==t.length))return _[0]+v+_[1];if(r<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=b?l(e,t,r,g,a):a.map(function(n){return h(e,t,r,g,n,b)}),e.seen.pop(),d(k,v,_)}function f(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function m(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function B(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var T=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(f in r)r.hasOwnProperty(f)&&u.push(f);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)c=u[a],l=r[c],h=a>0?",":"",h+=JSON.stringify(c)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},n.parse=function(e){for(var t,n,i,o,a,s,u,f,c,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,r(null,l,h);break;case"t":d+=3,r(!0,l,h);break;case"f":d+=4,r(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",d--;;){if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}n+=i}r(parseFloat(n),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+o+'"'),l,h);break;case"[":f={element:[],index:l.length},l.push(f.element),h.push(f);break;case"{":c={element:{},index:l.length},l.push(c.element),h.push(c);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,h)}}},{}],88:[function(e,t,n){function r(){for(var e={},t=0;t>>1,n(e[r],t)<0?i=r+1:o=r;return i}function H(e,t,n){var r=J(e,t,n);e.splice(r,0,t)}function $(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var y=g.ids[2],v=0,b=y.length;v0||r0||ri.end)return t(null,{total_rows:r,offset:e.skip,rows:[]});var u=[],f=E.docStore.readStream(i),c=We.obj(function(t,n,r){function i(t){var n={id:a.id,key:a.id,value:{rev:c}};if(e.include_docs){n.doc=t,n.doc._rev=n.value.rev,e.conflicts&&(n.doc._conflicts=z(a));for(var i in n.doc._attachments)n.doc._attachments.hasOwnProperty(i)&&(n.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return r();if(l){if("ok"!==e.deleted)return r();n.value.deleted=!0,n.doc=null}u.push(n),r()}var a=t.value,c=Re(a),l=Ae(a,c);if(l){if("ok"!==e.deleted)return void r()}else{if(o-- >0)return void r();if("number"==typeof s&&s--<=0)return f.unpipe(),f.destroy(),void r()}if(e.include_docs){var h=a.rev_map[c];E.bySeqStore.get(d(h),function(e,t){i(t)})}else i()},function(n){at.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,E,e)}).then(function(){t(null,{total_rows:r,offset:e.skip,rows:u})},t),n()}).on("unpipe",function(){c.end()});f.on("error",t),f.pipe(c)})}),w._changes=function(e){function t(){e.done=!0,f&&e.limit&&e.limit0&&(r=e.limit),u.reverse||(u.start=d(e.since||0));var f,c=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;f="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var v=E.bySeqStore.readStream(u),b=We.obj(function(n,u,p){function g(t){function n(n){var r=e.processChange(n,t,e);r.seq=t.seq;var i=l(r);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([r],E,e).then(function(){e.onChange(r)}):e.onChange(r),f&&o.push(r)),void p())}var r=Re(t);if(t.seq!==v)return p();if(a=v,r===b._rev)return n(b);var i=t.rev_map[r];E.bySeqStore.get(d(i),function(e,t){n(t)})}if(r&&s>=r)return t(),p();if(e.cancelled||e.done)return p();var v=y(n.key),b=n.value;if(v===e.since&&!i)return p();if(c&&!c.has(b._id))return p();var _;return(_=h.get(b._id))?g(_):void E.docStore.get(b._id,function(t,n){return e.cancelled||e.done||m.isClosed()||ie(n.id)?p():(h.set(b._id,n),void g(n))})},function(t){return e.cancelled?t():(f&&e.limit&&e.limitr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(qe.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Ie(R,Error),R.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var ft,ct=(new R({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new R({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new R({status:404,error:"not_found",reason:"missing" -})),lt=new R({status:409,error:"conflict",reason:"Document update conflict"}),ht=new R({status:400,error:"bad_request",reason:"_id field must contain a string"}),dt=new R({status:412,error:"missing_id",reason:"_id is required for puts"}),pt=new R({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),gt=new R({status:412,error:"precondition_failed",reason:"Database not open"}),yt=(new R({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new R({status:500,error:"badarg",reason:"Some query argument is invalid"})),vt=(new R({status:400,error:"invalid_request",reason:"Request was invalid"}),new R({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new R({status:500,error:"doc_validation",reason:"Bad special document member"})),bt=new R({status:400,error:"bad_request",reason:"Something wrong with the request"}),mt=(new R({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new R({status:404,error:"not_found",reason:"Database not found"}),new R({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new R({status:500,error:"web_sql_went_bad",reason:"unknown"}),new R({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new R({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new R({status:400,error:"bad_request",reason:"Invalid rev format"})),_t=(new R({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new R({status:412,error:"missing_stub"})),wt=(new R({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),M.name);ft=wt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var Et=ft,kt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),St=D(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),xt=D(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),Bt=function(e){return atob(e)},Rt=function(e){return btoa(e)},At=n.setImmediate||n.setTimeout,jt=32768;Be.prototype.get=function(e,n,r){var i=xe(this,e),o=i.get(n);return o?t.nextTick(function(){r(null,o)}):null===o?t.nextTick(function(){r({name:"NotFoundError"})}):void e.get(n,function(e,t){return e?("NotFoundError"===e.name&&i.set(n,null),r(e)):(i.set(n,t),void r(null,t))})},Be.prototype.batch=function(e){for(var t=0,n=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;n.has(a)||(n.add(a),r.push(o))}e.batch(r,t)};var Ot="document-store",Mt="by-sequence",Tt="attach-store",Lt="attach-binary-store",Ct="local-store",Dt="meta-store",qt=new p,Nt="_local_last_update_seq",It="_local_doc_count",Pt="_local_uuid",Ut="md5-",Wt={encode:we,decode:_e,buffer:!1,type:"cheap-json"},Ft=new x;Te.valid=function(){return!!n.indexedDB},Te.use_prefix=!0;var zt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");zt?Le(zt):B("error",'fruitdown adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(8).Buffer)},{11:11,21:21,25:25,28:28,33:33,36:36,37:37,4:4,43:43,49:49,50:50,53:53,61:61,62:62,8:8,82:82,87:87,pouchdb:"pouchdb"}]},{},[89]); +!function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-r(e)}function o(e){var t,n,i,o,a,s,u=e.length;a=r(e),s=new l(3*u/4-a),i=a>0?u-4:u;var f=0;for(t=0,n=0;t>16&255,s[f++]=o>>8&255,s[f++]=255&o;return 2===a?(o=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,s[f++]=255&o):1===a&&(o=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,s[f++]=o>>8&255,s[f++]=255&o),s}function a(e){return f[e>>18&63]+f[e>>12&63]+f[e>>6&63]+f[63&e]}function s(e,t,n){for(var r,i=[],o=t;oc?c:u+a));return 1===r?(t=e[n-1],i+=f[t>>2],i+=f[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=f[t>>10],i+=f[t>>4&63],i+=f[t<<2&63],i+="="),o.push(i),o.join("")}n.byteLength=i,n.toByteArray=o,n.fromByteArray=u;for(var f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;da)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),f=u.length,c=-1;++ca)throw new RangeError("size is too large");return new i(e)},n.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},n.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{8:8}],8:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return Y(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return Y(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var f;if(i){var c=-1;for(f=n;fs&&(n=s-u),f=n;f>=0;f--){for(var l=!0,h=0;hi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,f,c,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],f=e[i+2],128===(192&u)&&128===(192&f)&&(l=(15&o)<<12|(63&u)<<6|63&f,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],f=e[i+2],c=e[i+3],128===(192&u)&&128===(192&f)&&128===(192&c)&&(l=(15&o)<<18|(63&u)<<12|(63&f)<<6|63&c,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function q(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function I(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||P(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function W(e,t,n,r,i){return i||P(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function K(e){return e<16?"0"+e.toString(16):e.toString(16)}function Y(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var X=e(5),Z=e(31),Q=e(35);n.Buffer=a,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return f(null,e,t,n)},a.allocUnsafe=function(e){return c(null,e)},a.allocUnsafeSlow=function(e){return c(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),f=this.slice(r,i),c=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return B(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var i=Math.pow(2,8*n)-1;q(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):I(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);q(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);q(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):I(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||q(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):I(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return W(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return W(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>2],i=(3&a)<<4;break;case 1:n+=e[i|a>>4], +i=(15&a)<<2;break;case 2:n+=e[i|a>>6],n+=e[63&a],i=0}}return r%3&&(n+=e[i]),n},t.decode=function(e){for(var t=e.length,i=0,o=new r(~~(t/4*3)),a=0,s=0;s>4,a=u<<4&255;break;case 2:o[i++]=a|u>>2,a=u<<6&255;break;case 3:o[i++]=a|u}}return o},t},t.exports(i,t.exports)},{8:8}],11:[function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function s(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(12),n.log=o,n.formatArgs=i,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{12:12}],12:[function(e,t,n){function r(){return n.colors[c++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(f||t);e.diff=o,e.prev=f,e.curr=t,f=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var i=n.formatters[r];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=i.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}r.prototype.toArray=function(){for(var e=this._length,t=new Array(e),n=this._front,r=this._capacity,i=0;i1){var r=this._capacity;if(n+t>r){for(var i=0;i1){var r=this._capacity;if(t+n>r){for(var i=n-1;i>=0;i--){this._checkCapacity(t+1);var r=this._capacity,o=(this._front-1&r-1^r)-r;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=n-1;i>=0;i--){var o=(a-1&r-1^r)-r;this[o]=arguments[i],a=o}return this._front=a,this._length=t+n,t+n}if(0===n)return t;this._checkCapacity(t+1);var r=this._capacity,i=(this._front-1&r-1^r)-r;return this[i]=e,this._length=t+1,this._front=i,t+1},r.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},r.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},r.prototype.get=function(e){var t=e;if(t===(0|t)){var n=this._length;if(t<0&&(t+=n),!(t<0||t>=n))return this[this._front+t&this._capacity-1]}},r.prototype.isEmpty=function(){return 0===this._length},r.prototype.clear=function(){for(var e=this._length,t=this._front,n=this._capacity,r=0;rt){var o=n+r&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=r},{}],22:[function(e,t,n){function r(e,t,n){a(this,{type:e,name:e,cause:"string"!=typeof t?t:n,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),r.call(this,"CustomError",e,t)}function o(e,t,n){var o=function(n,i){r.call(this,t,n,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=n?new n:new i,o}var a=e(24);i.prototype=new Error,t.exports=function(e){var t=function(t,n){return o(e,t,n)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{24:24}],23:[function(e,t,n){var r=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},r.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(22)(t.exports),t.exports.create=t.exports.custom.createError},{22:22}],24:[function(e,t,n){!function(e,n,r){"undefined"!=typeof t&&t.exports?t.exports=r():n[e]=r()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,n){return Object.defineProperty(e,t,n),e}:function(e,t,n){return e[t]=n.value,e},t=function(e,t){var n="object"==typeof t,r=!n&&"string"==typeof t,i=function(e){return n?!!t[e]:!!r&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},n=function(n,r,i,o){var a;if(o=t(i,o),"object"==typeof r){for(a in r)Object.hasOwnProperty.call(r,a)&&(o.value=r[a],e(n,a,o));return n}return e(n,r,o)};return n})},{}],25:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,f;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),f=n.slice(),r=f.length,u=0;u0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],26:[function(e,t,n){(function(e,n){"use strict";function r(e){this._dbName=e}function i(e,t){if(u[e])return s(function(){t(null,u[e])});var n=indexedDB.open(e,1);f[e]=n,n.onupgradeneeded=function(e){var t=e.target.result;1!==e.oldVersion&&t.createObjectStore(a).createIndex("fakeKey","fakeKey")},n.onsuccess=function(n){var r=u[e]=n.target.result;t(null,r)},n.onerror=function(e){var n="Failed to open indexedDB, are you in private browsing mode?";console.error(n),t(e)}}function o(e,t){try{return{txn:e.transaction(a,t)}}catch(e){return{error:e}}}var a="fruitdown",s=n.setImmediate||e.nextTick,u={},f={};r.prototype.getKeys=function(e){i(this._dbName,function(t,n){if(t)return e(t);var r=o(n,"readonly");if(r.error)return e(r.error);var i=r.txn,s=i.objectStore(a);i.onerror=e;var u=[];i.oncomplete=function(){e(null,u.sort())};var f=s.index("fakeKey").openKeyCursor();f.onsuccess=function(e){var t=e.target.result;t&&(u.push(t.primaryKey),t.continue())}})},r.prototype.put=function(e,t,n){i(this._dbName,function(r,i){if(r)return n(r);var s=o(i,"readwrite");if(s.error)return n(s.error);var u=s.txn,f=u.objectStore(a),c="string"==typeof t?t:t.toString();u.onerror=n,u.oncomplete=function(){n()},f.put({value:c,fakeKey:0},e)})},r.prototype.get=function(e,t){i(this._dbName,function(n,r){if(n)return t(n);var i=o(r,"readonly");if(i.error)return t(i.error);var s,u=i.txn,f=u.objectStore(a),c=f.get(e);c.onsuccess=function(e){e.target.result&&(s=e.target.result.value)},u.onerror=t,u.oncomplete=function(){t(null,s)}})},r.prototype.remove=function(e,t){i(this._dbName,function(n,r){if(n)return t(n);var i=o(r,"readwrite");if(i.error)return t(i.error);var s=i.txn,u=s.objectStore(a);u.delete(e),s.onerror=t,s.oncomplete=function(){t()}})},r.destroy=function(e,t){s(function(){f[e]&&f[e].result&&(f[e].result.close(),delete u[e]);var n=indexedDB.deleteDatabase(e);n.onsuccess=function(){f[e]&&(f[e]=null),t(null)},n.onerror=t})},t.exports=r}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{53:53}],27:[function(e,t,n){(function(n){"use strict";function r(e){this._store=new l(e),this._queue=new h}var i="ArrayBuffer:",o=new RegExp("^"+i),a="Uint8Array:",s=new RegExp("^"+a),u="Buff:",f=new RegExp("^"+u),c=e(30),l=e(26),h=e(29),d=e(10);r.prototype.sequentialize=function(e,t){this._queue.add(t,e)},r.prototype.init=function(e){var t=this;t.sequentialize(e,function(e){t._store.getKeys(function(n,r){return n?e(n):(t._keys=r,e())})})},r.prototype.keys=function(e){var t=this;t.sequentialize(e,function(e){e(null,t._keys.slice())})},r.prototype.setItem=function(e,t,r){var i=this;i.sequentialize(r,function(r){n.isBuffer(t)&&(t=u+d.encode(t));var o=c.sortedIndexOf(i._keys,e);i._keys[o]!==e&&i._keys.splice(o,0,e),i._store.put(e,t,r)})},r.prototype.getItem=function(e,t){var n=this;n.sequentialize(t,function(t){n._store.get(e,function(e,n){return e?t(e):"undefined"==typeof n||null===n?t(new Error("NotFound")):("undefined"!=typeof n&&(f.test(n)?n=d.decode(n.substring(u.length)):o.test(n)?(n=n.substring(i.length),n=new ArrayBuffer(atob(n).split("").map(function(e){return e.charCodeAt(0)}))):s.test(n)&&(n=n.substring(a.length),n=new Uint8Array(atob(n).split("").map(function(e){return e.charCodeAt(0)})))),void t(null,n))})})},r.prototype.removeItem=function(e,t){var n=this;n.sequentialize(t,function(t){var r=c.sortedIndexOf(n._keys,e);n._keys[r]===e?(n._keys.splice(r,1),n._store.remove(e,function(e){return e?t(e):void t()})):t()})},r.prototype.length=function(e){var t=this;t.sequentialize(e,function(e){e(null,t._keys.length)})},t.exports=r}).call(this,{isBuffer:e(34)})},{10:10,26:26,29:29,30:30,34:34}],28:[function(e,t,n){(function(n,r,i){"use strict";function o(e,t){c.call(this,e),this._reverse=!!t.reverse,this._endkey=t.end,this._startkey=t.start,this._gt=t.gt,this._gte=t.gte,this._lt=t.lt,this._lte=t.lte,this._exclusiveStart=t.exclusiveStart,this._limit=t.limit,this._count=0,this.onInitCompleteListeners=[]}function a(e){return this instanceof a?(f.call(this,e),void(this.container=new l(e))):new a(e)}function s(e,t){if(null===e||void 0===e)return new Error(t+" cannot be `null` or `undefined`");if(null===e||void 0===e)return new Error(t+" cannot be `null` or `undefined`");if("key"===t){if(e instanceof Boolean)return new Error(t+" cannot be `null` or `undefined`");if(""===e)return new Error(t+" cannot be empty")}if(0===e.toString().indexOf("[object ArrayBuffer]")&&(0===e.byteLength||void 0===e.byteLength))return new Error(t+" cannot be an empty Buffer");if(i.isBuffer(e)){if(0===e.length)return new Error(t+" cannot be an empty Buffer")}else if(""===String(e))return new Error(t+" cannot be an empty String")}var u=e(33),f=e(3).AbstractLevelDOWN,c=e(3).AbstractIterator,l=e(27),h=e(26),d=e(30),p=r.setImmediate||n.nextTick;u(o,c),o.prototype._init=function(e){p(function(){e()})},o.prototype._next=function(e){function t(){if(n._pos===n._keys.length||n._pos<0)return e();var t=n._keys[n._pos];return n._endkey&&(n._reverse?tn._endkey)?e():n._limit&&n._limit>0&&n._count++>=n._limit?e():n._lt&&t>=n._lt||n._lte&&t>n._lte||n._gt&&t<=n._gt||n._gte&&t=n._keys.length||o<0?void 0:n._keys[o];n._pos=o,n._reverse?(n._exclusiveStart||a!==n._startkey)&&n._pos--:n._exclusiveStart&&a===n._startkey&&n._pos++}else n._pos=n._reverse?n._keys.length-1:0;t(),n.initCompleted=!0;for(var s=-1;++s-1){var o=JSON.parse(r);r=o.data}n(null,r)}))},a.prototype._del=function(e,t,n){var r=s(e,"key");return r?p(function(){n(r)}):(i.isBuffer(e)||(e=String(e)),void this.container.removeItem(e,n))},a.prototype._batch=function(e,t,n){var r=this;p(function(){function o(){++l===e.length&&n(c)}var a,u,f,c,l=0;if(Array.isArray(e)&&e.length)for(var h=0;h>>1,e[n]>1,c=-7,l=n?i-1:0,h=n?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-c)-1,d>>=-c,c+=s;c>0;o=256*o+e[t+l],l+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=r;c>0;a=256*a+e[t+l],l+=h,c-=8);if(0===o)o=1-f;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,r),o-=f}return(d?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,u,f=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=c?(s=0,a=c):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,f-=8);e[n+d-p]|=128*g; +}},{}],32:[function(e,t,n){(function(e){"use strict";function n(){c=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[r],e):e[r]}),n},r.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(n,r){return{key:t.decodeKey(n,e),value:t.decodeValue(r,e)}}:e.keys?function(n){return t.decodeKey(n,e)}:e.values?function(n,r){return t.decodeValue(r,e)}:function(){}},r.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},r.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{38:38}],38:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},n.id=n.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],39:[function(e,t,n){var r=e(23).create,i=r("LevelUPError"),o=r("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:r("InitializationError",i),OpenError:r("OpenError",i),ReadError:r("ReadError",i),WriteError:r("WriteError",i),NotFoundError:o,EncodingError:r("EncodingError",i)}},{23:23}],40:[function(e,t,n){function r(e,t){return this instanceof r?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new r(e,t)}var i=e(33),o=e(61).Readable,a=e(41),s=e(39).EncodingError;t.exports=r,i(r,o),r.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,n,r){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===n&&void 0===r)e.push(null);else{if(!e._decoder)return e.push({key:n,value:r});try{var r=e._decoder(n,r)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(r)}}})},r.prototype.destroy=r.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{33:33,39:39,41:41,61:61}],41:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],42:[function(e,t,n){function r(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(44),o=e(39).WriteError,a=i.getOptions,s=i.dispatchError;r.prototype.put=function(e,t,n){n=a(n);var r=this._codec.encodeKey(e,n),i=this._codec.encodeValue(t,n);try{this.batch.put(r,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:r,value:i}),this.length++,this},r.prototype.del=function(e,t){t=a(t);var n=this._codec.encodeKey(e,t);try{this.batch.del(n)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:n}),this.length++,this},r.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},r.prototype.write=function(e){var t=this._levelup,n=this.ops;try{this.batch.write(function(r){return r?s(t,new o(r),e):(t.emit("batch",n),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=r},{39:39,44:44}],43:[function(e,t,n){(function(n){function r(e,t){return"function"==typeof e?e:t}function i(e,t,r){if(!(this instanceof i))return new i(e,t,r);var o;if(f.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{},t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e,e=null),"function"==typeof t&&(r=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),r)return n.nextTick(function(){r(o)});throw o}t=B(t),this.options=h(R,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(r)}function o(e,t,n){if(!e._isOpening()&&!e.isOpen())return j(e,new b("Database is not open"),n),!0}function a(e,t,n){j(e,new v(t),n)}function s(e,t,n){j(e,new b(t),n)}function u(e){return function(t,n){A()[e](t,n||function(){})}}var f=e(25).EventEmitter,c=e(87).inherits,l=e(87).deprecate,h=e(47),d=e(54),p=e(14),g=e(40),y=e(39),v=y.WriteError,b=y.ReadError,m=y.NotFoundError,_=y.OpenError,w=y.EncodingError,E=y.InitializationError,k=e(44),S=e(42),x=e(45),B=k.getOptions,R=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;c(i,f),i.prototype.open=function(e){var t,r,i=this;return this.isOpen()?(e&&n.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),r=t(this.location),void r.open(this.options,function(t){return t?j(i,new _(t),e):(i.db.setDb(r),i.db=r,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return n.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,n){var i,a=this;if(n=r(t,n),!o(this,t,n)){if(null===e||void 0===e||"function"!=typeof n)return s(this,"get() requires key and callback arguments",n);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(r,i){if(r)return r=/notfound/i.test(r)||r.notFound?new m("Key not found in database ["+e+"]",r):new b(r),j(a,r,n);if(n){try{i=a._codec.decodeValue(i,t)}catch(e){return n(new w(e))}n(null,i)}})}},i.prototype.put=function(e,t,n,i){var s,u,f=this;return i=r(n,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,n,i)||(n=B(n),s=this._codec.encodeKey(e,n),u=this._codec.encodeValue(t,n),this.db.put(s,u,n,function(n){return n?j(f,new v(n),i):(f.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,n){var i,s=this;return n=r(t,n),null===e||void 0===e?a(this,"del() requires a key argument",n):void(o(this,t,n)||(t=B(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new v(t),n):(s.emit("del",e),void(n&&n()))})))},i.prototype.batch=function(e,t,n){var i,s=this;return arguments.length?(n=r(t,n),Array.isArray(e)?void(o(this,t,n)||(t=B(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new v(t),n):(s.emit("batch",e),void(n&&n()))}))):a(this,"batch() requires an array argument",n)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,n,i){var o,a,u=this;return i=r(n,i),n=B(n),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,n),a=this._codec.encodeKey(t,n),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new _(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(39),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(53))},{14:14,25:25,39:39,40:40,42:42,44:44,45:45,47:47,53:53,54:54,87:87}],44:[function(e,t,n){function r(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,n=e(48).devDependencies.leveldown;try{t=e(6).version}catch(e){throw o(e)}if(!e(6).satisfies(t,n))throw new f("Installed version of LevelDOWN ("+t+") does not match required version ("+n+")");try{return u=e(6)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new f(c(t,e.message))}function a(e,t,n){"function"==typeof n?n(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,f=(e(47),e(39).LevelUPError),c=e(87).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:r,getLevelDOWN:i,dispatchError:a,isDefined:s}},{39:39,47:47,48:48,6:6,87:87}],45:[function(e,t,n){arguments[4][37][0].apply(n,arguments)},{37:37,46:46}],46:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],47:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],48:[function(e,t,n){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],49:[function(e,t,n){"use strict";function r(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=b,this.queue=[],this.outcome=void 0,e!==r&&u(this,e)}function o(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function a(e,t,n){p(function(){var r;try{r=t(n)}catch(t){return g.reject(e,t)}r===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,r)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function n(t){o||(o=!0,g.reject(e,t))}function r(t){o||(o=!0,g.resolve(e,t))}function i(){t(r,n)}var o=!1,a=f(i);"error"===a.status&&n(a.value)}function f(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}function c(e){return e instanceof this?e:g.resolve(new this(r),e)}function l(e){var t=new this(r);return g.reject(t,e)}function h(e){function t(e,t){function r(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(f,a))}n.resolve(e).then(r,function(e){o||(o=!0,g.reject(f,e))})}var n=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,f=new this(r);++un?1:0};var a=n.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=n.lowerBound=function(e){var t=a(e);return t&&e[t]};n.lowerBoundInclusive=function(e){return!t(e,"gt")},n.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=n.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},f=n.upperBoundExclusive=function(e){return!!t(e,"lt")},c=n.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=n.upperBound=function(e){var t=c(e);return t&&e[t]};n.toLtgt=function(e,r,i,a,s){r=r||{},i=i||o;var u=arguments.length>3,f=n.lowerBoundKey(e),c=n.upperBoundKey(e);return f?"gt"===f?r.gt=i(e.gt,!1):r.gte=i(e[f],!1):u&&(r.gte=i(a,!1)),c?"lt"===c?r.lt=i(e.lt,!0):r.lte=i(e[c],!0):u&&(r.lte=i(s,!0)),null!=e.reverse&&(r.reverse=!!e.reverse),t(r,"max")&&delete r.max,t(r,"min")&&delete r.min,t(r,"start")&&delete r.start,t(r,"end")&&delete r.end,r},n.contains=function(e,t,i){i=i||n.compare;var o=s(e);if(r(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var c=l(e);if(r(c)){var a=i(t,c);if(a>0||0===a&&f(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(34)})},{34:34}],51:[function(e,t,n){function r(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*f;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=f?Math.round(e/f)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,c,"day")||a(e,f,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e1)for(var n=1;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||r||(n=t.decoder.write(n)),t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):(t.reading=!1,t.buffer.push(n)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.length>0?l(e):_(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?n.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){p(e,t)}))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(x.listenerCount(e,"data")>0&&b(e))):void(r.ranOut=!0)}function v(){this._readableState.ranOut&&(this._readableState.ranOut=!1,y(this))}function b(e,t){var r=e._readableState;if(r.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=B.prototype.pipe,e.on=e.addListener=B.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?n.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function m(e,t){var n,r=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(a)n=r.shift();else if(!e||e>=i)n=o?r.join(""):S.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return n=null,t.length>0&&t.decoder&&(n=m(e,t),t.length-=n.length),0===t.length&&_(this),n;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(r,t)),n=e>0?m(e,t):null,null===n&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&_(this),n},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){e===c&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),c.removeListener("end",i),c.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){f(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),f()}function u(){e.removeListener("close",s),f()}function f(){c.unpipe(e)}var c=this,l=this._readableState; +switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e];break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,d=h?i:o;l.endEmitted?n.nextTick(d):c.once("end",d),e.on("unpipe",r);var p=g(c);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",c),l.flowing||(this.on("readable",v),l.flowing=!0,n.nextTick(function(){y(c)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1;for(var i=0;i>>32-i,n)}function n(e,n,r,i,o,a,s){return t(n&r|~n&i,e,n,o,a,s)}function r(e,n,r,i,o,a,s){return t(n&i|r&~i,e,n,o,a,s)}function i(e,n,r,i,o,a,s){return t(n^r^i,e,n,o,a,s)}function o(e,n,r,i,o,a,s){return t(r^(n|~i),e,n,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],f=e[3];a=n(a,s,u,f,t[0],7,-680876936),f=n(f,a,s,u,t[1],12,-389564586),u=n(u,f,a,s,t[2],17,606105819),s=n(s,u,f,a,t[3],22,-1044525330),a=n(a,s,u,f,t[4],7,-176418897),f=n(f,a,s,u,t[5],12,1200080426),u=n(u,f,a,s,t[6],17,-1473231341),s=n(s,u,f,a,t[7],22,-45705983),a=n(a,s,u,f,t[8],7,1770035416),f=n(f,a,s,u,t[9],12,-1958414417),u=n(u,f,a,s,t[10],17,-42063),s=n(s,u,f,a,t[11],22,-1990404162),a=n(a,s,u,f,t[12],7,1804603682),f=n(f,a,s,u,t[13],12,-40341101),u=n(u,f,a,s,t[14],17,-1502002290),s=n(s,u,f,a,t[15],22,1236535329),a=r(a,s,u,f,t[1],5,-165796510),f=r(f,a,s,u,t[6],9,-1069501632),u=r(u,f,a,s,t[11],14,643717713),s=r(s,u,f,a,t[0],20,-373897302),a=r(a,s,u,f,t[5],5,-701558691),f=r(f,a,s,u,t[10],9,38016083),u=r(u,f,a,s,t[15],14,-660478335),s=r(s,u,f,a,t[4],20,-405537848),a=r(a,s,u,f,t[9],5,568446438),f=r(f,a,s,u,t[14],9,-1019803690),u=r(u,f,a,s,t[3],14,-187363961),s=r(s,u,f,a,t[8],20,1163531501),a=r(a,s,u,f,t[13],5,-1444681467),f=r(f,a,s,u,t[2],9,-51403784),u=r(u,f,a,s,t[7],14,1735328473),s=r(s,u,f,a,t[12],20,-1926607734),a=i(a,s,u,f,t[5],4,-378558),f=i(f,a,s,u,t[8],11,-2022574463),u=i(u,f,a,s,t[11],16,1839030562),s=i(s,u,f,a,t[14],23,-35309556),a=i(a,s,u,f,t[1],4,-1530992060),f=i(f,a,s,u,t[4],11,1272893353),u=i(u,f,a,s,t[7],16,-155497632),s=i(s,u,f,a,t[10],23,-1094730640),a=i(a,s,u,f,t[13],4,681279174),f=i(f,a,s,u,t[0],11,-358537222),u=i(u,f,a,s,t[3],16,-722521979),s=i(s,u,f,a,t[6],23,76029189),a=i(a,s,u,f,t[9],4,-640364487),f=i(f,a,s,u,t[12],11,-421815835),u=i(u,f,a,s,t[15],16,530742520),s=i(s,u,f,a,t[2],23,-995338651),a=o(a,s,u,f,t[0],6,-198630844),f=o(f,a,s,u,t[7],10,1126891415),u=o(u,f,a,s,t[14],15,-1416354905),s=o(s,u,f,a,t[5],21,-57434055),a=o(a,s,u,f,t[12],6,1700485571),f=o(f,a,s,u,t[3],10,-1894986606),u=o(u,f,a,s,t[10],15,-1051523),s=o(s,u,f,a,t[1],21,-2054922799),a=o(a,s,u,f,t[8],6,1873313359),f=o(f,a,s,u,t[15],10,-30611744),u=o(u,f,a,s,t[6],15,-1560198380),s=o(s,u,f,a,t[13],21,1309151649),a=o(a,s,u,f,t[4],6,-145523070),f=o(f,a,s,u,t[11],10,-1120210379),u=o(u,f,a,s,t[2],15,718787259),s=o(s,u,f,a,t[9],21,-343485551),e[0]=m(a,e[0]),e[1]=m(s,e[1]),e[2]=m(u,e[2]),e[3]=m(f,e[3])}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function f(e){var t,n,r,i,o,u,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,r[14]=o,r[15]=u,a(c,r),c}function c(e){var t,n,r,i,o,s,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,r[14]=o,r[15]=s,a(c,r),c}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=_[e>>8*t+4&15]+_[e>>8*t&15];return n}function h(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,a,s,u=this.byteLength,f=t(n,u),c=u;return r!==e&&(c=t(r,u)),f>c?new ArrayBuffer(0):(i=c-f,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,f,i),a.set(s),o)}}(),b.prototype.append=function(e){return this.appendBinary(d(e)),this},b.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},b.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},b.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},b.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},b.prototype._finish=function(e,t){var n,r,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=r,e[15]=i,a(this._hash,e)},b.hash=function(e,t){return b.hashBinary(d(e),t)},b.hashBinary=function(e,t){var n=f(e),r=h(n);return t?v(r):r},b.ArrayBuffer=function(){this.reset()},b.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.ArrayBuffer.prototype.getState=function(){var e=b.prototype.getState.call(this);return e.buff=g(e.buff),e},b.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),b.prototype.setState.call(this,e)},b.ArrayBuffer.prototype.destroy=b.prototype.destroy,b.ArrayBuffer.prototype._finish=b.prototype._finish,b.ArrayBuffer.hash=function(e,t){var n=c(new Uint8Array(e)),r=h(n);return t?v(r):r},b})},{}],63:[function(e,t,n){function r(){i.call(this)}t.exports=r;var i=e(25).EventEmitter,o=e(33);o(r,i),r.Readable=e(72),r.Writable=e(74),r.Duplex=e(64),r.Transform=e(73),r.PassThrough=e(71),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&f.pause&&f.pause()}function r(){f.readable&&f.resume&&f.resume()}function o(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){f.removeListener("data",n),e.removeListener("drain",r),f.removeListener("end",o),f.removeListener("close",a),f.removeListener("error",s),e.removeListener("error",s),f.removeListener("end",u),f.removeListener("close",u),e.removeListener("close",u)}var f=this;f.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(f.on("end",o),f.on("close",a));var c=!1;return f.on("error",s),e.on("error",s),f.on("end",u),f.on("close",u),e.on("close",u),e.emit("pipe",f),e}},{25:25,33:33,64:64,71:71,72:72,73:73,74:74}],64:[function(e,t,n){t.exports=e(65)},{65:65}],65:[function(e,t,n){"use strict";function r(e){return this instanceof r?(f.call(this,e),c.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e(52),u=e(9);u.inherits=e(33);var f=e(67),c=e(69);u.inherits(r,f);for(var l=a(c.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var f;!t.decoder||i||r||(n=t.decoder.write(n),f=!t.objectMode&&0===n.length),i||(t.reading=!1),f||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function c(e,t){var n=null;return L.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(N("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){N("emit readable"),e.emit("readable"),_(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=E(e,t.buffer,t.decoder),n}function E(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=C.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(B,t,e))}function B(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function R(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return N("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;N("need readable",r),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){N("onunpipe"),e===h&&a()}function o(){N("onend"),e.end()}function a(){N("cleanup"),e.removeListener("close",f),e.removeListener("finish",c),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),b=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){N("ondata"),m=!1;var n=e.write(t);!1!==n||m||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!b&&(N("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,m=!0),h.pause())}function u(t){N("onerror",t),l(),e.removeListener("error",u),0===T(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",c),l()}function c(){N("onfinish"),e.removeListener("close",f),l()}function l(){N("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,N("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var v=y(h);e.on("drain",v);var b=!1,m=!1;return h.on("data",s),r(e,"error",u),e.once("close",f),e.once("finish",c),e.emit("pipe",h),d.flowing||(N("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(9);x.inherits=e(33);var B,R={deprecate:e(84)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(25).EventEmitter)}}();var A=e(8).Buffer,j=e(7);x.inherits(a,B);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:R.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{25:25,33:33,52:52,53:53,65:65,7:7,8:8,84:84,9:9}],70:[function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(e(8).Buffer,e(7));t.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},{7:7,8:8}],71:[function(e,t,n){t.exports=e(66)},{66:66}],72:[function(e,t,n){(function(r){var i=function(){try{return e("stream")}catch(e){}}();n=t.exports=e(67),n.Stream=i||n,n.Readable=n,n.Writable=e(69),n.Duplex=e(65),n.Transform=e(68),n.PassThrough=e(66),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(53))},{53:53,65:65,66:66,67:67,68:68,69:69}],73:[function(e,t,n){t.exports=e(68)},{68:68}],74:[function(e,t,n){t.exports=e(69)},{69:69}],75:[function(e,t,n){function r(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(8).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},f=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};f.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},f.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},f.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}},{8:8}],76:[function(e,t,n){arguments[4][65][0].apply(n,arguments)},{33:33,52:52,65:65,77:77,79:79,9:9}],77:[function(e,t,n){(function(n){"use strict";function r(t,n){C=C||e(76),t=t||{},this.objectMode=!!t.objectMode,n instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(L||(L=e(75).StringDecoder),this.decoder=new L(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(76),this instanceof i?(this._readableState=new r(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,n,r,i){var o=f(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,c(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||r||(n=t.decoder.write(n),u=!t.objectMode&&0===n.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=D?e=D:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return R.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(T("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){T("emit readable"),e.emit("readable"),m(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)n=o?r.join(""):1===r.length?r[0]:R.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return T("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;T("need readable",r),(0===t.length||t.length-e0?_(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){T("onunpipe"),e===l&&o()}function i(){T("onend"),e.end()}function o(){T("cleanup"),e.removeListener("close",u),e.removeListener("finish",f),e.removeListener("drain",y),e.removeListener("error",s),e.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),v=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function a(t){T("ondata");var n=e.write(t);!1===n&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||v||(T("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){T("onerror",t),c(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",f),c()}function f(){T("onfinish"),e.removeListener("close",u),c()}function c(){T("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,T("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",r);var y=g(l);e.on("drain",y);var v=!1;return l.on("data",a),e._events&&e._events.error?B(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",f),e.emit("pipe",l),h.flowing||(T("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(8).Buffer;a.WritableState=o;var B=e(9);B.inherits=e(33);var R,A={deprecate:e(84)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(25).EventEmitter)}}();var x=e(8).Buffer;B.inherits(a,R);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{25:25,33:33,52:52,53:53,76:76,8:8,84:84,9:9}],80:[function(e,t,n){arguments[4][73][0].apply(n,arguments)},{73:73,78:78}],81:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],82:[function(e,t,n){(function(n){function r(e){a.call(this,e),this._destroyed=!1}function i(e,t,n){n(null,e)}function o(e){return function(t,n,r){return"function"==typeof t&&(r=n,n=t,t={}),"function"!=typeof n&&(n=i),"function"!=typeof r&&(r=null),e(t,n,r)}}var a=e(80),s=e(87).inherits,u=e(81);s(r,a),r.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;n.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,n){var i=new r(e);return i._transform=t,n&&(i._flush=n),i}),t.exports.ctor=o(function(e,t,n){function i(t){return this instanceof i?(this.options=u(e,t),void r.call(this,this.options)):new i(t)}return s(i,r),i.prototype._transform=t,n&&(i.prototype._flush=n),i}),t.exports.obj=o(function(e,t,n){var i=new r(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,n&&(i._flush=n),i})}).call(this,e(53))},{53:53,80:80,81:81,87:87}],83:[function(e,t,n){"use strict";function r(){this.length=0}r.prototype.push=function(e){var t={item:e};this.last?this.last=this.last.next=t:this.last=this.first=t,this.length++},r.prototype.shift=function(){var e=this.first;if(e)return this.first=e.next,--this.length||(this.last=void 0),e.item},r.prototype.slice=function(e,t){e="undefined"==typeof e?0:e,t="undefined"==typeof t?1/0:t;for(var n=[],r=0,i=this.first;i&&!(--t<0);i=i.next)++r>e&&n.push(i.item);return n},t.exports=r},{}],84:[function(e,t,n){(function(e){function n(e,t){function n(){if(!i){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],85:[function(e,t,n){arguments[4][33][0].apply(n,arguments)},{33:33}],86:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],87:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&B(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return m(i)||(i=u(e,i,r)),i}var o=f(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(B(t)){var y=t.name?": "+t.name:"";return e.stylize("[Function"+y+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return c(t)}var v="",b=!1,_=["{","}"];if(p(t)&&(b=!0,_=["[","]"]),B(t)){var w=t.name?": "+t.name:"";v=" [Function"+w+"]"}if(E(t)&&(v=" "+RegExp.prototype.toString.call(t)),S(t)&&(v=" "+Date.prototype.toUTCString.call(t)),x(t)&&(v=" "+c(t)),0===a.length&&(!b||0==t.length))return _[0]+v+_[1];if(r<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=b?l(e,t,r,g,a):a.map(function(n){return h(e,t,r,g,n,b)}),e.seen.pop(),d(k,v,_)}function f(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function m(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function B(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var T=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(f in r)r.hasOwnProperty(f)&&u.push(f);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)c=u[a],l=r[c],h=a>0?",":"",h+=JSON.stringify(c)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},n.parse=function(e){for(var t,n,i,o,a,s,u,f,c,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,r(null,l,h);break;case"t":d+=3,r(!0,l,h);break;case"f":d+=4,r(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",d--;;){if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}n+=i}r(parseFloat(n),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+o+'"'),l,h);break;case"[":f={element:[],index:l.length},l.push(f.element),h.push(f);break;case"{":c={element:{},index:l.length},l.push(c.element),h.push(c);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,h)}}},{}],89:[function(e,t,n){function r(){for(var e={},t=0;t>>1,n(e[r],t)<0?i=r+1:o=r;return i}function H(e,t,n){var r=J(e,t,n);e.splice(r,0,t)}function $(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var y=g.ids[2],v=0,b=y.length;v0||r0||ri.end)return t(null,{total_rows:r,offset:e.skip,rows:[]});var u=[],f=k.docStore.readStream(i),c=We.obj(function(t,n,r){function i(t){var n={id:a.id,key:a.id,value:{rev:c}};if(e.include_docs){n.doc=t,n.doc._rev=n.value.rev,e.conflicts&&(n.doc._conflicts=z(a));for(var i in n.doc._attachments)n.doc._attachments.hasOwnProperty(i)&&(n.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return r();if(l){if("ok"!==e.deleted)return r();n.value.deleted=!0,n.doc=null}u.push(n),r()}var a=t.value,c=Re(a),l=Ae(a,c);if(l){if("ok"!==e.deleted)return void r()}else{if(o-- >0)return void r();if("number"==typeof s&&s--<=0)return f.unpipe(),f.destroy(),void r()}if(e.include_docs){var h=a.rev_map[c];k.bySeqStore.get(y(h),function(e,t){i(t)})}else i()},function(n){it.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,k,e)}).then(function(){t(null,{total_rows:r,offset:e.skip,rows:u})},t),n()}).on("unpipe",function(){c.end()});f.on("error",t),f.pipe(c)})}),E._changes=function(e){function t(){e.done=!0,f&&e.limit&&e.limit0&&(r=e.limit),u.reverse||(u.start=y(e.since||0));var f,c=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;f="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var d=k.bySeqStore.readStream(u),b=We.obj(function(n,u,d){function p(t){function n(n){var r=e.processChange(n,t,e);r.seq=t.seq;var i=l(r);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([r],k,e).then(function(){e.onChange(r)}):e.onChange(r),f&&o.push(r)),void d())}var r=Re(t);if(t.seq!==g)return d();if(a=g,r===b._rev)return n(b);var i=t.rev_map[r];k.bySeqStore.get(y(i),function(e,t){n(t)})}if(r&&s>=r)return t(),d();if(e.cancelled||e.done)return d();var g=v(n.key),b=n.value;if(g===e.since&&!i)return d();if(c&&!c.has(b._id))return d();var m;return(m=h.get(b._id))?p(m):void k.docStore.get(b._id,function(t,n){return e.cancelled||e.done||w.isClosed()||ie(n.id)?d():(h.set(b._id,n),void p(n))})},function(t){return e.cancelled?t():(f&&e.limit&&e.limitr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(qe.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Ie(R,Error),R.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var st,ut=(new R({status:401,error:"unauthorized",reason:"Name or password is incorrect." +}),new R({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new R({status:404,error:"not_found",reason:"missing"})),ft=new R({status:409,error:"conflict",reason:"Document update conflict"}),ct=new R({status:400,error:"bad_request",reason:"_id field must contain a string"}),lt=new R({status:412,error:"missing_id",reason:"_id is required for puts"}),ht=new R({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),dt=new R({status:412,error:"precondition_failed",reason:"Database not open"}),pt=(new R({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new R({status:500,error:"badarg",reason:"Some query argument is invalid"})),gt=(new R({status:400,error:"invalid_request",reason:"Request was invalid"}),new R({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new R({status:500,error:"doc_validation",reason:"Bad special document member"})),yt=new R({status:400,error:"bad_request",reason:"Something wrong with the request"}),vt=(new R({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new R({status:404,error:"not_found",reason:"Database not found"}),new R({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new R({status:500,error:"web_sql_went_bad",reason:"unknown"}),new R({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new R({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new R({status:400,error:"bad_request",reason:"Invalid rev format"})),bt=(new R({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new R({status:412,error:"missing_stub"})),mt=(new R({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),M.name);st=mt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var _t=st,wt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Et=D(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),kt=D(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),St=function(e){return atob(e)},xt=function(e){return btoa(e)},Bt=n.setImmediate||n.setTimeout,Rt=32768;Be.prototype.get=function(e,n,r){var i=xe(this,e),o=i.get(n);return o?t.nextTick(function(){r(null,o)}):null===o?t.nextTick(function(){r({name:"NotFoundError"})}):void e.get(n,function(e,t){return e?("NotFoundError"===e.name&&i.set(n,null),r(e)):(i.set(n,t),void r(null,t))})},Be.prototype.batch=function(e){for(var t=0,n=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;n.has(a)||(n.add(a),r.push(o))}e.batch(r,t)};var At="document-store",jt="by-sequence",Ot="attach-store",Mt="attach-binary-store",Tt="local-store",Lt="meta-store",Ct=new p,Dt="_local_last_update_seq",qt="_local_doc_count",Nt="_local_uuid",It="md5-",Pt={encode:we,decode:_e,buffer:!1,type:"cheap-json"},Ut=new x;Te.valid=function(){return!!n.indexedDB},Te.use_prefix=!0;var Wt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");Wt?Le(Wt):B("error",'fruitdown adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(8).Buffer)},{11:11,21:21,25:25,28:28,33:33,36:36,37:37,4:4,43:43,49:49,50:50,53:53,61:61,62:62,8:8,82:82,88:88,pouchdb:"pouchdb"}]},{},[90]); diff --git a/lib/pouchdb/dist/pouchdb.js b/lib/pouchdb/dist/pouchdb.js index 39f4ceb1..9c7bac06 100644 --- a/lib/pouchdb/dist/pouchdb.js +++ b/lib/pouchdb/dist/pouchdb.js @@ -1,4 +1,4 @@ -// PouchDB 6.0.4 +// PouchDB 6.0.6 // // (c) 2012-2016 Dale Harvey and the PouchDB team // PouchDB may be freely distributed under the Apache license, version 2.0. @@ -5349,7 +5349,7 @@ PouchDB.defaults = function (defaultOpts) { }; // managed automatically by set-version.js -var version = "6.0.4"; +var version = "6.0.6"; PouchDB.version = version; @@ -10402,7 +10402,7 @@ function HttpPouch(opts, callback) { // Update/create the document ajax$$(opts, { method: 'PUT', - url: genDBUrl(host, encodeURIComponent(doc._id)), + url: genDBUrl(host, encodeDocId(doc._id)), body: doc }, function (err, result) { if (err) { @@ -11228,13 +11228,90 @@ function createView(opts) { return promiseForView; } -function evalfunc(func, emit, sum, log, isArray, toJSON) { +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} + +inherits(QueryParseError, Error); + +function NotFoundError(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError); + } catch (e) {} +} + +inherits(NotFoundError, Error); + +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} + +inherits(BuiltInError, Error); + +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} + +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} + +var log$2 = guardedConsole.bind(null, 'log'); +var isArray = Array.isArray; +var toJSON = JSON.parse; + +function evalFunctionWithEval(func, emit) { return scopedEval( "return (" + func.replace(/;\s*$/, "") + ");", { emit: emit, sum: sum, - log: log, + log: log$2, isArray: isArray, toJSON: toJSON } @@ -11312,8 +11389,6 @@ var persistentQueues = {}; var tempViewQueue = new TaskQueue$1(); var CHANGES_BATCH_SIZE$1 = 50; -var log$2 = guardedConsole.bind(null, 'log'); - function parseViewName(name) { // can be either 'ddocname/viewname' or just 'viewname' // (where the ddoc name is the same) @@ -11397,43 +11472,6 @@ function postprocessAttachments(opts) { }; } -function createBuiltInError(name) { - var message = 'builtin ' + name + - ' function requires map values to be numbers' + - ' or number arrays'; - return new BuiltInError(message); -} - -function sum(values) { - var result = 0; - for (var i = 0, len = values.length; i < len; i++) { - var num = values[i]; - if (typeof num !== 'number') { - if (Array.isArray(num)) { - // lists of numbers are also allowed, sum them separately - result = typeof result === 'number' ? [result] : result; - for (var j = 0, jLen = num.length; j < jLen; j++) { - var jNum = num[j]; - if (typeof jNum !== 'number') { - throw createBuiltInError('_sum'); - } else if (typeof result[j] === 'undefined') { - result.push(jNum); - } else { - result[j] += jNum; - } - } - } else { // not array/number - throw createBuiltInError('_sum'); - } - } else if (typeof result === 'number') { - result += num; - } else { // add number to array - result[0] += num; - } - } - return result; -} - var builtInReduce = { _sum: function (keys, values) { return sum(values); @@ -11788,8 +11826,7 @@ function updateViewInQueue(view) { return origMap(doc, emit); }; } else { - mapFun = evalfunc(view.mapFun.toString(), emit, sum, log$2, Array.isArray, - JSON.parse); + mapFun = evalFunctionWithEval(view.mapFun.toString(), emit); } var currentSeq = view.seq || 0; @@ -11882,8 +11919,7 @@ function reduceView(view, results, options) { if (builtInReduce[view.reduceFun]) { reduceFun = builtInReduce[view.reduceFun]; } else { - reduceFun = evalfunc( - view.reduceFun.toString(), null, sum, log$2, Array.isArray, JSON.parse); + reduceFun = evalFunctionWithEval(view.reduceFun.toString()); } var groups = []; @@ -12230,41 +12266,6 @@ var query = function (fun, opts, callback) { return promise; }; -function QueryParseError(message) { - this.status = 400; - this.name = 'query_parse_error'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, QueryParseError); - } catch (e) {} -} - -inherits(QueryParseError, Error); - -function NotFoundError(message) { - this.status = 404; - this.name = 'not_found'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, NotFoundError); - } catch (e) {} -} - -inherits(NotFoundError, Error); - -function BuiltInError(message) { - this.status = 500; - this.name = 'invalid_value'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, BuiltInError); - } catch (e) {} -} - -inherits(BuiltInError, Error); var mapreduce = { query: query, @@ -13518,6 +13519,10 @@ PouchDB.plugin(IDBPouch) .plugin(mapreduce) .plugin(replication); +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. + module.exports = PouchDB; }).call(this,_dereq_(11),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"1":1,"11":11,"12":12,"13":13,"14":14,"2":2,"4":4,"5":5,"7":7,"8":8,"9":9}]},{},[15])(15) diff --git a/lib/pouchdb/dist/pouchdb.localstorage.js b/lib/pouchdb/dist/pouchdb.localstorage.js index a95c000b..b092ac73 100644 --- a/lib/pouchdb/dist/pouchdb.localstorage.js +++ b/lib/pouchdb/dist/pouchdb.localstorage.js @@ -1,4 +1,4 @@ -// PouchDB localStorage plugin 6.0.4 +// PouchDB localStorage plugin 6.0.6 // Based on localstorage-down: https://github.com/No9/localstorage-down // // (c) 2012-2016 Dale Harvey and the PouchDB team @@ -146,7 +146,7 @@ module.exports = AbstractIterator (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ -var xtend = _dereq_(92) +var xtend = _dereq_(93) , AbstractIterator = _dereq_(2) , AbstractChainedBatch = _dereq_(1) @@ -404,7 +404,7 @@ module.exports.AbstractIterator = AbstractIterator module.exports.AbstractChainedBatch = AbstractChainedBatch }).call(this,{"isBuffer":_dereq_(32)},_dereq_(57)) -},{"1":1,"2":2,"32":32,"57":57,"92":92}],4:[function(_dereq_,module,exports){ +},{"1":1,"2":2,"32":32,"57":57,"93":93}],4:[function(_dereq_,module,exports){ 'use strict'; module.exports = argsArray; @@ -427,6 +427,7 @@ function argsArray(fun) { },{}],5:[function(_dereq_,module,exports){ 'use strict' +exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray @@ -434,23 +435,17 @@ var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array -function init () { - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -init() +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr +function placeHoldersCount (b64) { var len = b64.length - if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } @@ -460,9 +455,19 @@ function toByteArray (b64) { // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} +function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars @@ -3000,7 +3005,7 @@ function coerce(val) { } },{"55":55}],13:[function(_dereq_,module,exports){ -var util = _dereq_(90) +var util = _dereq_(91) , AbstractIterator = _dereq_(18).AbstractIterator @@ -3035,9 +3040,9 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"18":18,"90":90}],14:[function(_dereq_,module,exports){ +},{"18":18,"91":91}],14:[function(_dereq_,module,exports){ (function (Buffer,process){ -var util = _dereq_(90) +var util = _dereq_(91) , AbstractLevelDOWN = _dereq_(18).AbstractLevelDOWN , DeferredIterator = _dereq_(13) @@ -3095,7 +3100,7 @@ module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator }).call(this,{"isBuffer":_dereq_(32)},_dereq_(57)) -},{"13":13,"18":18,"32":32,"57":57,"90":90}],15:[function(_dereq_,module,exports){ +},{"13":13,"18":18,"32":32,"57":57,"91":91}],15:[function(_dereq_,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -5258,8 +5263,8 @@ module.exports = Batch */ var EventEmitter = _dereq_(25).EventEmitter - , inherits = _dereq_(90).inherits - , deprecate = _dereq_(90).deprecate + , inherits = _dereq_(91).inherits + , deprecate = _dereq_(91).deprecate , extend = _dereq_(45) , prr = _dereq_(58) , DeferredLevelDOWN = _dereq_(14) @@ -5652,7 +5657,7 @@ module.exports.repair = deprecate( }).call(this,_dereq_(57)) -},{"14":14,"25":25,"37":37,"38":38,"40":40,"42":42,"43":43,"45":45,"57":57,"58":58,"90":90}],42:[function(_dereq_,module,exports){ +},{"14":14,"25":25,"37":37,"38":38,"40":40,"42":42,"43":43,"45":45,"57":57,"58":58,"91":91}],42:[function(_dereq_,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -5661,7 +5666,7 @@ module.exports.repair = deprecate( var extend = _dereq_(45) , LevelUPError = _dereq_(37).LevelUPError - , format = _dereq_(90).format + , format = _dereq_(91).format , defaultOptions = { createIfMissing : true , errorIfExists : false @@ -5731,7 +5736,7 @@ module.exports = { , isDefined : isDefined } -},{"37":37,"45":45,"46":46,"6":6,"90":90}],43:[function(_dereq_,module,exports){ +},{"37":37,"45":45,"46":46,"6":6,"91":91}],43:[function(_dereq_,module,exports){ arguments[4][35][0].apply(exports,arguments) },{"35":35,"44":44}],44:[function(_dereq_,module,exports){ (function (Buffer){ @@ -13697,7 +13702,7 @@ arguments[4][20][0].apply(exports,arguments) },{"20":20}],86:[function(_dereq_,module,exports){ (function (process){ var Transform = _dereq_(84) - , inherits = _dereq_(90).inherits + , inherits = _dereq_(91).inherits , xtend = _dereq_(85) function DestroyableTransform(opts) { @@ -13794,7 +13799,7 @@ module.exports.obj = through2(function (options, transform, flush) { }) }).call(this,_dereq_(57)) -},{"57":57,"84":84,"85":85,"90":90}],87:[function(_dereq_,module,exports){ +},{"57":57,"84":84,"85":85,"91":91}],87:[function(_dereq_,module,exports){ 'use strict'; // Simple FIFO queue implementation to avoid having to do shift() @@ -13916,13 +13921,15 @@ function config (name) { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],89:[function(_dereq_,module,exports){ +arguments[4][31][0].apply(exports,arguments) +},{"31":31}],90:[function(_dereq_,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],90:[function(_dereq_,module,exports){ +},{}],91:[function(_dereq_,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14449,7 +14456,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = _dereq_(89); +exports.isBuffer = _dereq_(90); function objectToString(o) { return Object.prototype.toString.call(o); @@ -14493,7 +14500,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = _dereq_(31); +exports.inherits = _dereq_(89); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -14512,7 +14519,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,_dereq_(57),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"31":31,"57":57,"89":89}],91:[function(_dereq_,module,exports){ +},{"57":57,"89":89,"90":90}],92:[function(_dereq_,module,exports){ 'use strict'; /** @@ -14687,7 +14694,7 @@ exports.parse = function (str) { } }; -},{}],92:[function(_dereq_,module,exports){ +},{}],93:[function(_dereq_,module,exports){ module.exports = extend function extend() { @@ -14706,7 +14713,7 @@ function extend() { return target } -},{}],93:[function(_dereq_,module,exports){ +},{}],94:[function(_dereq_,module,exports){ (function (process,global,Buffer){ 'use strict'; @@ -14725,7 +14732,7 @@ var Deque = _interopDefault(_dereq_(21)); var lie = _interopDefault(_dereq_(47)); var debug = _interopDefault(_dereq_(11)); var Md5 = _interopDefault(_dereq_(66)); -var vuvuzela = _interopDefault(_dereq_(91)); +var vuvuzela = _interopDefault(_dereq_(92)); var jsExtend = _dereq_(34); var localstoragedown = _interopDefault(_dereq_(48)); @@ -14860,8 +14867,8 @@ function nut(db, precodec, codec) { }; } -function NotFoundError(reason) { - Error.call(this, reason); +function NotFoundError() { + Error.call(this); } inherits(NotFoundError, Error); @@ -14871,6 +14878,8 @@ NotFoundError.prototype.name = 'NotFoundError'; var EventEmitter$1 = events__default.EventEmitter; var version = "6.5.4"; +var NOT_FOUND_ERROR = new NotFoundError(); + var sublevel = function (nut, prefix, createStream, options) { var emitter = new EventEmitter$1(); emitter.sublevels = {}; @@ -14959,7 +14968,7 @@ var sublevel = function (nut, prefix, createStream, options) { } nut.get(key, prefix, mergeOpts(opts), function (err, value) { if (err) { - cb(new NotFoundError(err)); + cb(NOT_FOUND_ERROR); } else { cb(null, value); } @@ -15162,25 +15171,6 @@ _Set.prototype.has = function (key) { return this.store.has(key); }; -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -16920,8 +16910,8 @@ function LevelPouch(opts, callback) { db._docCount = -1; db._queue = new Deque(); /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationOne(name, db, afterDBCreated); } else { afterDBCreated(); } @@ -16936,19 +16926,26 @@ function LevelPouch(opts, callback) { stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationTwo(db, stores, afterLastMigration); + } else { + afterLastMigration(); + } + } + + function afterLastMigration() { + stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { + if (typeof db._updateSeq === 'undefined') { + db._updateSeq = value || 0; + } + stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { + db._docCount = !err ? value : 0; + stores.metaStore.get(UUID_KEY, function (err, value) { + instanceId = !err ? value : uuid(); + stores.metaStore.put(UUID_KEY, instanceId, function () { + process.nextTick(function () { + callback(null, api); }); }); }); @@ -18237,4 +18234,4 @@ if (!PDB) { LocalStoragePouchPlugin(PDB); } }).call(this,_dereq_(57),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(8).Buffer) -},{"11":11,"21":21,"25":25,"31":31,"34":34,"35":35,"4":4,"41":41,"47":47,"48":48,"54":54,"57":57,"65":65,"66":66,"8":8,"86":86,"91":91,"pouchdb":"pouchdb"}]},{},[93]); +},{"11":11,"21":21,"25":25,"31":31,"34":34,"35":35,"4":4,"41":41,"47":47,"48":48,"54":54,"57":57,"65":65,"66":66,"8":8,"86":86,"92":92,"pouchdb":"pouchdb"}]},{},[94]); diff --git a/lib/pouchdb/dist/pouchdb.localstorage.min.js b/lib/pouchdb/dist/pouchdb.localstorage.min.js index 41719a7d..d09df624 100644 --- a/lib/pouchdb/dist/pouchdb.localstorage.min.js +++ b/lib/pouchdb/dist/pouchdb.localstorage.min.js @@ -1,14 +1,14 @@ -// PouchDB localStorage plugin 6.0.4 +// PouchDB localStorage plugin 6.0.6 // Based on localstorage-down: https://github.com/No9/localstorage-down // // (c) 2012-2016 Dale Harvey and the PouchDB team // PouchDB may be freely distributed under the Apache license, version 2.0. // For all details and documentation: // http://pouchdb.com -!function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=n[a]={exports:{}};t[a][0].call(f.exports,function(e){var n=t[a][1][e];return i(n?n:e)},f,f.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new f(3*s/4-o),r=o>0?s-4:s;var u=0;for(t=0,n=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}function o(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,n){for(var r,i=[],a=t;af?f:c+s));return 1===r?(t=e[n-1],i+=u[t>>2],i+=u[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=u[t>>10],i+=u[t>>4&63],i+=u[t<<2&63],i+="="),o.push(i),o.join("")}n.toByteArray=i,n.fromByteArray=s;var u=[],c=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array;r()},{}],6:[function(e,t,n){},{}],7:[function(e,t,n){(function(t){"use strict";var r=e(8),i=r.Buffer,o=r.SlowBuffer,a=r.kMaxLength||2147483647;n.alloc=function(e,t,n){if("function"==typeof i.alloc)return i.alloc(e,t,n);if("number"==typeof n)throw new TypeError("encoding must not be number");if("number"!=typeof e)throw new TypeError("size must be a number");if(e>a)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),c=u.length,f=-1;++fa)throw new RangeError("size is too large");return new i(e)},n.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},n.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{8:8}],8:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return K(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return M(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var c;if(i){var f=-1;for(c=n;cs&&(n=s-u),c=n;c>=0;c--){for(var l=!0,h=0;hi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,c,f,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],c=e[i+2],128===(192&u)&&128===(192&c)&&(l=(15&o)<<12|(63&u)<<6|63&c,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],c=e[i+2],f=e[i+3],128===(192&u)&&128===(192&c)&&128===(192&f)&&(l=(15&o)<<18|(63&u)<<12|(63&c)<<6|63&f,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function q(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function N(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||P(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function W(e,t,n,r,i){return i||P(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function K(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var X=e(5),Z=e(29),Q=e(33);n.Buffer=a,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return c(null,e,t,n)},a.allocUnsafe=function(e){return f(null,e)},a.allocUnsafeSlow=function(e){return f(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),c=this.slice(r,i),f=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return B(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var i=Math.pow(2,8*n)-1;D(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):q(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):q(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);D(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);D(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):q(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):q(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return W(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return W(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>2],i=(3&a)<<4;break;case 1:n+=e[i|a>>4],i=(15&a)<<2;break;case 2:n+=e[i|a>>6],n+=e[63&a],i=0}}return r%3&&(n+=e[i]), -n},t.decode=function(e){for(var t=e.length,i=0,o=new r(~~(t/4*3)),a=0,s=0;s>4,a=u<<4&255;break;case 2:o[i++]=a|u>>2,a=u<<6&255;break;case 3:o[i++]=a|u}}return o},t},t.exports(i,t.exports)},{8:8}],11:[function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function s(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(12),n.log=o,n.formatArgs=i,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{12:12}],12:[function(e,t,n){function r(){return n.colors[f++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(c||t);e.diff=o,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var i=n.formatters[r];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=i.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}r.prototype.toArray=function(){for(var e=this._length,t=new Array(e),n=this._front,r=this._capacity,i=0;i1){var r=this._capacity;if(n+t>r){for(var i=0;i1){var r=this._capacity;if(t+n>r){for(var i=n-1;i>=0;i--){this._checkCapacity(t+1);var r=this._capacity,o=(this._front-1&r-1^r)-r;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=n-1;i>=0;i--){var o=(a-1&r-1^r)-r;this[o]=arguments[i],a=o}return this._front=a,this._length=t+n,t+n}if(0===n)return t;this._checkCapacity(t+1);var r=this._capacity,i=(this._front-1&r-1^r)-r;return this[i]=e,this._length=t+1,this._front=i,t+1},r.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},r.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},r.prototype.get=function(e){var t=e;if(t===(0|t)){var n=this._length;if(t<0&&(t+=n),!(t<0||t>=n))return this[this._front+t&this._capacity-1]}},r.prototype.isEmpty=function(){return 0===this._length},r.prototype.clear=function(){for(var e=this._length,t=this._front,n=this._capacity,r=0;rt){var o=n+r&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=r},{}],22:[function(e,t,n){function r(e,t,n){a(this,{type:e,name:e,cause:"string"!=typeof t?t:n,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),r.call(this,"CustomError",e,t)}function o(e,t,n){var o=function(n,i){r.call(this,t,n,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=n?new n:new i,o}var a=e(24);i.prototype=new Error,t.exports=function(e){var t=function(t,n){return o(e,t,n)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{24:24}],23:[function(e,t,n){var r=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},r.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(22)(t.exports),t.exports.create=t.exports.custom.createError},{22:22}],24:[function(e,t,n){!function(e,n,r){"undefined"!=typeof t&&t.exports?t.exports=r():n[e]=r()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,n){return Object.defineProperty(e,t,n),e}:function(e,t,n){return e[t]=n.value,e},t=function(e,t){var n="object"==typeof t,r=!n&&"string"==typeof t,i=function(e){return n?!!t[e]:!!r&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},n=function(n,r,i,o){var a;if(o=t(i,o),"object"==typeof r){for(a in r)Object.hasOwnProperty.call(r,a)&&(o.value=r[a],e(n,a,o));return n}return e(n,r,o)};return n})},{}],25:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var f=new Error('Uncaught, unspecified "error" event. ('+t+")");throw f.context=t,f}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),c=n.slice(),r=c.length,u=0;u0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],26:[function(e,t,n){function r(){try{if("undefined"==typeof localStorage)return!1;if(localStorage.setItem("Storage-Test","1"),"1"!==localStorage.getItem("Storage-Test"))return!1;localStorage.removeItem("Storage-Test")}catch(e){return!1}return!0}"object"==typeof n&&(t.exports=r)},{}],27:[function(e,t,n){(function(n){var r=t.exports={},i=e(53);r.hasLocalStorage=e(26),r.create=function(){var e;return r.hasLocalStorage()?(e=n.localStorage,e={get length(){return n.localStorage.length},getItem:n.localStorage.getItem.bind(n.localStorage),setItem:n.localStorage.setItem.bind(n.localStorage),removeItem:n.localStorage.removeItem.bind(n.localStorage),key:n.localStorage.key.bind(n.localStorage),clear:n.localStorage.clear.bind(n.localStorage)},e.isPersistent=!0):(e=i,e.isPersistent=!1),e.getObject=r.getObject.bind(null,e),e.setObject=r.setObject.bind(null,e),e},r.setObject=function(e,t,n){return"object"!=typeof n?e.setItem(t,n):e.setItem(t,JSON.stringify(n))},r.getObject=function(e,t){var n=e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch(e){return n}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{26:26,53:53}],28:[function(e,t,n){var r=e(27);t.exports=r.create()},{27:27}],29:[function(e,t,n){n.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,u=(1<>1,f=-7,l=n?i-1:0,h=n?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+l],l+=h,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=r;f>0;a=256*a+e[t+l],l+=h,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,r),o-=c}return(d?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=f?(s=0,a=f):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,c-=8);e[n+d-p]|=128*g}},{}],30:[function(e,t,n){(function(e){"use strict";function n(){f=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[r],e):e[r]}),n},r.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(n,r){return{key:t.decodeKey(n,e),value:t.decodeValue(r,e)}}:e.keys?function(n){return t.decodeKey(n,e)}:e.values?function(n,r){return t.decodeValue(r,e)}:function(){}},r.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},r.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{36:36}],36:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},n.id=n.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],37:[function(e,t,n){var r=e(23).create,i=r("LevelUPError"),o=r("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:r("InitializationError",i),OpenError:r("OpenError",i),ReadError:r("ReadError",i),WriteError:r("WriteError",i),NotFoundError:o,EncodingError:r("EncodingError",i)}},{23:23}],38:[function(e,t,n){function r(e,t){return this instanceof r?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new r(e,t)}var i=e(31),o=e(65).Readable,a=e(39),s=e(37).EncodingError;t.exports=r,i(r,o),r.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,n,r){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===n&&void 0===r)e.push(null);else{if(!e._decoder)return e.push({key:n,value:r});try{var r=e._decoder(n,r)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(r)}}})},r.prototype.destroy=r.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{31:31,37:37,39:39,65:65}],39:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],40:[function(e,t,n){function r(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(42),o=e(37).WriteError,a=i.getOptions,s=i.dispatchError;r.prototype.put=function(e,t,n){n=a(n);var r=this._codec.encodeKey(e,n),i=this._codec.encodeValue(t,n);try{this.batch.put(r,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:r,value:i}),this.length++,this},r.prototype.del=function(e,t){t=a(t);var n=this._codec.encodeKey(e,t);try{this.batch.del(n)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:n}),this.length++,this},r.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},r.prototype.write=function(e){var t=this._levelup,n=this.ops;try{this.batch.write(function(r){return r?s(t,new o(r),e):(t.emit("batch",n),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=r},{37:37,42:42}],41:[function(e,t,n){(function(n){function r(e,t){return"function"==typeof e?e:t}function i(e,t,r){if(!(this instanceof i))return new i(e,t,r);var o;if(c.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{},t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e, -e=null),"function"==typeof t&&(r=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),r)return n.nextTick(function(){r(o)});throw o}t=B(t),this.options=h(R,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(r)}function o(e,t,n){if(!e._isOpening()&&!e.isOpen())return j(e,new b("Database is not open"),n),!0}function a(e,t,n){j(e,new v(t),n)}function s(e,t,n){j(e,new b(t),n)}function u(e){return function(t,n){A()[e](t,n||function(){})}}var c=e(25).EventEmitter,f=e(90).inherits,l=e(90).deprecate,h=e(45),d=e(58),p=e(14),g=e(38),y=e(37),v=y.WriteError,b=y.ReadError,m=y.NotFoundError,_=y.OpenError,w=y.EncodingError,E=y.InitializationError,k=e(42),S=e(40),x=e(43),B=k.getOptions,R=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;f(i,c),i.prototype.open=function(e){var t,r,i=this;return this.isOpen()?(e&&n.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),r=t(this.location),void r.open(this.options,function(t){return t?j(i,new _(t),e):(i.db.setDb(r),i.db=r,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return n.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,n){var i,a=this;if(n=r(t,n),!o(this,t,n)){if(null===e||void 0===e||"function"!=typeof n)return s(this,"get() requires key and callback arguments",n);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(r,i){if(r)return r=/notfound/i.test(r)||r.notFound?new m("Key not found in database ["+e+"]",r):new b(r),j(a,r,n);if(n){try{i=a._codec.decodeValue(i,t)}catch(e){return n(new w(e))}n(null,i)}})}},i.prototype.put=function(e,t,n,i){var s,u,c=this;return i=r(n,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,n,i)||(n=B(n),s=this._codec.encodeKey(e,n),u=this._codec.encodeValue(t,n),this.db.put(s,u,n,function(n){return n?j(c,new v(n),i):(c.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,n){var i,s=this;return n=r(t,n),null===e||void 0===e?a(this,"del() requires a key argument",n):void(o(this,t,n)||(t=B(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new v(t),n):(s.emit("del",e),void(n&&n()))})))},i.prototype.batch=function(e,t,n){var i,s=this;return arguments.length?(n=r(t,n),Array.isArray(e)?void(o(this,t,n)||(t=B(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new v(t),n):(s.emit("batch",e),void(n&&n()))}))):a(this,"batch() requires an array argument",n)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,n,i){var o,a,u=this;return i=r(n,i),n=B(n),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,n),a=this._codec.encodeKey(t,n),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new _(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(37),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(57))},{14:14,25:25,37:37,38:38,40:40,42:42,43:43,45:45,57:57,58:58,90:90}],42:[function(e,t,n){function r(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,n=e(46).devDependencies.leveldown;try{t=e(6).version}catch(e){throw o(e)}if(!e(6).satisfies(t,n))throw new c("Installed version of LevelDOWN ("+t+") does not match required version ("+n+")");try{return u=e(6)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new c(f(t,e.message))}function a(e,t,n){"function"==typeof n?n(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,c=(e(45),e(37).LevelUPError),f=e(90).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:r,getLevelDOWN:i,dispatchError:a,isDefined:s}},{37:37,45:45,46:46,6:6,90:90}],43:[function(e,t,n){arguments[4][35][0].apply(n,arguments)},{35:35,44:44}],44:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],45:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],46:[function(e,t,n){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],47:[function(e,t,n){"use strict";function r(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=b,this.queue=[],this.outcome=void 0,e!==r&&u(this,e)}function o(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function a(e,t,n){p(function(){var r;try{r=t(n)}catch(t){return g.reject(e,t)}r===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,r)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function n(t){o||(o=!0,g.reject(e,t))}function r(t){o||(o=!0,g.resolve(e,t))}function i(){t(r,n)}var o=!1,a=c(i);"error"===a.status&&n(a.value)}function c(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}function f(e){return e instanceof this?e:g.resolve(new this(r),e)}function l(e){var t=new this(r);return g.reject(t,e)}function h(e){function t(e,t){function r(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(c,a))}n.resolve(e).then(r,function(e){o||(o=!0,g.reject(c,e))})}var n=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,c=new this(r);++ur._endkey)?e():r._limit&&r._limit>0&&r._count++>=r._limit?e():r._lt&&t>=r._lt||r._lte&&t>r._lte||r._gt&&t<=r._gt||r._gte&&t=r._keys.length||o<0?void 0:r._keys[o];r._pos=o,r._reverse?(r._exclusiveStart||a!==r._startkey)&&r._pos--:r._exclusiveStart&&a===r._startkey&&r._pos++}else r._pos=r._reverse?r._keys.length-1:0;t(),r.initCompleted=!0;for(var s=-1;++s-1){var o=JSON.parse(r);r=o.data}n(null,r)}))},a.prototype._del=function(e,t,n){var r=s(e,"key");return r?p(function(){n(r)}):(i.isBuffer(e)||(e=String(e)),void this.container.removeItem(e,n))},a.prototype._batch=function(e,t,n){var r=this;p(function(){function o(){++l===e.length&&n(f)}var a,u,c,f,l=0;if(Array.isArray(e)&&e.length)for(var h=0;h>>1,e[n]n?1:0};var a=n.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=n.lowerBound=function(e){var t=a(e);return t&&e[t]};n.lowerBoundInclusive=function(e){return!t(e,"gt")},n.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=n.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},c=n.upperBoundExclusive=function(e){return!!t(e,"lt")},f=n.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=n.upperBound=function(e){var t=f(e);return t&&e[t]};n.toLtgt=function(e,r,i,a,s){r=r||{},i=i||o;var u=arguments.length>3,c=n.lowerBoundKey(e),f=n.upperBoundKey(e);return c?"gt"===c?r.gt=i(e.gt,!1):r.gte=i(e[c],!1):u&&(r.gte=i(a,!1)),f?"lt"===f?r.lt=i(e.lt,!0):r.lte=i(e[f],!0):u&&(r.lte=i(s,!0)),null!=e.reverse&&(r.reverse=!!e.reverse),t(r,"max")&&delete r.max,t(r,"min")&&delete r.min,t(r,"start")&&delete r.start,t(r,"end")&&delete r.end,r},n.contains=function(e,t,i){i=i||n.compare;var o=s(e);if(r(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var f=l(e);if(r(f)){var a=i(t,f);if(a>0||0===a&&c(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(32)})},{32:32}],55:[function(e,t,n){function r(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*f;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function i(e){return e>=f?Math.round(e/f)+"d":e>=c?Math.round(e/c)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,f,"day")||a(e,c,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e1)for(var n=1;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||r||(n=t.decoder.write(n)),t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):(t.reading=!1,t.buffer.push(n)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function c(e,t){var n=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function f(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.length>0?l(e):_(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?n.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){p(e,t)}))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(x.listenerCount(e,"data")>0&&b(e))):void(r.ranOut=!0)}function v(){this._readableState.ranOut&&(this._readableState.ranOut=!1,y(this))}function b(e,t){var r=e._readableState;if(r.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=B.prototype.pipe,e.on=e.addListener=B.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?n.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function m(e,t){var n,r=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(a)n=r.shift();else if(!e||e>=i)n=o?r.join(""):S.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return n=null,t.length>0&&t.decoder&&(n=m(e,t),t.length-=n.length),0===t.length&&_(this),n;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(r,t)),n=e>0?m(e,t):null,null===n&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&_(this),n},i.prototype._read=function(e){ -this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){e===f&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),f.removeListener("end",i),f.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){c(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),c()}function u(){e.removeListener("close",s),c()}function c(){f.unpipe(e)}var f=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e];break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,d=h?i:o;l.endEmitted?n.nextTick(d):f.once("end",d),e.on("unpipe",r);var p=g(f);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",f),l.flowing||(this.on("readable",v),l.flowing=!0,n.nextTick(function(){y(f)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1;for(var i=0;i>>32-i,n)}function n(e,n,r,i,o,a,s){return t(n&r|~n&i,e,n,o,a,s)}function r(e,n,r,i,o,a,s){return t(n&i|r&~i,e,n,o,a,s)}function i(e,n,r,i,o,a,s){return t(n^r^i,e,n,o,a,s)}function o(e,n,r,i,o,a,s){return t(r^(n|~i),e,n,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],c=e[3];a=n(a,s,u,c,t[0],7,-680876936),c=n(c,a,s,u,t[1],12,-389564586),u=n(u,c,a,s,t[2],17,606105819),s=n(s,u,c,a,t[3],22,-1044525330),a=n(a,s,u,c,t[4],7,-176418897),c=n(c,a,s,u,t[5],12,1200080426),u=n(u,c,a,s,t[6],17,-1473231341),s=n(s,u,c,a,t[7],22,-45705983),a=n(a,s,u,c,t[8],7,1770035416),c=n(c,a,s,u,t[9],12,-1958414417),u=n(u,c,a,s,t[10],17,-42063),s=n(s,u,c,a,t[11],22,-1990404162),a=n(a,s,u,c,t[12],7,1804603682),c=n(c,a,s,u,t[13],12,-40341101),u=n(u,c,a,s,t[14],17,-1502002290),s=n(s,u,c,a,t[15],22,1236535329),a=r(a,s,u,c,t[1],5,-165796510),c=r(c,a,s,u,t[6],9,-1069501632),u=r(u,c,a,s,t[11],14,643717713),s=r(s,u,c,a,t[0],20,-373897302),a=r(a,s,u,c,t[5],5,-701558691),c=r(c,a,s,u,t[10],9,38016083),u=r(u,c,a,s,t[15],14,-660478335),s=r(s,u,c,a,t[4],20,-405537848),a=r(a,s,u,c,t[9],5,568446438),c=r(c,a,s,u,t[14],9,-1019803690),u=r(u,c,a,s,t[3],14,-187363961),s=r(s,u,c,a,t[8],20,1163531501),a=r(a,s,u,c,t[13],5,-1444681467),c=r(c,a,s,u,t[2],9,-51403784),u=r(u,c,a,s,t[7],14,1735328473),s=r(s,u,c,a,t[12],20,-1926607734),a=i(a,s,u,c,t[5],4,-378558),c=i(c,a,s,u,t[8],11,-2022574463),u=i(u,c,a,s,t[11],16,1839030562),s=i(s,u,c,a,t[14],23,-35309556),a=i(a,s,u,c,t[1],4,-1530992060),c=i(c,a,s,u,t[4],11,1272893353),u=i(u,c,a,s,t[7],16,-155497632),s=i(s,u,c,a,t[10],23,-1094730640),a=i(a,s,u,c,t[13],4,681279174),c=i(c,a,s,u,t[0],11,-358537222),u=i(u,c,a,s,t[3],16,-722521979),s=i(s,u,c,a,t[6],23,76029189),a=i(a,s,u,c,t[9],4,-640364487),c=i(c,a,s,u,t[12],11,-421815835),u=i(u,c,a,s,t[15],16,530742520),s=i(s,u,c,a,t[2],23,-995338651),a=o(a,s,u,c,t[0],6,-198630844),c=o(c,a,s,u,t[7],10,1126891415),u=o(u,c,a,s,t[14],15,-1416354905),s=o(s,u,c,a,t[5],21,-57434055),a=o(a,s,u,c,t[12],6,1700485571),c=o(c,a,s,u,t[3],10,-1894986606),u=o(u,c,a,s,t[10],15,-1051523),s=o(s,u,c,a,t[1],21,-2054922799),a=o(a,s,u,c,t[8],6,1873313359),c=o(c,a,s,u,t[15],10,-30611744),u=o(u,c,a,s,t[6],15,-1560198380),s=o(s,u,c,a,t[13],21,1309151649),a=o(a,s,u,c,t[4],6,-145523070),c=o(c,a,s,u,t[11],10,-1120210379),u=o(u,c,a,s,t[2],15,718787259),s=o(s,u,c,a,t[9],21,-343485551),e[0]=m(a,e[0]),e[1]=m(s,e[1]),e[2]=m(u,e[2]),e[3]=m(c,e[3])}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function c(e){var t,n,r,i,o,u,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)a(f,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;t<16;t+=1)r[t]=0;return i=8*c,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,r[14]=o,r[15]=u,a(f,r),f}function f(e){var t,n,r,i,o,s,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)a(f,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;t<16;t+=1)r[t]=0;return i=8*c,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,r[14]=o,r[15]=s,a(f,r),f}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=_[e>>8*t+4&15]+_[e>>8*t&15];return n}function h(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,a,s,u=this.byteLength,c=t(n,u),f=u;return r!==e&&(f=t(r,u)),c>f?new ArrayBuffer(0):(i=f-c,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,c,i),a.set(s),o)}}(),b.prototype.append=function(e){return this.appendBinary(d(e)),this},b.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},b.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},b.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},b.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},b.prototype._finish=function(e,t){var n,r,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=r,e[15]=i,a(this._hash,e)},b.hash=function(e,t){return b.hashBinary(d(e),t)},b.hashBinary=function(e,t){var n=c(e),r=h(n);return t?v(r):r},b.ArrayBuffer=function(){this.reset()},b.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.ArrayBuffer.prototype.getState=function(){var e=b.prototype.getState.call(this);return e.buff=g(e.buff),e},b.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),b.prototype.setState.call(this,e)},b.ArrayBuffer.prototype.destroy=b.prototype.destroy,b.ArrayBuffer.prototype._finish=b.prototype._finish,b.ArrayBuffer.hash=function(e,t){var n=f(new Uint8Array(e)),r=h(n);return t?v(r):r},b})},{}],67:[function(e,t,n){function r(){i.call(this)}t.exports=r;var i=e(25).EventEmitter,o=e(31);o(r,i),r.Readable=e(76),r.Writable=e(78),r.Duplex=e(68),r.Transform=e(77),r.PassThrough=e(75),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&c.pause&&c.pause()}function r(){c.readable&&c.resume&&c.resume()}function o(){f||(f=!0,e.end())}function a(){f||(f=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){c.removeListener("data",n),e.removeListener("drain",r),c.removeListener("end",o),c.removeListener("close",a),c.removeListener("error",s),e.removeListener("error",s),c.removeListener("end",u),c.removeListener("close",u),e.removeListener("close",u)}var c=this;c.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(c.on("end",o),c.on("close",a));var f=!1;return c.on("error",s),e.on("error",s),c.on("end",u),c.on("close",u),e.on("close",u),e.emit("pipe",c),e}},{25:25,31:31,68:68,75:75,76:76,77:77,78:78}],68:[function(e,t,n){t.exports=e(69)},{69:69}],69:[function(e,t,n){"use strict";function r(e){return this instanceof r?(c.call(this,e),f.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e(56),u=e(9);u.inherits=e(31);var c=e(71),f=e(73);u.inherits(r,c);for(var l=a(f.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var c;!t.decoder||i||r||(n=t.decoder.write(n),c=!t.objectMode&&0===n.length),i||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function c(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function f(e,t){var n=null;return L.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(q("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){q("emit readable"),e.emit("readable"),_(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=E(e,t.buffer,t.decoder),n}function E(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=C.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(B,t,e))}function B(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function R(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return q("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=c(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;q("need readable",r),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){q("onunpipe"),e===h&&a()}function o(){q("onend"),e.end()}function a(){q("cleanup"),e.removeListener("close",c),e.removeListener("finish",f),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),b=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){q("ondata"),m=!1;var n=e.write(t);!1!==n||m||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!b&&(q("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,m=!0),h.pause())}function u(t){q("onerror",t),l(),e.removeListener("error",u),0===M(e,"error")&&e.emit("error",t)}function c(){e.removeListener("finish",f),l()}function f(){q("onfinish"),e.removeListener("close",c),l()}function l(){q("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var v=y(h);e.on("drain",v);var b=!1,m=!1;return h.on("data",s),r(e,"error",u),e.once("close",c),e.once("finish",f),e.emit("pipe",h),d.flowing||(q("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(9);x.inherits=e(31);var B,R={deprecate:e(88)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(25).EventEmitter)}}();var A=e(8).Buffer,j=e(7);x.inherits(a,B);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:R.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=f(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(57))},{25:25,31:31,56:56,57:57,69:69,7:7,8:8,88:88,9:9}],74:[function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(e(8).Buffer,e(7));t.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},{7:7,8:8}],75:[function(e,t,n){t.exports=e(70)},{70:70}],76:[function(e,t,n){(function(r){var i=function(){try{return e("stream")}catch(e){}}();n=t.exports=e(71),n.Stream=i||n,n.Readable=n,n.Writable=e(73),n.Duplex=e(69),n.Transform=e(72),n.PassThrough=e(70),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(57))},{57:57,69:69,70:70,71:71,72:72,73:73}],77:[function(e,t,n){t.exports=e(72)},{72:72}],78:[function(e,t,n){t.exports=e(73)},{73:73}],79:[function(e,t,n){function r(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(8).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},c=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};c.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},c.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},c.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}},{8:8}],80:[function(e,t,n){arguments[4][69][0].apply(n,arguments)},{31:31,56:56,69:69,81:81,83:83,9:9}],81:[function(e,t,n){(function(n){"use strict";function r(t,n){C=C||e(80),t=t||{},this.objectMode=!!t.objectMode,n instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(L||(L=e(79).StringDecoder),this.decoder=new L(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(80),this instanceof i?(this._readableState=new r(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,n,r,i){var o=c(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,f(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||r||(n=t.decoder.write(n),u=!t.objectMode&&0===n.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=I?e=I:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function c(e,t){var n=null;return R.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function f(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(M("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){M("emit readable"),e.emit("readable"),m(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)n=o?r.join(""):1===r.length?r[0]:R.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return M("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;M("need readable",r),(0===t.length||t.length-e0?_(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){M("onunpipe"),e===l&&o()}function i(){M("onend"),e.end()}function o(){M("cleanup"),e.removeListener("close",u),e.removeListener("finish",c),e.removeListener("drain",y),e.removeListener("error",s),e.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),v=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function a(t){M("ondata");var n=e.write(t);!1===n&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||v||(M("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){M("onerror",t),f(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",c),f()}function c(){M("onfinish"),e.removeListener("close",u),f()}function f(){M("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,M("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",r);var y=g(l);e.on("drain",y);var v=!1;return l.on("data",a),e._events&&e._events.error?B(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",c),e.emit("pipe",l),h.flowing||(M("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(8).Buffer;a.WritableState=o;var B=e(9);B.inherits=e(31);var R,A={deprecate:e(88)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(25).EventEmitter)}}();var x=e(8).Buffer;B.inherits(a,R);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=f(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(57))},{25:25,31:31,56:56,57:57,8:8,80:80,88:88,9:9}],84:[function(e,t,n){arguments[4][77][0].apply(n,arguments)},{77:77,82:82}],85:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],86:[function(e,t,n){(function(n){function r(e){a.call(this,e),this._destroyed=!1}function i(e,t,n){n(null,e)}function o(e){return function(t,n,r){return"function"==typeof t&&(r=n,n=t,t={}),"function"!=typeof n&&(n=i),"function"!=typeof r&&(r=null),e(t,n,r)}}var a=e(84),s=e(90).inherits,u=e(85);s(r,a),r.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;n.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,n){var i=new r(e);return i._transform=t,n&&(i._flush=n),i}),t.exports.ctor=o(function(e,t,n){function i(t){return this instanceof i?(this.options=u(e,t),void r.call(this,this.options)):new i(t)}return s(i,r),i.prototype._transform=t,n&&(i.prototype._flush=n),i}),t.exports.obj=o(function(e,t,n){var i=new r(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,n&&(i._flush=n),i})}).call(this,e(57))},{57:57,84:84,85:85,90:90}],87:[function(e,t,n){"use strict";function r(){this.length=0}r.prototype.push=function(e){var t={item:e};this.last?this.last=this.last.next=t:this.last=this.first=t,this.length++},r.prototype.shift=function(){var e=this.first;if(e)return this.first=e.next,--this.length||(this.last=void 0),e.item},r.prototype.slice=function(e,t){e="undefined"==typeof e?0:e,t="undefined"==typeof t?1/0:t;for(var n=[],r=0,i=this.first;i&&!(--t<0);i=i.next)++r>e&&n.push(i.item);return n},t.exports=r},{}],88:[function(e,t,n){(function(e){function n(e,t){function n(){if(!i){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],89:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],90:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&B(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return m(i)||(i=u(e,i,r)),i}var o=c(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(t);if(0===a.length){if(B(t)){var y=t.name?": "+t.name:"";return e.stylize("[Function"+y+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return f(t)}var v="",b=!1,_=["{","}"];if(p(t)&&(b=!0,_=["[","]"]),B(t)){var w=t.name?": "+t.name:"";v=" [Function"+w+"]"}if(E(t)&&(v=" "+RegExp.prototype.toString.call(t)),S(t)&&(v=" "+Date.prototype.toUTCString.call(t)),x(t)&&(v=" "+f(t)),0===a.length&&(!b||0==t.length))return _[0]+v+_[1];if(r<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=b?l(e,t,r,g,a):a.map(function(n){return h(e,t,r,g,n,b)}),e.seen.pop(),d(k,v,_)}function c(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function m(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function B(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),I[e.getMonth()],t].join(" ")}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var M=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(c in r)r.hasOwnProperty(c)&&u.push(c);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)f=u[a],l=r[f],h=a>0?",":"",h+=JSON.stringify(f)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},n.parse=function(e){for(var t,n,i,o,a,s,u,c,f,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,r(null,l,h);break;case"t":d+=3,r(!0,l,h);break;case"f":d+=4,r(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",d--;;){if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}n+=i}r(parseFloat(n),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+o+'"'),l,h);break;case"[":c={element:[],index:l.length},l.push(c.element),h.push(c);break;case"{":f={element:{},index:l.length},l.push(f.element),h.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,h)}}},{}],92:[function(e,t,n){function r(){for(var e={},t=0;t>>1,n(e[r],t)<0?i=r+1:o=r;return i}function H(e,t,n){var r=J(e,t,n);e.splice(r,0,t)}function $(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var y=g.ids[2],v=0,b=y.length;v0||r0||ri.end)return t(null,{total_rows:r,offset:e.skip,rows:[]});var u=[],c=E.docStore.readStream(i),f=We.obj(function(t,n,r){function i(t){var n={id:a.id,key:a.id,value:{rev:f}};if(e.include_docs){n.doc=t,n.doc._rev=n.value.rev,e.conflicts&&(n.doc._conflicts=z(a));for(var i in n.doc._attachments)n.doc._attachments.hasOwnProperty(i)&&(n.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return r();if(l){if("ok"!==e.deleted)return r();n.value.deleted=!0,n.doc=null}u.push(n),r()}var a=t.value,f=Re(a),l=Ae(a,f);if(l){if("ok"!==e.deleted)return void r()}else{if(o-- >0)return void r();if("number"==typeof s&&s--<=0)return c.unpipe(),c.destroy(),void r()}if(e.include_docs){var h=a.rev_map[f];E.bySeqStore.get(d(h),function(e,t){i(t)})}else i()},function(n){at.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,E,e)}).then(function(){t(null,{total_rows:r,offset:e.skip,rows:u})},t),n()}).on("unpipe",function(){f.end()});c.on("error",t),c.pipe(f)})}),w._changes=function(e){function t(){e.done=!0,c&&e.limit&&e.limit0&&(r=e.limit),u.reverse||(u.start=d(e.since||0));var c,f=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;c="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var v=E.bySeqStore.readStream(u),b=We.obj(function(n,u,p){function g(t){function n(n){var r=e.processChange(n,t,e);r.seq=t.seq;var i=l(r);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([r],E,e).then(function(){e.onChange(r)}):e.onChange(r),c&&o.push(r)),void p())}var r=Re(t);if(t.seq!==v)return p();if(a=v,r===b._rev)return n(b);var i=t.rev_map[r];E.bySeqStore.get(d(i),function(e,t){n(t)})}if(r&&s>=r)return t(),p();if(e.cancelled||e.done)return p();var v=y(n.key),b=n.value;if(v===e.since&&!i)return p();if(f&&!f.has(b._id))return p();var _;return(_=h.get(b._id))?g(_):void E.docStore.get(b._id,function(t,n){return e.cancelled||e.done||m.isClosed()||ie(n.id)?p():(h.set(b._id,n),void g(n))})},function(t){return e.cancelled?t():(c&&e.limit&&e.limitr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){ -var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(De.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Ne(R,Error),R.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var ct,ft=(new R({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new R({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new R({status:404,error:"not_found",reason:"missing"})),lt=new R({status:409,error:"conflict",reason:"Document update conflict"}),ht=new R({status:400,error:"bad_request",reason:"_id field must contain a string"}),dt=new R({status:412,error:"missing_id",reason:"_id is required for puts"}),pt=new R({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),gt=new R({status:412,error:"precondition_failed",reason:"Database not open"}),yt=(new R({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new R({status:500,error:"badarg",reason:"Some query argument is invalid"})),vt=(new R({status:400,error:"invalid_request",reason:"Request was invalid"}),new R({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new R({status:500,error:"doc_validation",reason:"Bad special document member"})),bt=new R({status:400,error:"bad_request",reason:"Something wrong with the request"}),mt=(new R({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new R({status:404,error:"not_found",reason:"Database not found"}),new R({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new R({status:500,error:"web_sql_went_bad",reason:"unknown"}),new R({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new R({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new R({status:400,error:"bad_request",reason:"Invalid rev format"})),_t=(new R({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new R({status:412,error:"missing_stub"})),wt=(new R({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),T.name);ct=wt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var Et=ct,kt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),St=I(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),xt=I(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),Bt=function(e){return atob(e)},Rt=function(e){return btoa(e)},At=n.setImmediate||n.setTimeout,jt=32768;Be.prototype.get=function(e,n,r){var i=xe(this,e),o=i.get(n);return o?t.nextTick(function(){r(null,o)}):null===o?t.nextTick(function(){r({name:"NotFoundError"})}):void e.get(n,function(e,t){return e?("NotFoundError"===e.name&&i.set(n,null),r(e)):(i.set(n,t),void r(null,t))})},Be.prototype.batch=function(e){for(var t=0,n=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;n.has(a)||(n.add(a),r.push(o))}e.batch(r,t)};var Ot="document-store",Tt="by-sequence",Mt="attach-store",Lt="attach-binary-store",Ct="local-store",It="meta-store",Dt=new p,qt="_local_last_update_seq",Nt="_local_doc_count",Pt="_local_uuid",Ut="md5-",Wt={encode:we,decode:_e,buffer:!1,type:"cheap-json"},Ft=new x;Me.valid=function(){return"undefined"!=typeof localStorage},Me.use_prefix=!0;var zt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");zt?Le(zt):B("error",'localstorage adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(57),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(8).Buffer)},{11:11,21:21,25:25,31:31,34:34,35:35,4:4,41:41,47:47,48:48,54:54,57:57,65:65,66:66,8:8,86:86,91:91,pouchdb:"pouchdb"}]},{},[93]); +!function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=n[a]={exports:{}};t[a][0].call(f.exports,function(e){var n=t[a][1][e];return i(n?n:e)},f,f.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-r(e)}function o(e){var t,n,i,o,a,s,u=e.length;a=r(e),s=new l(3*u/4-a),i=a>0?u-4:u;var c=0;for(t=0,n=0;t>16&255,s[c++]=o>>8&255,s[c++]=255&o;return 2===a?(o=f[e.charCodeAt(t)]<<2|f[e.charCodeAt(t+1)]>>4,s[c++]=255&o):1===a&&(o=f[e.charCodeAt(t)]<<10|f[e.charCodeAt(t+1)]<<4|f[e.charCodeAt(t+2)]>>2,s[c++]=o>>8&255,s[c++]=255&o),s}function a(e){return c[e>>18&63]+c[e>>12&63]+c[e>>6&63]+c[63&e]}function s(e,t,n){for(var r,i=[],o=t;of?f:u+a));return 1===r?(t=e[n-1],i+=c[t>>2],i+=c[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=c[t>>10],i+=c[t>>4&63],i+=c[t<<2&63],i+="="),o.push(i),o.join("")}n.byteLength=i,n.toByteArray=o,n.fromByteArray=u;for(var c=[],f=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;da)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),c=u.length,f=-1;++fa)throw new RangeError("size is too large");return new i(e)},n.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},n.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{8:8}],8:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return K(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return M(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return L(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var c;if(i){var f=-1;for(c=n;cs&&(n=s-u),c=n;c>=0;c--){for(var l=!0,h=0;hi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,c,f,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],c=e[i+2],128===(192&u)&&128===(192&c)&&(l=(15&o)<<12|(63&u)<<6|63&c,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],c=e[i+2],f=e[i+3],128===(192&u)&&128===(192&c)&&128===(192&f)&&(l=(15&o)<<18|(63&u)<<12|(63&c)<<6|63&f,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function q(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function N(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function P(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||P(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function W(e,t,n,r,i){return i||P(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function K(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var X=e(5),Z=e(29),Q=e(33);n.Buffer=a,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return c(null,e,t,n)},a.allocUnsafe=function(e){return f(null,e)},a.allocUnsafeSlow=function(e){return f(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),c=this.slice(r,i),f=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return B(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||I(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||I(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||I(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||I(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||I(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||I(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||I(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||I(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||I(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var i=Math.pow(2,8*n)-1;D(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):q(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):q(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);D(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);D(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):q(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):q(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return W(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return W(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>2],i=(3&a)<<4;break;case 1:n+=e[i|a>>4], +i=(15&a)<<2;break;case 2:n+=e[i|a>>6],n+=e[63&a],i=0}}return r%3&&(n+=e[i]),n},t.decode=function(e){for(var t=e.length,i=0,o=new r(~~(t/4*3)),a=0,s=0;s>4,a=u<<4&255;break;case 2:o[i++]=a|u>>2,a=u<<6&255;break;case 3:o[i++]=a|u}}return o},t},t.exports(i,t.exports)},{8:8}],11:[function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function s(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(12),n.log=o,n.formatArgs=i,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{12:12}],12:[function(e,t,n){function r(){return n.colors[f++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(c||t);e.diff=o,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var i=n.formatters[r];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=i.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}r.prototype.toArray=function(){for(var e=this._length,t=new Array(e),n=this._front,r=this._capacity,i=0;i1){var r=this._capacity;if(n+t>r){for(var i=0;i1){var r=this._capacity;if(t+n>r){for(var i=n-1;i>=0;i--){this._checkCapacity(t+1);var r=this._capacity,o=(this._front-1&r-1^r)-r;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=n-1;i>=0;i--){var o=(a-1&r-1^r)-r;this[o]=arguments[i],a=o}return this._front=a,this._length=t+n,t+n}if(0===n)return t;this._checkCapacity(t+1);var r=this._capacity,i=(this._front-1&r-1^r)-r;return this[i]=e,this._length=t+1,this._front=i,t+1},r.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},r.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},r.prototype.get=function(e){var t=e;if(t===(0|t)){var n=this._length;if(t<0&&(t+=n),!(t<0||t>=n))return this[this._front+t&this._capacity-1]}},r.prototype.isEmpty=function(){return 0===this._length},r.prototype.clear=function(){for(var e=this._length,t=this._front,n=this._capacity,r=0;rt){var o=n+r&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=r},{}],22:[function(e,t,n){function r(e,t,n){a(this,{type:e,name:e,cause:"string"!=typeof t?t:n,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),r.call(this,"CustomError",e,t)}function o(e,t,n){var o=function(n,i){r.call(this,t,n,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=n?new n:new i,o}var a=e(24);i.prototype=new Error,t.exports=function(e){var t=function(t,n){return o(e,t,n)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{24:24}],23:[function(e,t,n){var r=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},r.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(22)(t.exports),t.exports.create=t.exports.custom.createError},{22:22}],24:[function(e,t,n){!function(e,n,r){"undefined"!=typeof t&&t.exports?t.exports=r():n[e]=r()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,n){return Object.defineProperty(e,t,n),e}:function(e,t,n){return e[t]=n.value,e},t=function(e,t){var n="object"==typeof t,r=!n&&"string"==typeof t,i=function(e){return n?!!t[e]:!!r&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},n=function(n,r,i,o){var a;if(o=t(i,o),"object"==typeof r){for(a in r)Object.hasOwnProperty.call(r,a)&&(o.value=r[a],e(n,a,o));return n}return e(n,r,o)};return n})},{}],25:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var f=new Error('Uncaught, unspecified "error" event. ('+t+")");throw f.context=t,f}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),c=n.slice(),r=c.length,u=0;u0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],26:[function(e,t,n){function r(){try{if("undefined"==typeof localStorage)return!1;if(localStorage.setItem("Storage-Test","1"),"1"!==localStorage.getItem("Storage-Test"))return!1;localStorage.removeItem("Storage-Test")}catch(e){return!1}return!0}"object"==typeof n&&(t.exports=r)},{}],27:[function(e,t,n){(function(n){var r=t.exports={},i=e(53);r.hasLocalStorage=e(26),r.create=function(){var e;return r.hasLocalStorage()?(e=n.localStorage,e={get length(){return n.localStorage.length},getItem:n.localStorage.getItem.bind(n.localStorage),setItem:n.localStorage.setItem.bind(n.localStorage),removeItem:n.localStorage.removeItem.bind(n.localStorage),key:n.localStorage.key.bind(n.localStorage),clear:n.localStorage.clear.bind(n.localStorage)},e.isPersistent=!0):(e=i,e.isPersistent=!1),e.getObject=r.getObject.bind(null,e),e.setObject=r.setObject.bind(null,e),e},r.setObject=function(e,t,n){return"object"!=typeof n?e.setItem(t,n):e.setItem(t,JSON.stringify(n))},r.getObject=function(e,t){var n=e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch(e){return n}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{26:26,53:53}],28:[function(e,t,n){var r=e(27);t.exports=r.create()},{27:27}],29:[function(e,t,n){n.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,u=(1<>1,f=-7,l=n?i-1:0,h=n?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+l],l+=h,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=r;f>0;a=256*a+e[t+l],l+=h,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,r),o-=c}return(d?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=f?(s=0,a=f):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,c-=8);e[n+d-p]|=128*g}},{}],30:[function(e,t,n){(function(e){"use strict";function n(){f=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[r],e):e[r]}),n},r.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(n,r){return{key:t.decodeKey(n,e),value:t.decodeValue(r,e)}}:e.keys?function(n){return t.decodeKey(n,e)}:e.values?function(n,r){return t.decodeValue(r,e)}:function(){}},r.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},r.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{36:36}],36:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},n.id=n.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],37:[function(e,t,n){var r=e(23).create,i=r("LevelUPError"),o=r("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:r("InitializationError",i),OpenError:r("OpenError",i),ReadError:r("ReadError",i),WriteError:r("WriteError",i),NotFoundError:o,EncodingError:r("EncodingError",i)}},{23:23}],38:[function(e,t,n){function r(e,t){return this instanceof r?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new r(e,t)}var i=e(31),o=e(65).Readable,a=e(39),s=e(37).EncodingError;t.exports=r,i(r,o),r.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,n,r){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===n&&void 0===r)e.push(null);else{if(!e._decoder)return e.push({key:n,value:r});try{var r=e._decoder(n,r)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(r)}}})},r.prototype.destroy=r.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{31:31,37:37,39:39,65:65}],39:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],40:[function(e,t,n){function r(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(42),o=e(37).WriteError,a=i.getOptions,s=i.dispatchError;r.prototype.put=function(e,t,n){n=a(n);var r=this._codec.encodeKey(e,n),i=this._codec.encodeValue(t,n);try{this.batch.put(r,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:r,value:i}),this.length++,this},r.prototype.del=function(e,t){t=a(t);var n=this._codec.encodeKey(e,t);try{this.batch.del(n)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:n}),this.length++,this},r.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},r.prototype.write=function(e){var t=this._levelup,n=this.ops;try{this.batch.write(function(r){return r?s(t,new o(r),e):(t.emit("batch",n),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=r},{37:37,42:42}],41:[function(e,t,n){(function(n){function r(e,t){return"function"==typeof e?e:t}function i(e,t,r){if(!(this instanceof i))return new i(e,t,r);var o;if(c.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{}, +t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e,e=null),"function"==typeof t&&(r=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),r)return n.nextTick(function(){r(o)});throw o}t=B(t),this.options=h(R,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(r)}function o(e,t,n){if(!e._isOpening()&&!e.isOpen())return j(e,new b("Database is not open"),n),!0}function a(e,t,n){j(e,new v(t),n)}function s(e,t,n){j(e,new b(t),n)}function u(e){return function(t,n){A()[e](t,n||function(){})}}var c=e(25).EventEmitter,f=e(91).inherits,l=e(91).deprecate,h=e(45),d=e(58),p=e(14),g=e(38),y=e(37),v=y.WriteError,b=y.ReadError,m=y.NotFoundError,_=y.OpenError,w=y.EncodingError,E=y.InitializationError,k=e(42),S=e(40),x=e(43),B=k.getOptions,R=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;f(i,c),i.prototype.open=function(e){var t,r,i=this;return this.isOpen()?(e&&n.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),r=t(this.location),void r.open(this.options,function(t){return t?j(i,new _(t),e):(i.db.setDb(r),i.db=r,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return n.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,n){var i,a=this;if(n=r(t,n),!o(this,t,n)){if(null===e||void 0===e||"function"!=typeof n)return s(this,"get() requires key and callback arguments",n);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(r,i){if(r)return r=/notfound/i.test(r)||r.notFound?new m("Key not found in database ["+e+"]",r):new b(r),j(a,r,n);if(n){try{i=a._codec.decodeValue(i,t)}catch(e){return n(new w(e))}n(null,i)}})}},i.prototype.put=function(e,t,n,i){var s,u,c=this;return i=r(n,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,n,i)||(n=B(n),s=this._codec.encodeKey(e,n),u=this._codec.encodeValue(t,n),this.db.put(s,u,n,function(n){return n?j(c,new v(n),i):(c.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,n){var i,s=this;return n=r(t,n),null===e||void 0===e?a(this,"del() requires a key argument",n):void(o(this,t,n)||(t=B(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new v(t),n):(s.emit("del",e),void(n&&n()))})))},i.prototype.batch=function(e,t,n){var i,s=this;return arguments.length?(n=r(t,n),Array.isArray(e)?void(o(this,t,n)||(t=B(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new v(t),n):(s.emit("batch",e),void(n&&n()))}))):a(this,"batch() requires an array argument",n)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,n,i){var o,a,u=this;return i=r(n,i),n=B(n),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,n),a=this._codec.encodeKey(t,n),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new _(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(37),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(57))},{14:14,25:25,37:37,38:38,40:40,42:42,43:43,45:45,57:57,58:58,91:91}],42:[function(e,t,n){function r(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,n=e(46).devDependencies.leveldown;try{t=e(6).version}catch(e){throw o(e)}if(!e(6).satisfies(t,n))throw new c("Installed version of LevelDOWN ("+t+") does not match required version ("+n+")");try{return u=e(6)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new c(f(t,e.message))}function a(e,t,n){"function"==typeof n?n(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,c=(e(45),e(37).LevelUPError),f=e(91).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:r,getLevelDOWN:i,dispatchError:a,isDefined:s}},{37:37,45:45,46:46,6:6,91:91}],43:[function(e,t,n){arguments[4][35][0].apply(n,arguments)},{35:35,44:44}],44:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(8).Buffer)},{8:8}],45:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],46:[function(e,t,n){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],47:[function(e,t,n){"use strict";function r(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=b,this.queue=[],this.outcome=void 0,e!==r&&u(this,e)}function o(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function a(e,t,n){p(function(){var r;try{r=t(n)}catch(t){return g.reject(e,t)}r===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,r)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function n(t){o||(o=!0,g.reject(e,t))}function r(t){o||(o=!0,g.resolve(e,t))}function i(){t(r,n)}var o=!1,a=c(i);"error"===a.status&&n(a.value)}function c(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}function f(e){return e instanceof this?e:g.resolve(new this(r),e)}function l(e){var t=new this(r);return g.reject(t,e)}function h(e){function t(e,t){function r(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(c,a))}n.resolve(e).then(r,function(e){o||(o=!0,g.reject(c,e))})}var n=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,c=new this(r);++ur._endkey)?e():r._limit&&r._limit>0&&r._count++>=r._limit?e():r._lt&&t>=r._lt||r._lte&&t>r._lte||r._gt&&t<=r._gt||r._gte&&t=r._keys.length||o<0?void 0:r._keys[o];r._pos=o,r._reverse?(r._exclusiveStart||a!==r._startkey)&&r._pos--:r._exclusiveStart&&a===r._startkey&&r._pos++}else r._pos=r._reverse?r._keys.length-1:0;t(),r.initCompleted=!0;for(var s=-1;++s-1){var o=JSON.parse(r);r=o.data}n(null,r)}))},a.prototype._del=function(e,t,n){var r=s(e,"key");return r?p(function(){n(r)}):(i.isBuffer(e)||(e=String(e)),void this.container.removeItem(e,n))},a.prototype._batch=function(e,t,n){var r=this;p(function(){function o(){++l===e.length&&n(f)}var a,u,c,f,l=0;if(Array.isArray(e)&&e.length)for(var h=0;h>>1,e[n]n?1:0};var a=n.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=n.lowerBound=function(e){var t=a(e);return t&&e[t]};n.lowerBoundInclusive=function(e){return!t(e,"gt")},n.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=n.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},c=n.upperBoundExclusive=function(e){return!!t(e,"lt")},f=n.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=n.upperBound=function(e){var t=f(e);return t&&e[t]};n.toLtgt=function(e,r,i,a,s){r=r||{},i=i||o;var u=arguments.length>3,c=n.lowerBoundKey(e),f=n.upperBoundKey(e);return c?"gt"===c?r.gt=i(e.gt,!1):r.gte=i(e[c],!1):u&&(r.gte=i(a,!1)),f?"lt"===f?r.lt=i(e.lt,!0):r.lte=i(e[f],!0):u&&(r.lte=i(s,!0)),null!=e.reverse&&(r.reverse=!!e.reverse),t(r,"max")&&delete r.max,t(r,"min")&&delete r.min,t(r,"start")&&delete r.start,t(r,"end")&&delete r.end,r},n.contains=function(e,t,i){i=i||n.compare;var o=s(e);if(r(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var f=l(e);if(r(f)){var a=i(t,f);if(a>0||0===a&&c(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(32)})},{32:32}],55:[function(e,t,n){function r(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*f;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function i(e){return e>=f?Math.round(e/f)+"d":e>=c?Math.round(e/c)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,f,"day")||a(e,c,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e1)for(var n=1;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||r||(n=t.decoder.write(n)),t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):(t.reading=!1,t.buffer.push(n)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function c(e,t){var n=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function f(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.length>0?l(e):_(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?n.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){p(e,t)}))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(x.listenerCount(e,"data")>0&&b(e))):void(r.ranOut=!0)}function v(){this._readableState.ranOut&&(this._readableState.ranOut=!1,y(this))}function b(e,t){var r=e._readableState;if(r.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=B.prototype.pipe,e.on=e.addListener=B.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?n.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function m(e,t){var n,r=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(a)n=r.shift();else if(!e||e>=i)n=o?r.join(""):S.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return n=null,t.length>0&&t.decoder&&(n=m(e,t),t.length-=n.length),0===t.length&&_(this),n;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(r,t)),n=e>0?m(e,t):null,null===n&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0), +t.ended&&!t.endEmitted&&0===t.length&&_(this),n},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){e===f&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),f.removeListener("end",i),f.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){c(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),c()}function u(){e.removeListener("close",s),c()}function c(){f.unpipe(e)}var f=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e];break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,d=h?i:o;l.endEmitted?n.nextTick(d):f.once("end",d),e.on("unpipe",r);var p=g(f);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",f),l.flowing||(this.on("readable",v),l.flowing=!0,n.nextTick(function(){y(f)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",v),t.flowing=!1;for(var i=0;i>>32-i,n)}function n(e,n,r,i,o,a,s){return t(n&r|~n&i,e,n,o,a,s)}function r(e,n,r,i,o,a,s){return t(n&i|r&~i,e,n,o,a,s)}function i(e,n,r,i,o,a,s){return t(n^r^i,e,n,o,a,s)}function o(e,n,r,i,o,a,s){return t(r^(n|~i),e,n,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],c=e[3];a=n(a,s,u,c,t[0],7,-680876936),c=n(c,a,s,u,t[1],12,-389564586),u=n(u,c,a,s,t[2],17,606105819),s=n(s,u,c,a,t[3],22,-1044525330),a=n(a,s,u,c,t[4],7,-176418897),c=n(c,a,s,u,t[5],12,1200080426),u=n(u,c,a,s,t[6],17,-1473231341),s=n(s,u,c,a,t[7],22,-45705983),a=n(a,s,u,c,t[8],7,1770035416),c=n(c,a,s,u,t[9],12,-1958414417),u=n(u,c,a,s,t[10],17,-42063),s=n(s,u,c,a,t[11],22,-1990404162),a=n(a,s,u,c,t[12],7,1804603682),c=n(c,a,s,u,t[13],12,-40341101),u=n(u,c,a,s,t[14],17,-1502002290),s=n(s,u,c,a,t[15],22,1236535329),a=r(a,s,u,c,t[1],5,-165796510),c=r(c,a,s,u,t[6],9,-1069501632),u=r(u,c,a,s,t[11],14,643717713),s=r(s,u,c,a,t[0],20,-373897302),a=r(a,s,u,c,t[5],5,-701558691),c=r(c,a,s,u,t[10],9,38016083),u=r(u,c,a,s,t[15],14,-660478335),s=r(s,u,c,a,t[4],20,-405537848),a=r(a,s,u,c,t[9],5,568446438),c=r(c,a,s,u,t[14],9,-1019803690),u=r(u,c,a,s,t[3],14,-187363961),s=r(s,u,c,a,t[8],20,1163531501),a=r(a,s,u,c,t[13],5,-1444681467),c=r(c,a,s,u,t[2],9,-51403784),u=r(u,c,a,s,t[7],14,1735328473),s=r(s,u,c,a,t[12],20,-1926607734),a=i(a,s,u,c,t[5],4,-378558),c=i(c,a,s,u,t[8],11,-2022574463),u=i(u,c,a,s,t[11],16,1839030562),s=i(s,u,c,a,t[14],23,-35309556),a=i(a,s,u,c,t[1],4,-1530992060),c=i(c,a,s,u,t[4],11,1272893353),u=i(u,c,a,s,t[7],16,-155497632),s=i(s,u,c,a,t[10],23,-1094730640),a=i(a,s,u,c,t[13],4,681279174),c=i(c,a,s,u,t[0],11,-358537222),u=i(u,c,a,s,t[3],16,-722521979),s=i(s,u,c,a,t[6],23,76029189),a=i(a,s,u,c,t[9],4,-640364487),c=i(c,a,s,u,t[12],11,-421815835),u=i(u,c,a,s,t[15],16,530742520),s=i(s,u,c,a,t[2],23,-995338651),a=o(a,s,u,c,t[0],6,-198630844),c=o(c,a,s,u,t[7],10,1126891415),u=o(u,c,a,s,t[14],15,-1416354905),s=o(s,u,c,a,t[5],21,-57434055),a=o(a,s,u,c,t[12],6,1700485571),c=o(c,a,s,u,t[3],10,-1894986606),u=o(u,c,a,s,t[10],15,-1051523),s=o(s,u,c,a,t[1],21,-2054922799),a=o(a,s,u,c,t[8],6,1873313359),c=o(c,a,s,u,t[15],10,-30611744),u=o(u,c,a,s,t[6],15,-1560198380),s=o(s,u,c,a,t[13],21,1309151649),a=o(a,s,u,c,t[4],6,-145523070),c=o(c,a,s,u,t[11],10,-1120210379),u=o(u,c,a,s,t[2],15,718787259),s=o(s,u,c,a,t[9],21,-343485551),e[0]=m(a,e[0]),e[1]=m(s,e[1]),e[2]=m(u,e[2]),e[3]=m(c,e[3])}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function c(e){var t,n,r,i,o,u,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)a(f,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;t<16;t+=1)r[t]=0;return i=8*c,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,r[14]=o,r[15]=u,a(f,r),f}function f(e){var t,n,r,i,o,s,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)a(f,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;t<16;t+=1)r[t]=0;return i=8*c,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,r[14]=o,r[15]=s,a(f,r),f}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=_[e>>8*t+4&15]+_[e>>8*t&15];return n}function h(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,a,s,u=this.byteLength,c=t(n,u),f=u;return r!==e&&(f=t(r,u)),c>f?new ArrayBuffer(0):(i=f-c,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,c,i),a.set(s),o)}}(),b.prototype.append=function(e){return this.appendBinary(d(e)),this},b.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},b.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},b.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},b.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},b.prototype._finish=function(e,t){var n,r,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=r,e[15]=i,a(this._hash,e)},b.hash=function(e,t){return b.hashBinary(d(e),t)},b.hashBinary=function(e,t){var n=c(e),r=h(n);return t?v(r):r},b.ArrayBuffer=function(){this.reset()},b.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=v(n)),this.reset(),n},b.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},b.ArrayBuffer.prototype.getState=function(){var e=b.prototype.getState.call(this);return e.buff=g(e.buff),e},b.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),b.prototype.setState.call(this,e)},b.ArrayBuffer.prototype.destroy=b.prototype.destroy,b.ArrayBuffer.prototype._finish=b.prototype._finish,b.ArrayBuffer.hash=function(e,t){var n=f(new Uint8Array(e)),r=h(n);return t?v(r):r},b})},{}],67:[function(e,t,n){function r(){i.call(this)}t.exports=r;var i=e(25).EventEmitter,o=e(31);o(r,i),r.Readable=e(76),r.Writable=e(78),r.Duplex=e(68),r.Transform=e(77),r.PassThrough=e(75),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&c.pause&&c.pause()}function r(){c.readable&&c.resume&&c.resume()}function o(){f||(f=!0,e.end())}function a(){f||(f=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){c.removeListener("data",n),e.removeListener("drain",r),c.removeListener("end",o),c.removeListener("close",a),c.removeListener("error",s),e.removeListener("error",s),c.removeListener("end",u),c.removeListener("close",u),e.removeListener("close",u)}var c=this;c.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(c.on("end",o),c.on("close",a));var f=!1;return c.on("error",s),e.on("error",s),c.on("end",u),c.on("close",u),e.on("close",u),e.emit("pipe",c),e}},{25:25,31:31,68:68,75:75,76:76,77:77,78:78}],68:[function(e,t,n){t.exports=e(69)},{69:69}],69:[function(e,t,n){"use strict";function r(e){return this instanceof r?(c.call(this,e),f.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e(56),u=e(9);u.inherits=e(31);var c=e(71),f=e(73);u.inherits(r,c);for(var l=a(f.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var c;!t.decoder||i||r||(n=t.decoder.write(n),c=!t.objectMode&&0===n.length),i||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function c(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function f(e,t){var n=null;return M.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(q("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){q("emit readable"),e.emit("readable"),_(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=E(e,t.buffer,t.decoder),n}function E(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=C.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(B,t,e))}function B(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function R(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return q("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=c(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;q("need readable",r),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){q("onunpipe"),e===h&&a()}function o(){q("onend"),e.end()}function a(){q("cleanup"),e.removeListener("close",c),e.removeListener("finish",f),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),b=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){q("ondata"),m=!1;var n=e.write(t);!1!==n||m||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!b&&(q("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,m=!0),h.pause())}function u(t){q("onerror",t),l(),e.removeListener("error",u),0===L(e,"error")&&e.emit("error",t)}function c(){e.removeListener("finish",f),l()}function f(){q("onfinish"),e.removeListener("close",c),l()}function l(){q("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var v=y(h);e.on("drain",v);var b=!1,m=!1;return h.on("data",s),r(e,"error",u),e.once("close",c),e.once("finish",f),e.emit("pipe",h),d.flowing||(q("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(9);x.inherits=e(31);var B,R={deprecate:e(88)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(25).EventEmitter)}}();var A=e(8).Buffer,j=e(7);x.inherits(a,B);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:R.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=f(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(57))},{25:25,31:31,56:56,57:57,69:69,7:7,8:8,88:88,9:9}],74:[function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(e(8).Buffer,e(7));t.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},{7:7,8:8}],75:[function(e,t,n){t.exports=e(70)},{70:70}],76:[function(e,t,n){(function(r){var i=function(){try{return e("stream")}catch(e){}}();n=t.exports=e(71),n.Stream=i||n,n.Readable=n,n.Writable=e(73),n.Duplex=e(69),n.Transform=e(72),n.PassThrough=e(70),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(57))},{57:57,69:69,70:70,71:71,72:72,73:73}],77:[function(e,t,n){t.exports=e(72)},{72:72}],78:[function(e,t,n){t.exports=e(73)},{73:73}],79:[function(e,t,n){function r(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(8).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},c=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};c.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},c.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},c.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}},{8:8}],80:[function(e,t,n){arguments[4][69][0].apply(n,arguments)},{31:31,56:56,69:69,81:81,83:83,9:9}],81:[function(e,t,n){(function(n){"use strict";function r(t,n){C=C||e(80),t=t||{},this.objectMode=!!t.objectMode,n instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(M||(M=e(79).StringDecoder),this.decoder=new M(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(80),this instanceof i?(this._readableState=new r(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,n,r,i){var o=c(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,f(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||r||(n=t.decoder.write(n),u=!t.objectMode&&0===n.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=I?e=I:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function c(e,t){var n=null;return R.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function f(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(L("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){L("emit readable"),e.emit("readable"),m(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)n=o?r.join(""):1===r.length?r[0]:R.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return L("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;L("need readable",r),(0===t.length||t.length-e0?_(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){L("onunpipe"),e===l&&o()}function i(){L("onend"),e.end()}function o(){L("cleanup"),e.removeListener("close",u),e.removeListener("finish",c),e.removeListener("drain",y),e.removeListener("error",s),e.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),v=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function a(t){L("ondata");var n=e.write(t);!1===n&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||v||(L("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){L("onerror",t),f(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",c),f()}function c(){L("onfinish"),e.removeListener("close",u),f()}function f(){L("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,L("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",r);var y=g(l);e.on("drain",y);var v=!1;return l.on("data",a),e._events&&e._events.error?B(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",c),e.emit("pipe",l),h.flowing||(L("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(8).Buffer;a.WritableState=o;var B=e(9);B.inherits=e(31);var R,A={deprecate:e(88)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(25).EventEmitter)}}();var x=e(8).Buffer;B.inherits(a,R);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=f(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(57))},{25:25,31:31,56:56,57:57,8:8,80:80,88:88,9:9}],84:[function(e,t,n){arguments[4][77][0].apply(n,arguments)},{77:77,82:82}],85:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{20:20}],86:[function(e,t,n){(function(n){function r(e){a.call(this,e),this._destroyed=!1}function i(e,t,n){n(null,e)}function o(e){return function(t,n,r){return"function"==typeof t&&(r=n,n=t,t={}),"function"!=typeof n&&(n=i),"function"!=typeof r&&(r=null),e(t,n,r)}}var a=e(84),s=e(91).inherits,u=e(85);s(r,a),r.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;n.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,n){var i=new r(e);return i._transform=t,n&&(i._flush=n),i}),t.exports.ctor=o(function(e,t,n){function i(t){return this instanceof i?(this.options=u(e,t),void r.call(this,this.options)):new i(t)}return s(i,r),i.prototype._transform=t,n&&(i.prototype._flush=n),i}),t.exports.obj=o(function(e,t,n){var i=new r(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,n&&(i._flush=n),i})}).call(this,e(57))},{57:57,84:84,85:85,91:91}],87:[function(e,t,n){"use strict";function r(){this.length=0}r.prototype.push=function(e){var t={item:e};this.last?this.last=this.last.next=t:this.last=this.first=t,this.length++},r.prototype.shift=function(){var e=this.first;if(e)return this.first=e.next,--this.length||(this.last=void 0),e.item},r.prototype.slice=function(e,t){e="undefined"==typeof e?0:e,t="undefined"==typeof t?1/0:t;for(var n=[],r=0,i=this.first;i&&!(--t<0);i=i.next)++r>e&&n.push(i.item);return n},t.exports=r},{}],88:[function(e,t,n){(function(e){function n(e,t){function n(){if(!i){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],89:[function(e,t,n){arguments[4][31][0].apply(n,arguments)},{31:31}],90:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],91:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&B(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return m(i)||(i=u(e,i,r)),i}var o=c(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(t);if(0===a.length){if(B(t)){var y=t.name?": "+t.name:"";return e.stylize("[Function"+y+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return f(t)}var v="",b=!1,_=["{","}"];if(p(t)&&(b=!0,_=["[","]"]),B(t)){var w=t.name?": "+t.name:"";v=" [Function"+w+"]"}if(E(t)&&(v=" "+RegExp.prototype.toString.call(t)),S(t)&&(v=" "+Date.prototype.toUTCString.call(t)),x(t)&&(v=" "+f(t)),0===a.length&&(!b||0==t.length))return _[0]+v+_[1];if(r<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=b?l(e,t,r,g,a):a.map(function(n){return h(e,t,r,g,n,b)}),e.seen.pop(),d(k,v,_)}function c(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function m(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function B(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),I[e.getMonth()],t].join(" ")}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var L=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(c in r)r.hasOwnProperty(c)&&u.push(c);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)f=u[a],l=r[f],h=a>0?",":"",h+=JSON.stringify(f)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},n.parse=function(e){for(var t,n,i,o,a,s,u,c,f,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,r(null,l,h);break;case"t":d+=3,r(!0,l,h);break;case"f":d+=4,r(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",d--;;){if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}n+=i}r(parseFloat(n),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+o+'"'),l,h);break;case"[":c={element:[],index:l.length},l.push(c.element),h.push(c);break;case"{":f={element:{},index:l.length},l.push(f.element),h.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,h)}}},{}],93:[function(e,t,n){function r(){for(var e={},t=0;t>>1,n(e[r],t)<0?i=r+1:o=r;return i}function H(e,t,n){var r=J(e,t,n);e.splice(r,0,t)}function $(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var y=g.ids[2],v=0,b=y.length;v0||r0||ri.end)return t(null,{total_rows:r,offset:e.skip,rows:[]});var u=[],c=k.docStore.readStream(i),f=We.obj(function(t,n,r){function i(t){var n={id:a.id,key:a.id,value:{rev:f}};if(e.include_docs){n.doc=t,n.doc._rev=n.value.rev,e.conflicts&&(n.doc._conflicts=z(a));for(var i in n.doc._attachments)n.doc._attachments.hasOwnProperty(i)&&(n.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return r();if(l){if("ok"!==e.deleted)return r();n.value.deleted=!0,n.doc=null}u.push(n),r()}var a=t.value,f=Re(a),l=Ae(a,f);if(l){if("ok"!==e.deleted)return void r()}else{if(o-- >0)return void r();if("number"==typeof s&&s--<=0)return c.unpipe(),c.destroy(),void r()}if(e.include_docs){var h=a.rev_map[f];k.bySeqStore.get(y(h),function(e,t){i(t)})}else i()},function(n){it.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,k,e)}).then(function(){t(null,{total_rows:r,offset:e.skip,rows:u})},t),n()}).on("unpipe",function(){f.end()});c.on("error",t),c.pipe(f)})}),E._changes=function(e){function t(){e.done=!0,c&&e.limit&&e.limit0&&(r=e.limit),u.reverse||(u.start=y(e.since||0));var c,f=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;c="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var d=k.bySeqStore.readStream(u),b=We.obj(function(n,u,d){function p(t){function n(n){var r=e.processChange(n,t,e);r.seq=t.seq;var i=l(r);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([r],k,e).then(function(){e.onChange(r)}):e.onChange(r),c&&o.push(r)),void d())}var r=Re(t);if(t.seq!==g)return d();if(a=g,r===b._rev)return n(b);var i=t.rev_map[r];k.bySeqStore.get(y(i),function(e,t){n(t)})}if(r&&s>=r)return t(),d();if(e.cancelled||e.done)return d();var g=v(n.key),b=n.value;if(g===e.since&&!i)return d();if(f&&!f.has(b._id))return d();var m;return(m=h.get(b._id))?p(m):void k.docStore.get(b._id,function(t,n){return e.cancelled||e.done||w.isClosed()||ie(n.id)?d():(h.set(b._id,n),void p(n))})},function(t){return e.cancelled?t():(c&&e.limit&&e.limitr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){ +var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(De.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Ne(R,Error),R.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var st,ut=(new R({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new R({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new R({status:404,error:"not_found",reason:"missing"})),ct=new R({status:409,error:"conflict",reason:"Document update conflict"}),ft=new R({status:400,error:"bad_request",reason:"_id field must contain a string"}),lt=new R({status:412,error:"missing_id",reason:"_id is required for puts"}),ht=new R({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),dt=new R({status:412,error:"precondition_failed",reason:"Database not open"}),pt=(new R({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new R({status:500,error:"badarg",reason:"Some query argument is invalid"})),gt=(new R({status:400,error:"invalid_request",reason:"Request was invalid"}),new R({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new R({status:500,error:"doc_validation",reason:"Bad special document member"})),yt=new R({status:400,error:"bad_request",reason:"Something wrong with the request"}),vt=(new R({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new R({status:404,error:"not_found",reason:"Database not found"}),new R({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new R({status:500,error:"web_sql_went_bad",reason:"unknown"}),new R({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new R({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new R({status:400,error:"bad_request",reason:"Invalid rev format"})),bt=(new R({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new R({status:412,error:"missing_stub"})),mt=(new R({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),T.name);st=mt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var _t=st,wt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Et=I(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),kt=I(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),St=function(e){return atob(e)},xt=function(e){return btoa(e)},Bt=n.setImmediate||n.setTimeout,Rt=32768;Be.prototype.get=function(e,n,r){var i=xe(this,e),o=i.get(n);return o?t.nextTick(function(){r(null,o)}):null===o?t.nextTick(function(){r({name:"NotFoundError"})}):void e.get(n,function(e,t){return e?("NotFoundError"===e.name&&i.set(n,null),r(e)):(i.set(n,t),void r(null,t))})},Be.prototype.batch=function(e){for(var t=0,n=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;n.has(a)||(n.add(a),r.push(o))}e.batch(r,t)};var At="document-store",jt="by-sequence",Ot="attach-store",Tt="attach-binary-store",Lt="local-store",Mt="meta-store",Ct=new p,It="_local_last_update_seq",Dt="_local_doc_count",qt="_local_uuid",Nt="md5-",Pt={encode:we,decode:_e,buffer:!1,type:"cheap-json"},Ut=new x;Le.valid=function(){return"undefined"!=typeof localStorage},Le.use_prefix=!0;var Wt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");Wt?Me(Wt):B("error",'localstorage adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(57),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(8).Buffer)},{11:11,21:21,25:25,31:31,34:34,35:35,4:4,41:41,47:47,48:48,54:54,57:57,65:65,66:66,8:8,86:86,92:92,pouchdb:"pouchdb"}]},{},[94]); diff --git a/lib/pouchdb/dist/pouchdb.memory.js b/lib/pouchdb/dist/pouchdb.memory.js index e97d9d8b..d1ef46ac 100644 --- a/lib/pouchdb/dist/pouchdb.memory.js +++ b/lib/pouchdb/dist/pouchdb.memory.js @@ -1,4 +1,4 @@ -// PouchDB in-memory plugin 6.0.4 +// PouchDB in-memory plugin 6.0.6 // Based on MemDOWN: https://github.com/rvagg/memdown // // (c) 2012-2016 Dale Harvey and the PouchDB team @@ -28,6 +28,7 @@ function argsArray(fun) { },{}],2:[function(_dereq_,module,exports){ 'use strict' +exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray @@ -35,23 +36,17 @@ var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array -function init () { - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -init() +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr +function placeHoldersCount (b64) { var len = b64.length - if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } @@ -61,9 +56,19 @@ function toByteArray (b64) { // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} +function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars @@ -2524,7 +2529,7 @@ function coerce(val) { } },{"51":51}],9:[function(_dereq_,module,exports){ -var util = _dereq_(85) +var util = _dereq_(86) , AbstractIterator = _dereq_(14).AbstractIterator @@ -2559,9 +2564,9 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"14":14,"85":85}],10:[function(_dereq_,module,exports){ +},{"14":14,"86":86}],10:[function(_dereq_,module,exports){ (function (Buffer,process){ -var util = _dereq_(85) +var util = _dereq_(86) , AbstractLevelDOWN = _dereq_(14).AbstractLevelDOWN , DeferredIterator = _dereq_(9) @@ -2619,7 +2624,7 @@ module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator }).call(this,{"isBuffer":_dereq_(26)},_dereq_(53)) -},{"14":14,"26":26,"53":53,"85":85,"9":9}],11:[function(_dereq_,module,exports){ +},{"14":14,"26":26,"53":53,"86":86,"9":9}],11:[function(_dereq_,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -5705,8 +5710,8 @@ module.exports = Batch */ var EventEmitter = _dereq_(21).EventEmitter - , inherits = _dereq_(85).inherits - , deprecate = _dereq_(85).deprecate + , inherits = _dereq_(86).inherits + , deprecate = _dereq_(86).deprecate , extend = _dereq_(39) , prr = _dereq_(54) , DeferredLevelDOWN = _dereq_(10) @@ -6099,7 +6104,7 @@ module.exports.repair = deprecate( }).call(this,_dereq_(53)) -},{"10":10,"21":21,"31":31,"32":32,"34":34,"36":36,"37":37,"39":39,"53":53,"54":54,"85":85}],36:[function(_dereq_,module,exports){ +},{"10":10,"21":21,"31":31,"32":32,"34":34,"36":36,"37":37,"39":39,"53":53,"54":54,"86":86}],36:[function(_dereq_,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -6108,7 +6113,7 @@ module.exports.repair = deprecate( var extend = _dereq_(39) , LevelUPError = _dereq_(31).LevelUPError - , format = _dereq_(85).format + , format = _dereq_(86).format , defaultOptions = { createIfMissing : true , errorIfExists : false @@ -6178,7 +6183,7 @@ module.exports = { , isDefined : isDefined } -},{"3":3,"31":31,"39":39,"40":40,"85":85}],37:[function(_dereq_,module,exports){ +},{"3":3,"31":31,"39":39,"40":40,"86":86}],37:[function(_dereq_,module,exports){ arguments[4][29][0].apply(exports,arguments) },{"29":29,"38":38}],38:[function(_dereq_,module,exports){ (function (Buffer){ @@ -6873,13 +6878,10 @@ var inherits = _dereq_(25) , AbstractLevelDOWN = _dereq_(47).AbstractLevelDOWN , AbstractIterator = _dereq_(47).AbstractIterator , ltgt = _dereq_(49) - , setImmediate = global.setImmediate || process.nextTick , createRBT = _dereq_(22) , globalStore = {} - -function toKey (key) { - return typeof key == 'string' ? '$' + key : JSON.stringify(key) -} +/* istanbul ignore next */ +var setImmediate = global.setImmediate || process.nextTick function gt(value) { return ltgt.compare(value, this._end) > 0 @@ -6905,7 +6907,7 @@ function MemIterator (db, options) { if (this._limit === -1) this._limit = Infinity - var tree = db._store[db._location]; + var tree = db._store[db._location] this.keyAsBuffer = options.keyAsBuffer !== false this.valueAsBuffer = options.valueAsBuffer !== false @@ -6914,16 +6916,16 @@ function MemIterator (db, options) { this._done = 0 if (!this._reverse) { - this._incr = 'next'; - this._start = ltgt.lowerBound(options); + this._incr = 'next' + this._start = ltgt.lowerBound(options) this._end = ltgt.upperBound(options) if (typeof this._start === 'undefined') - this._tree = tree.begin; + this._tree = tree.begin else if (ltgt.lowerBoundInclusive(options)) - this._tree = tree.ge(this._start); + this._tree = tree.ge(this._start) else - this._tree = tree.gt(this._start); + this._tree = tree.gt(this._start) if (this._end) { if (ltgt.upperBoundInclusive(options)) @@ -6933,12 +6935,12 @@ function MemIterator (db, options) { } } else { - this._incr = 'prev'; + this._incr = 'prev' this._start = ltgt.upperBound(options) this._end = ltgt.lowerBound(options) if (typeof this._start === 'undefined') - this._tree = tree.end; + this._tree = tree.end else if (ltgt.upperBoundInclusive(options)) this._tree = tree.le(this._start) else @@ -6994,7 +6996,7 @@ function MemDOWN (location) { AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') - this._location = this.location ? toKey(this.location) : '_tree' + this._location = this.location ? ('$' + this.location) : '_tree' this._store = this.location ? globalStore: this this._store[this._location] = this._store[this._location] || createRBT(ltgt.compare) } @@ -7002,7 +7004,7 @@ function MemDOWN (location) { MemDOWN.clearGlobalStore = function (strict) { if (strict) { Object.keys(globalStore).forEach(function (key) { - delete globalStore[key]; + delete globalStore[key] }) } else { globalStore = {} @@ -7033,10 +7035,9 @@ MemDOWN.prototype._put = function (key, value, options, callback) { MemDOWN.prototype._get = function (key, options, callback) { var value = this._store[this._location].get(key) - if (value === undefined) { + if (typeof value === 'undefined') { // 'NotFound' error, consistent with LevelDOWN API - var err = new Error('NotFound') - return setImmediate(function callNext() { callback(err) }) + return setImmediate(function callNext() { callback(new Error('NotFound')) }) } if (options.asBuffer !== false && !this._isBuffer(value)) @@ -7054,8 +7055,7 @@ MemDOWN.prototype._del = function (key, options, callback) { } MemDOWN.prototype._batch = function (array, options, callback) { - var err - , i = -1 + var i = -1 , key , value , iter @@ -7064,30 +7064,20 @@ MemDOWN.prototype._batch = function (array, options, callback) { while (++i < len) { if (!array[i]) - continue; + continue key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key) - err = this._checkKey(key, 'key') - if (err) - return setImmediate(function errorCall() { callback(err) }) - iter = tree.find(key) if (array[i].type === 'put') { value = this._isBuffer(array[i].value) ? array[i].value : String(array[i].value) - if (value === null || value === undefined) - err = new Error('value cannot be `null` or `undefined`') - - if (err) - return setImmediate(function errorCall() { callback(err) }) - tree = iter.valid ? iter.update(value) : tree.insert(key, value) } else { tree = iter.remove() } } - this._store[this._location] = tree; + this._store[this._location] = tree setImmediate(callback) } @@ -7101,7 +7091,7 @@ MemDOWN.prototype._isBuffer = function (obj) { } MemDOWN.destroy = function (name, callback) { - var key = toKey(name) + var key = '$' + name if (key in globalStore) delete globalStore[key] @@ -7113,376 +7103,12 @@ module.exports = MemDOWN }).call(this,_dereq_(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(5).Buffer) },{"22":22,"25":25,"47":47,"49":49,"5":5,"53":53}],44:[function(_dereq_,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -function AbstractChainedBatch (db) { - this._db = db - this._operations = [] - this._written = false -} - -AbstractChainedBatch.prototype._serializeKey = function (key) { - return this._db._serializeKey(key) -} - -AbstractChainedBatch.prototype._serializeValue = function (value) { - return this._db._serializeValue(value) -} - -AbstractChainedBatch.prototype._checkWritten = function () { - if (this._written) - throw new Error('write() already called on this batch') -} - -AbstractChainedBatch.prototype.put = function (key, value) { - this._checkWritten() - - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) - throw err - - key = this._serializeKey(key) - value = this._serializeValue(value) - - if (typeof this._put == 'function' ) - this._put(key, value) - else - this._operations.push({ type: 'put', key: key, value: value }) - - return this -} - -AbstractChainedBatch.prototype.del = function (key) { - this._checkWritten() - - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) throw err - - key = this._serializeKey(key) - - if (typeof this._del == 'function' ) - this._del(key) - else - this._operations.push({ type: 'del', key: key }) - - return this -} - -AbstractChainedBatch.prototype.clear = function () { - this._checkWritten() - - this._operations = [] - - if (typeof this._clear == 'function' ) - this._clear() - - return this -} - -AbstractChainedBatch.prototype.write = function (options, callback) { - this._checkWritten() - - if (typeof options == 'function') - callback = options - if (typeof callback != 'function') - throw new Error('write() requires a callback argument') - if (typeof options != 'object') - options = {} - - this._written = true - - if (typeof this._write == 'function' ) - return this._write(callback) - - if (typeof this._db._batch == 'function') - return this._db._batch(this._operations, options, callback) - - process.nextTick(callback) -} - -module.exports = AbstractChainedBatch - -}).call(this,_dereq_(53)) -},{"53":53}],45:[function(_dereq_,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"11":11,"53":53}],45:[function(_dereq_,module,exports){ arguments[4][12][0].apply(exports,arguments) },{"12":12,"53":53}],46:[function(_dereq_,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -var xtend = _dereq_(50) - , AbstractIterator = _dereq_(45) - , AbstractChainedBatch = _dereq_(44) - -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') - - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') - - this.location = location - this.status = 'new' -} - -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - , oldStatus = this.status - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') - - if (typeof options != 'object') - options = {} - - options.createIfMissing = options.createIfMissing != false - options.errorIfExists = !!options.errorIfExists - - if (typeof this._open == 'function') { - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'open' - callback() - }) - } else { - this.status = 'open' - process.nextTick(callback) - } -} - -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - , oldStatus = this.status - - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') - - if (typeof this._close == 'function') { - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) - } else { - this.status = 'closed' - process.nextTick(callback) - } -} - -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') - - if (err = this._checkKey(key, 'key')) - return callback(err) - - key = this._serializeKey(key) - - if (typeof options != 'object') - options = {} - - options.asBuffer = options.asBuffer != false - - if (typeof this._get == 'function') - return this._get(key, options, callback) - - process.nextTick(function () { callback(new Error('NotFound')) }) -} - -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') - - if (err = this._checkKey(key, 'key')) - return callback(err) - - key = this._serializeKey(key) - value = this._serializeValue(value) - - if (typeof options != 'object') - options = {} - - if (typeof this._put == 'function') - return this._put(key, value, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') - - if (err = this._checkKey(key, 'key')) - return callback(err) - - key = this._serializeKey(key) - - if (typeof options != 'object') - options = {} - - if (typeof this._del == 'function') - return this._del(key, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() - - if (typeof options == 'function') - callback = options - - if (typeof array == 'function') - callback = array - - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') - - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) - - if (!options || typeof options != 'object') - options = {} - - var i = 0 - , l = array.length - , e - , err - - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue - - if (err = this._checkKey(e.type, 'type')) - return callback(err) - - if (err = this._checkKey(e.key, 'key')) - return callback(err) - } - - if (typeof this._batch == 'function') - return this._batch(array, options, callback) - - process.nextTick(callback) -} - -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') - } - - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') - - start = this._serializeKey(start) - end = this._serializeKey(end) - - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) - - process.nextTick(function () { - callback(null, 0) - }) -} - -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this - - options = xtend(options) - - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) - - options.reverse = !!options.reverse - options.keys = options.keys != false - options.values = options.values != false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer != false - options.valueAsBuffer = options.valueAsBuffer != false - - return options -} - -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} - - options = this._setupIteratorOptions(options) - - if (typeof this._iterator == 'function') - return this._iterator(options) - - return new AbstractIterator(this) -} - -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} - -AbstractLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) -} - -AbstractLevelDOWN.prototype._serializeKey = function (key) { - return this._isBuffer(key) - ? key - : String(key) -} - -AbstractLevelDOWN.prototype._serializeValue = function (value) { - return this._isBuffer(value) || process.browser - ? value - : String(value) -} - -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') - - if (this._isBuffer(obj) && obj.length === 0) - return new Error(type + ' cannot be an empty Buffer') - else if (String(obj) === '') - return new Error(type + ' cannot be an empty String') -} - -module.exports = AbstractLevelDOWN - -}).call(this,{"isBuffer":_dereq_(26)},_dereq_(53)) -},{"26":26,"44":44,"45":45,"50":50,"53":53}],47:[function(_dereq_,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"13":13,"26":26,"44":44,"45":45,"50":50,"53":53}],47:[function(_dereq_,module,exports){ arguments[4][14][0].apply(exports,arguments) },{"14":14,"44":44,"45":45,"46":46,"48":48}],48:[function(_dereq_,module,exports){ arguments[4][15][0].apply(exports,arguments) @@ -14188,7 +13814,7 @@ arguments[4][16][0].apply(exports,arguments) },{"16":16}],82:[function(_dereq_,module,exports){ (function (process){ var Transform = _dereq_(80) - , inherits = _dereq_(85).inherits + , inherits = _dereq_(86).inherits , xtend = _dereq_(81) function DestroyableTransform(opts) { @@ -14285,7 +13911,7 @@ module.exports.obj = through2(function (options, transform, flush) { }) }).call(this,_dereq_(53)) -},{"53":53,"80":80,"81":81,"85":85}],83:[function(_dereq_,module,exports){ +},{"53":53,"80":80,"81":81,"86":86}],83:[function(_dereq_,module,exports){ (function (global){ /** @@ -14357,13 +13983,15 @@ function config (name) { }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],84:[function(_dereq_,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"25":25}],85:[function(_dereq_,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],85:[function(_dereq_,module,exports){ +},{}],86:[function(_dereq_,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14890,7 +14518,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = _dereq_(84); +exports.isBuffer = _dereq_(85); function objectToString(o) { return Object.prototype.toString.call(o); @@ -14934,7 +14562,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = _dereq_(25); +exports.inherits = _dereq_(84); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -14953,7 +14581,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,_dereq_(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"25":25,"53":53,"84":84}],86:[function(_dereq_,module,exports){ +},{"53":53,"84":84,"85":85}],87:[function(_dereq_,module,exports){ 'use strict'; /** @@ -15128,7 +14756,7 @@ exports.parse = function (str) { } }; -},{}],87:[function(_dereq_,module,exports){ +},{}],88:[function(_dereq_,module,exports){ (function (process,global,Buffer){ 'use strict'; @@ -15147,7 +14775,7 @@ var Deque = _interopDefault(_dereq_(17)); var lie = _interopDefault(_dereq_(41)); var debug = _interopDefault(_dereq_(7)); var Md5 = _interopDefault(_dereq_(62)); -var vuvuzela = _interopDefault(_dereq_(86)); +var vuvuzela = _interopDefault(_dereq_(87)); var jsExtend = _dereq_(28); var memdown = _interopDefault(_dereq_(43)); @@ -15282,8 +14910,8 @@ function nut(db, precodec, codec) { }; } -function NotFoundError(reason) { - Error.call(this, reason); +function NotFoundError() { + Error.call(this); } inherits(NotFoundError, Error); @@ -15293,6 +14921,8 @@ NotFoundError.prototype.name = 'NotFoundError'; var EventEmitter$1 = events__default.EventEmitter; var version = "6.5.4"; +var NOT_FOUND_ERROR = new NotFoundError(); + var sublevel = function (nut, prefix, createStream, options) { var emitter = new EventEmitter$1(); emitter.sublevels = {}; @@ -15381,7 +15011,7 @@ var sublevel = function (nut, prefix, createStream, options) { } nut.get(key, prefix, mergeOpts(opts), function (err, value) { if (err) { - cb(new NotFoundError(err)); + cb(NOT_FOUND_ERROR); } else { cb(null, value); } @@ -15584,25 +15214,6 @@ _Set.prototype.has = function (key) { return this.store.has(key); }; -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -17342,8 +16953,8 @@ function LevelPouch(opts, callback) { db._docCount = -1; db._queue = new Deque(); /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationOne(name, db, afterDBCreated); } else { afterDBCreated(); } @@ -17358,19 +16969,26 @@ function LevelPouch(opts, callback) { stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationTwo(db, stores, afterLastMigration); + } else { + afterLastMigration(); + } + } + + function afterLastMigration() { + stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { + if (typeof db._updateSeq === 'undefined') { + db._updateSeq = value || 0; + } + stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { + db._docCount = !err ? value : 0; + stores.metaStore.get(UUID_KEY, function (err, value) { + instanceId = !err ? value : uuid(); + stores.metaStore.put(UUID_KEY, instanceId, function () { + process.nextTick(function () { + callback(null, api); }); }); }); @@ -18659,4 +18277,4 @@ if (!PDB) { MemoryPouchPlugin(PDB); } }).call(this,_dereq_(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_(5).Buffer) -},{"1":1,"17":17,"21":21,"25":25,"28":28,"29":29,"35":35,"41":41,"42":42,"43":43,"5":5,"53":53,"61":61,"62":62,"7":7,"82":82,"86":86,"pouchdb":"pouchdb"}]},{},[87]); +},{"1":1,"17":17,"21":21,"25":25,"28":28,"29":29,"35":35,"41":41,"42":42,"43":43,"5":5,"53":53,"61":61,"62":62,"7":7,"82":82,"87":87,"pouchdb":"pouchdb"}]},{},[88]); diff --git a/lib/pouchdb/dist/pouchdb.memory.min.js b/lib/pouchdb/dist/pouchdb.memory.min.js index 4564e326..168fa8d3 100644 --- a/lib/pouchdb/dist/pouchdb.memory.min.js +++ b/lib/pouchdb/dist/pouchdb.memory.min.js @@ -1,14 +1,14 @@ -// PouchDB in-memory plugin 6.0.4 +// PouchDB in-memory plugin 6.0.6 // Based on MemDOWN: https://github.com/rvagg/memdown // // (c) 2012-2016 Dale Harvey and the PouchDB team // PouchDB may be freely distributed under the Apache license, version 2.0. // For all details and documentation: // http://pouchdb.com -!function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var c=r[a]={exports:{}};t[a][0].call(c.exports,function(e){var r=t[a][1][e];return i(r?r:e)},c,c.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new c(3*s/4-o),n=o>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=f[e.charCodeAt(t)]<<2|f[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=f[e.charCodeAt(t)]<<10|f[e.charCodeAt(t+1)]<<4|f[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}function o(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,r){for(var n,i=[],a=t;ac?c:f+s));return 1===n?(t=e[r-1],i+=u[t>>2],i+=u[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=u[t>>10],i+=u[t>>4&63],i+=u[t<<2&63],i+="="),o.push(i),o.join("")}r.toByteArray=i,r.fromByteArray=s;var u=[],f=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],3:[function(e,t,r){},{}],4:[function(e,t,r){(function(t){"use strict";var n=e(5),i=n.Buffer,o=n.SlowBuffer,a=n.kMaxLength||2147483647;r.alloc=function(e,t,r){if("function"==typeof i.alloc)return i.alloc(e,t,r);if("number"==typeof r)throw new TypeError("encoding must not be number");if("number"!=typeof e)throw new TypeError("size must be a number");if(e>a)throw new RangeError("size is too large");var n=r,o=t;void 0===o&&(n=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,n),f=u.length,c=-1;++ca)throw new RangeError("size is too large");return new i(e)},r.from=function(e,r,n){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,r,n);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,r);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=r;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=n;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},r.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{5:5}],5:[function(e,t,r){(function(t){"use strict";function n(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function v(e){return+e!=e&&(e=0),a.alloc(+e)}function y(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Y(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return H(e).length;default:if(n)return Y(e).length;t=(""+t).toLowerCase(),n=!0}}function _(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return L(this,t,r);case"utf8":case"utf-8":return j(this,t,r);case"ascii":return M(this,t,r);case"latin1":case"binary":return T(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function b(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}var f;if(i){var c=-1;for(f=r;fs&&(r=s-u),f=r;f>=0;f--){for(var l=!0,h=0;hi&&(n=i)):n=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=r){var u,f,c,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],f=e[i+2],128===(192&u)&&128===(192&f)&&(l=(15&o)<<12|(63&u)<<6|63&f,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],f=e[i+2],c=e[i+3],128===(192&u)&&128===(192&f)&&128===(192&c)&&(l=(15&o)<<18|(63&u)<<12|(63&f)<<6|63&c,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=s}return O(n)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function q(e,t,r,n,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function P(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function N(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function I(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return i||I(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,r,n,23,4),r+4}function W(e,t,r,n,i){return i||I(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,r,n,52,8),r+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function K(e){return e<16?"0"+e.toString(16):e.toString(16)}function Y(e,t){t=t||1/0;for(var r,n=e.length,i=null,o=[],a=0;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function J(e){for(var t=[],r=0;r>8,i=r%256,o.push(i),o.push(n);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function G(e){return e!==e}var X=e(2),Z=e(23),Q=e(27);r.Buffer=a,r.SlowBuffer=v,r.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:n(),r.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,r){return s(null,e,t,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,r){return f(null,e,t,r)},a.allocUnsafe=function(e){return c(null,e)},a.allocUnsafeSlow=function(e){return c(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,r,n,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var o=i-n,s=r-t,u=Math.min(o,s),f=this.slice(n,i),c=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return E(this,e,t,r);case"utf8":case"utf-8":return k(this,e,t,r);case"ascii":return S(this,e,t,r);case"latin1":case"binary":return x(this,e,t,r);case"base64":return B(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,r){e=0|e,t=0|t,r||D(e,t,this.length);for(var n=this[e],i=1,o=0;++o=i&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e=0|e,t=0|t,r||D(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t=0|t,r=0|r,!n){var i=Math.pow(2,8*r)-1;q(this,e,t,r,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+r},a.prototype.writeUInt8=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=0|t,!n){var i=Math.pow(2,8*r-1);q(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=0|t,!n){var i=Math.pow(2,8*r-1);q(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t=0|t,r||q(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return W(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return W(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff),!t)return e;var n="color: "+this.color;e=[e[0],n,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,n),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?r.storage.removeItem("debug"):r.storage.debug=e}catch(e){}}function s(){var e;try{e=r.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}r=t.exports=e(8),r.log=o,r.formatArgs=i,r.save=a,r.load=s,r.useColors=n,r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(e){return JSON.stringify(e)},r.enable(s())},{8:8}],8:[function(e,t,r){function n(){return r.colors[c++%r.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(f||t);e.diff=o,e.prev=f,e.curr=t,f=t,null==e.useColors&&(e.useColors=r.useColors()),null==e.color&&e.useColors&&(e.color=n());var a=Array.prototype.slice.call(arguments);a[0]=r.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,n){if("%%"===t)return t;s++;var i=r.formatters[n];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof r.formatArgs&&(a=r.formatArgs.apply(e,a));var u=i.log||r.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=r.enabled(e)?i:t;return o.namespace=e,o}function o(e){r.save(e);for(var t=(e||"").split(/[\s,]+/),n=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}n.prototype.toArray=function(){for(var e=this._length,t=new Array(e),r=this._front,n=this._capacity,i=0;i1){var n=this._capacity;if(r+t>n){for(var i=0;i1){var n=this._capacity;if(t+r>n){for(var i=r-1;i>=0;i--){this._checkCapacity(t+1);var n=this._capacity,o=(this._front-1&n-1^n)-n;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=r-1;i>=0;i--){var o=(a-1&n-1^n)-n;this[o]=arguments[i],a=o}return this._front=a,this._length=t+r,t+r}if(0===r)return t;this._checkCapacity(t+1);var n=this._capacity,i=(this._front-1&n-1^n)-n;return this[i]=e,this._length=t+1,this._front=i,t+1},n.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},n.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},n.prototype.get=function(e){var t=e;if(t===(0|t)){var r=this._length;if(t<0&&(t+=r),!(t<0||t>=r))return this[this._front+t&this._capacity-1]}},n.prototype.isEmpty=function(){return 0===this._length},n.prototype.clear=function(){for(var e=this._length,t=this._front,r=this._capacity,n=0;nt){var o=r+n&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=n},{}],18:[function(e,t,r){function n(e,t,r){a(this,{type:e,name:e,cause:"string"!=typeof t?t:r,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),n.call(this,"CustomError",e,t)}function o(e,t,r){var o=function(r,i){n.call(this,t,r,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=r?new r:new i,o}var a=e(20);i.prototype=new Error,t.exports=function(e){var t=function(t,r){return o(e,t,r)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{20:20}],19:[function(e,t,r){var n=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},n.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(18)(t.exports),t.exports.create=t.exports.custom.createError},{18:18}],20:[function(e,t,r){!function(e,r,n){"undefined"!=typeof t&&t.exports?t.exports=n():r[e]=n()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,r){return Object.defineProperty(e,t,r),e}:function(e,t,r){return e[t]=r.value,e},t=function(e,t){var r="object"==typeof t,n=!r&&"string"==typeof t,i=function(e){return r?!!t[e]:!!n&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},r=function(r,n,i,o){var a;if(o=t(i,o),"object"==typeof n){for(a in n)Object.hasOwnProperty.call(n,a)&&(o.value=n[a],e(r,a,o));return r}return e(r,n,o)};return r})},{}],21:[function(e,t,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,r,n,o,u,f;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(r=this._events[e],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),r.apply(this,o)}else if(a(r))for(o=Array.prototype.slice.call(arguments,1),f=r.slice(),n=f.length,u=0;u0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var n=!1;return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,t){var r,n,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(s=o;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],i(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],22:[function(e,t,r){"use strict";function n(e,t,r,n,i,o){this._color=e,this.key=t,this.value=r,this.left=n,this.right=i,this._count=o}function i(e){return new n(e._color,e.key,e.value,e.left,e.right,e._count)}function o(e,t){return new n(e,t.key,t.value,t.left,t.right,t._count)}function a(e){e._count=1+(e.left?e.left._count:0)+(e.right?e.right._count:0)}function s(e,t){this._compare=e,this.root=t}function u(e,t){if(t.left){var r=u(e,t.left);if(r)return r}var r=e(t.key,t.value);return r?r:t.right?u(e,t.right):void 0}function f(e,t,r,n){var i=t(e,n.key);if(i<=0){if(n.left){var o=f(e,t,r,n.left);if(o)return o}var o=r(n.key,n.value);if(o)return o}if(n.right)return f(e,t,r,n.right)}function c(e,t,r,n,i){var o,a=r(e,i.key),s=r(t,i.key);if(a<=0){if(i.left&&(o=c(e,t,r,n,i.left)))return o;if(s>0&&(o=n(i.key,i.value)))return o}if(s>0&&i.right)return c(e,t,r,n,i.right)}function l(e,t){this.tree=e,this._stack=t}function h(e,t){e.key=t.key,e.value=t.value,e.left=t.left,e.right=t.right,e._color=t._color,e._count=t._count}function d(e){for(var t,r,n,s,u=e.length-1;u>=0;--u){if(t=e[u],0===u)return void(t._color=y);if(r=e[u-1],r.left===t){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,t._color=y,r._color=y,s._color=y,a(r),a(n),u>1){var f=e[u-2];f.left===r?f.left=n:f.right=n}return void(e[u-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=y,n._color=y,t._color=y,a(r),a(n),a(s),u>1){var f=e[u-2];f.left===r?f.left=s:f.right=s}return void(e[u-1]=s)}if(n._color===y){if(r._color===v)return r._color=y,void(r.right=o(v,n));r.right=o(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,a(r),a(n),u>1){var f=e[u-2];f.left===r?f.left=n:f.right=n}e[u-1]=n,e[u]=r,u+11){var f=e[u-2];f.right===r?f.right=n:f.left=n}return void(e[u-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=y,n._color=y,t._color=y,a(r),a(n),a(s),u>1){var f=e[u-2];f.right===r?f.right=s:f.left=s}return void(e[u-1]=s)}if(n._color===y){if(r._color===v)return r._color=y,void(r.left=o(v,n));r.left=o(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,a(r),a(n),u>1){var f=e[u-2];f.right===r?f.right=n:f.left=n}e[u-1]=n,e[u]=r,u+1t?1:0}function g(e){return new s(e||p,null)}t.exports=g;var v=0,y=1,_=s.prototype;Object.defineProperty(_,"keys",{get:function(){var e=[];return this.forEach(function(t,r){e.push(t)}),e}}),Object.defineProperty(_,"values",{get:function(){var e=[];return this.forEach(function(t,r){e.push(r)}),e}}),Object.defineProperty(_,"length",{get:function(){return this.root?this.root._count:0}}),_.insert=function(e,t){for(var r=this._compare,i=this.root,u=[],f=[];i;){var c=r(e,i.key);u.push(i),f.push(c),i=c<=0?i.left:i.right}u.push(new n(v,e,t,null,null,1));for(var l=u.length-2;l>=0;--l){var i=u[l];f[l]<=0?u[l]=new n(i._color,i.key,i.value,u[l+1],i.right,i._count+1):u[l]=new n(i._color,i.key,i.value,i.left,u[l+1],i._count+1)}for(var l=u.length-1;l>1;--l){var h=u[l-1],i=u[l];if(h._color===y||i._color===y)break;var d=u[l-2];if(d.left===h)if(h.left===i){var p=d.right;if(!p||p._color!==v){if(d._color=v,d.left=h.right,h._color=y,h.right=d,u[l-2]=h,u[l-1]=i,a(d),a(h),l>=3){var g=u[l-3];g.left===d?g.left=h:g.right=h}break}h._color=y,d.right=o(y,p),d._color=v,l-=1}else{var p=d.right;if(!p||p._color!==v){if(h.right=i.left,d._color=v,d.left=i.right,i._color=y,i.left=h,i.right=d,u[l-2]=i,u[l-1]=h,a(d),a(h),a(i),l>=3){var g=u[l-3];g.left===d?g.left=i:g.right=i}break}h._color=y,d.right=o(y,p),d._color=v,l-=1}else if(h.right===i){var p=d.left;if(!p||p._color!==v){if(d._color=v,d.right=h.left,h._color=y,h.left=d,u[l-2]=h,u[l-1]=i,a(d),a(h),l>=3){var g=u[l-3];g.right===d?g.right=h:g.left=h}break}h._color=y,d.left=o(y,p),d._color=v,l-=1}else{var p=d.left;if(!p||p._color!==v){if(h.left=i.right,d._color=v,d.right=i.left,i._color=y,i.right=h,i.left=d,u[l-2]=i,u[l-1]=h,a(d),a(h),a(i),l>=3){var g=u[l-3];g.right===d?g.right=i:g.left=i}break}h._color=y,d.left=o(y,p),d._color=v,l-=1}}return u[0]._color=y,new s(r,u[0])},_.forEach=function(e,t,r){if(this.root)switch(arguments.length){case 1:return u(e,this.root);case 2:return f(t,this._compare,e,this.root);case 3:if(this._compare(t,r)>=0)return;return c(t,r,this._compare,e,this.root)}},Object.defineProperty(_,"begin",{get:function(){for(var e=[],t=this.root;t;)e.push(t),t=t.left;return new l(this,e)}}),Object.defineProperty(_,"end",{get:function(){for(var e=[],t=this.root;t;)e.push(t),t=t.right;return new l(this,e)}}),_.at=function(e){if(e<0)return new l(this,[]);for(var t=this.root,r=[];;){if(r.push(t),t.left){if(e=t.right._count)break;t=t.right}return new l(this,[])},_.ge=function(e){for(var t=this._compare,r=this.root,n=[],i=0;r;){var o=t(e,r.key);n.push(r),o<=0&&(i=n.length),r=o<=0?r.left:r.right}return n.length=i,new l(this,n)},_.gt=function(e){for(var t=this._compare,r=this.root,n=[],i=0;r;){var o=t(e,r.key);n.push(r),o<0&&(i=n.length),r=o<0?r.left:r.right}return n.length=i,new l(this,n)},_.lt=function(e){for(var t=this._compare,r=this.root,n=[],i=0;r;){var o=t(e,r.key);n.push(r),o>0&&(i=n.length),r=o<=0?r.left:r.right}return n.length=i,new l(this,n)},_.le=function(e){for(var t=this._compare,r=this.root,n=[],i=0;r;){var o=t(e,r.key);n.push(r),o>=0&&(i=n.length),r=o<0?r.left:r.right}return n.length=i,new l(this,n)},_.find=function(e){for(var t=this._compare,r=this.root,n=[];r;){var i=t(e,r.key);if(n.push(r),0===i)return new l(this,n);r=i<=0?r.left:r.right}return new l(this,[])},_.remove=function(e){var t=this.find(e);return t?t.remove():this},_.get=function(e){for(var t=this._compare,r=this.root;r;){var n=t(e,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var b=l.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new l(this.tree,this._stack.slice())},b.remove=function(){var e=this._stack;if(0===e.length)return this.tree;var t=new Array(e.length),r=e[e.length-1];t[t.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=e.length-2;i>=0;--i){var r=e[i];r.left===e[i+1]?t[i]=new n(r._color,r.key,r.value,t[i+1],r.right,r._count):t[i]=new n(r._color,r.key,r.value,r.left,t[i+1],r._count)}if(r=t[t.length-1],r.left&&r.right){var o=t.length;for(r=r.left;r.right;)t.push(r),r=r.right;var a=t[o-1];t.push(new n(r._color,a.key,a.value,r.left,r.right,r._count)),t[o-1].key=r.key,t[o-1].value=r.value;for(var i=t.length-2;i>=o;--i)r=t[i],t[i]=new n(r._color,r.key,r.value,r.left,t[i+1],r._count);t[o-1].left=t[o]}if(r=t[t.length-1],r._color===v){var u=t[t.length-2];u.left===r?u.left=null:u.right===r&&(u.right=null),t.pop();for(var i=0;i0)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var e=0,t=this._stack;if(0===t.length){var r=this.tree.root;return r?r._count:0}t[t.length-1].left&&(e=t[t.length-1].left._count);for(var n=t.length-2;n>=0;--n)t[n+1]===t[n].right&&(++e,t[n].left&&(e+=t[n].left._count));return e},enumerable:!0}),b.next=function(){var e=this._stack;if(0!==e.length){var t=e[e.length-1];if(t.right)for(t=t.right;t;)e.push(t),t=t.left;else for(e.pop();e.length>0&&e[e.length-1].right===t;)t=e[e.length-1],e.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var e=this._stack;if(0===e.length)return!1;if(e[e.length-1].right)return!0;for(var t=e.length-1;t>0;--t)if(e[t-1].left===e[t])return!0;return!1}}),b.update=function(e){var t=this._stack;if(0===t.length)throw new Error("Can't update empty node!");var r=new Array(t.length),i=t[t.length-1];r[r.length-1]=new n(i._color,i.key,e,i.left,i.right,i._count);for(var o=t.length-2;o>=0;--o)i=t[o],i.left===t[o+1]?r[o]=new n(i._color,i.key,i.value,r[o+1],i.right,i._count):r[o]=new n(i._color,i.key,i.value,i.left,r[o+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var e=this._stack;if(0!==e.length){var t=e[e.length-1];if(t.left)for(t=t.left;t;)e.push(t),t=t.right;else for(e.pop();e.length>0&&e[e.length-1].left===t;)t=e[e.length-1],e.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var e=this._stack;if(0===e.length)return!1;if(e[e.length-1].left)return!0;for(var t=e.length-1;t>0;--t)if(e[t-1].right===e[t])return!0;return!1}})},{}],23:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,c=-7,l=r?i-1:0,h=r?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-c)-1,d>>=-c,c+=s;c>0;o=256*o+e[t+l],l+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=n;c>0;a=256*a+e[t+l],l+=h,c-=8);if(0===o)o=1-f;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,n),o-=f}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,f=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=c?(s=0,a=c):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,f-=8);e[r+d-p]|=128*g}},{}],24:[function(e,t,r){(function(e){"use strict";function r(){c=!0;for(var e,t,r=l.length;r;){for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[n],e):e[n]}),r},n.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(r,n){return{key:t.decodeKey(r,e),value:t.decodeValue(n,e)}}:e.keys?function(r){return t.decodeKey(r,e)}:e.values?function(r,n){return t.decodeValue(n,e)}:function(){}},n.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},n.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{30:30}],30:[function(e,t,r){(function(e){function t(e){return e}function n(t){return void 0===t||null===t||e.isBuffer(t)}r.utf8=r["utf-8"]={encode:function(e){return n(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},r.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},r.binary={encode:function(t){return n(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},r.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},r.id=r.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){r[t]={encode:function(r){return n(r)?r:new e(r,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(5).Buffer)},{5:5}],31:[function(e,t,r){var n=e(19).create,i=n("LevelUPError"),o=n("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:n("InitializationError",i),OpenError:n("OpenError",i),ReadError:n("ReadError",i),WriteError:n("WriteError",i),NotFoundError:o,EncodingError:n("EncodingError",i)}},{19:19}],32:[function(e,t,r){function n(e,t){return this instanceof n?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new n(e,t)}var i=e(25),o=e(61).Readable,a=e(33),s=e(31).EncodingError; -t.exports=n,i(n,o),n.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,r,n){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===r&&void 0===n)e.push(null);else{if(!e._decoder)return e.push({key:r,value:n});try{var n=e._decoder(r,n)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(n)}}})},n.prototype.destroy=n.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{25:25,31:31,33:33,61:61}],33:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{16:16}],34:[function(e,t,r){function n(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(36),o=e(31).WriteError,a=i.getOptions,s=i.dispatchError;n.prototype.put=function(e,t,r){r=a(r);var n=this._codec.encodeKey(e,r),i=this._codec.encodeValue(t,r);try{this.batch.put(n,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:n,value:i}),this.length++,this},n.prototype.del=function(e,t){t=a(t);var r=this._codec.encodeKey(e,t);try{this.batch.del(r)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:r}),this.length++,this},n.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},n.prototype.write=function(e){var t=this._levelup,r=this.ops;try{this.batch.write(function(n){return n?s(t,new o(n),e):(t.emit("batch",r),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=n},{31:31,36:36}],35:[function(e,t,r){(function(r){function n(e,t){return"function"==typeof e?e:t}function i(e,t,n){if(!(this instanceof i))return new i(e,t,n);var o;if(f.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{},t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e,e=null),"function"==typeof t&&(n=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),n)return r.nextTick(function(){n(o)});throw o}t=B(t),this.options=h(R,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(n)}function o(e,t,r){if(!e._isOpening()&&!e.isOpen())return j(e,new _("Database is not open"),r),!0}function a(e,t,r){j(e,new y(t),r)}function s(e,t,r){j(e,new _(t),r)}function u(e){return function(t,r){A()[e](t,r||function(){})}}var f=e(21).EventEmitter,c=e(85).inherits,l=e(85).deprecate,h=e(39),d=e(54),p=e(10),g=e(32),v=e(31),y=v.WriteError,_=v.ReadError,b=v.NotFoundError,m=v.OpenError,w=v.EncodingError,E=v.InitializationError,k=e(36),S=e(34),x=e(37),B=k.getOptions,R=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;c(i,f),i.prototype.open=function(e){var t,n,i=this;return this.isOpen()?(e&&r.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),n=t(this.location),void n.open(this.options,function(t){return t?j(i,new m(t),e):(i.db.setDb(n),i.db=n,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return r.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,r){var i,a=this;if(r=n(t,r),!o(this,t,r)){if(null===e||void 0===e||"function"!=typeof r)return s(this,"get() requires key and callback arguments",r);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(n,i){if(n)return n=/notfound/i.test(n)||n.notFound?new b("Key not found in database ["+e+"]",n):new _(n),j(a,n,r);if(r){try{i=a._codec.decodeValue(i,t)}catch(e){return r(new w(e))}r(null,i)}})}},i.prototype.put=function(e,t,r,i){var s,u,f=this;return i=n(r,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,r,i)||(r=B(r),s=this._codec.encodeKey(e,r),u=this._codec.encodeValue(t,r),this.db.put(s,u,r,function(r){return r?j(f,new y(r),i):(f.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,r){var i,s=this;return r=n(t,r),null===e||void 0===e?a(this,"del() requires a key argument",r):void(o(this,t,r)||(t=B(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new y(t),r):(s.emit("del",e),void(r&&r()))})))},i.prototype.batch=function(e,t,r){var i,s=this;return arguments.length?(r=n(t,r),Array.isArray(e)?void(o(this,t,r)||(t=B(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new y(t),r):(s.emit("batch",e),void(r&&r()))}))):a(this,"batch() requires an array argument",r)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,r,i){var o,a,u=this;return i=n(r,i),r=B(r),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,r),a=this._codec.encodeKey(t,r),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new m(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(31),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(53))},{10:10,21:21,31:31,32:32,34:34,36:36,37:37,39:39,53:53,54:54,85:85}],36:[function(e,t,r){function n(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,r=e(40).devDependencies.leveldown;try{t=e(3).version}catch(e){throw o(e)}if(!e(3).satisfies(t,r))throw new f("Installed version of LevelDOWN ("+t+") does not match required version ("+r+")");try{return u=e(3)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new f(c(t,e.message))}function a(e,t,r){"function"==typeof r?r(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,f=(e(39),e(31).LevelUPError),c=e(85).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:n,getLevelDOWN:i,dispatchError:a,isDefined:s}},{3:3,31:31,39:39,40:40,85:85}],37:[function(e,t,r){arguments[4][29][0].apply(r,arguments)},{29:29,38:38}],38:[function(e,t,r){(function(e){function t(e){return e}function n(t){return void 0===t||null===t||e.isBuffer(t)}r.utf8=r["utf-8"]={encode:function(e){return n(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},r.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},r.binary={encode:function(t){return n(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},r.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){r[t]={encode:function(r){return n(r)?r:new e(r,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(5).Buffer)},{5:5}],39:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{16:16}],40:[function(e,t,r){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],41:[function(e,t,r){"use strict";function n(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=_,this.queue=[],this.outcome=void 0,e!==n&&u(this,e)}function o(e,t,r){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof r&&(this.onRejected=r,this.callRejected=this.otherCallRejected)}function a(e,t,r){p(function(){var n;try{n=t(r)}catch(t){return g.reject(e,t)}n===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,n)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function r(t){o||(o=!0,g.reject(e,t))}function n(t){o||(o=!0,g.resolve(e,t))}function i(){t(n,r)}var o=!1,a=f(i);"error"===a.status&&r(a.value)}function f(e,t){var r={};try{r.value=e(t),r.status="success"}catch(e){r.status="error",r.value=e}return r}function c(e){return e instanceof this?e:g.resolve(new this(n),e)}function l(e){var t=new this(n);return g.reject(t,e)}function h(e){function t(e,t){function n(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(f,a))}r.resolve(e).then(n,function(e){o||(o=!0,g.reject(f,e))})}var r=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,f=new this(n);++ur?1:0};var a=r.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=r.lowerBound=function(e){var t=a(e);return t&&e[t]};r.lowerBoundInclusive=function(e){return!t(e,"gt")},r.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=r.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},f=r.upperBoundExclusive=function(e){return!!t(e,"lt")},c=r.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=r.upperBound=function(e){var t=c(e);return t&&e[t]};r.toLtgt=function(e,n,i,a,s){n=n||{},i=i||o;var u=arguments.length>3,f=r.lowerBoundKey(e),c=r.upperBoundKey(e);return f?"gt"===f?n.gt=i(e.gt,!1):n.gte=i(e[f],!1):u&&(n.gte=i(a,!1)),c?"lt"===c?n.lt=i(e.lt,!0):n.lte=i(e[c],!0):u&&(n.lte=i(s,!0)),null!=e.reverse&&(n.reverse=!!e.reverse),t(n,"max")&&delete n.max,t(n,"min")&&delete n.min,t(n,"start")&&delete n.start,t(n,"end")&&delete n.end,n},r.contains=function(e,t,i){i=i||r.compare;var o=s(e);if(n(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var c=l(e);if(n(c)){var a=i(t,c);if(a>0||0===a&&f(e))return!1}return!0},r.filter=function(e,t){return function(n){return r.contains(e,n,t)}}}).call(this,{isBuffer:e(26)})},{26:26}],43:[function(e,t,r){(function(r,n,i){function o(e){return"string"==typeof e?"$"+e:JSON.stringify(e)}function a(e){return g.compare(e,this._end)>0}function s(e){return g.compare(e,this._end)>=0}function u(e){return g.compare(e,this._end)<0}function f(e){return g.compare(e,this._end)<=0}function c(e,t){p.call(this,e),this._limit=t.limit,this._limit===-1&&(this._limit=1/0);var r=e._store[e._location];this.keyAsBuffer=t.keyAsBuffer!==!1,this.valueAsBuffer=t.valueAsBuffer!==!1,this._reverse=t.reverse,this._options=t,this._done=0,this._reverse?(this._incr="prev",this._start=g.upperBound(t),this._end=g.lowerBound(t),"undefined"==typeof this._start?this._tree=r.end:g.upperBoundInclusive(t)?this._tree=r.le(this._start):this._tree=r.lt(this._start),this._end&&(g.lowerBoundInclusive(t)?this._test=s:this._test=a)):(this._incr="next",this._start=g.lowerBound(t),this._end=g.upperBound(t),"undefined"==typeof this._start?this._tree=r.begin:g.lowerBoundInclusive(t)?this._tree=r.ge(this._start):this._tree=r.gt(this._start),this._end&&(g.upperBoundInclusive(t)?this._test=f:this._test=u))}function l(e){return this instanceof l?(d.call(this,"string"==typeof e?e:""),this._location=this.location?o(this.location):"_tree",this._store=this.location?_:this,void(this._store[this._location]=this._store[this._location]||y(g.compare))):new l(e)}var h=e(25),d=e(47).AbstractLevelDOWN,p=e(47).AbstractIterator,g=e(49),v=n.setImmediate||r.nextTick,y=e(22),_={};h(c,p),c.prototype._next=function(e){var t,r;return this._done++>=this._limit?v(e):this._tree.valid?(t=this._tree.key,r=this._tree.value,this._test(t)?(this.keyAsBuffer&&(t=new i(t)),this.valueAsBuffer&&(r=new i(r)),this._tree[this._incr](),void v(function(){e(null,t,r)})):v(e)):v(e)},c.prototype._test=function(){return!0},l.clearGlobalStore=function(e){e?Object.keys(_).forEach(function(e){delete _[e]}):_={}},h(l,d),l.prototype._open=function(e,t){var r=this;v(function(){t(null,r)})},l.prototype._put=function(e,t,r,n){"undefined"!=typeof t&&null!==t||(t="");var i=this._store[this._location].find(e);i.valid?this._store[this._location]=i.update(t):this._store[this._location]=this._store[this._location].insert(e,t),v(n)},l.prototype._get=function(e,t,r){var n=this._store[this._location].get(e);if(void 0===n){var o=new Error("NotFound");return v(function(){r(o)})}t.asBuffer===!1||this._isBuffer(n)||(n=new i(String(n))),v(function(){r(null,n)})},l.prototype._del=function(e,t,r){this._store[this._location]=this._store[this._location].remove(e),v(r)},l.prototype._batch=function(e,t,r){for(var n,i,o,a,s=-1,u=e.length,f=this._store[this._location];++sr?1:0};var n=r.lowerBound=function(e){return t(e.gt)?e.gt:t(e.gte)?e.gte:t(e.min)?e.min:t(e.start)&&!e.reverse?e.start:t(e.end)&&e.reverse?e.end:void 0};r.lowerBoundInclusive=function(e){return!t(e.gt)},r.upperBoundInclusive=function(e){return!t(e.lt)};var i=r.lowerBoundExclusive=function(e){return!!t(e.gt)},o=r.upperBoundExclusive=function(e){return!!t(e.lt)},a=r.upperBound=function(e){return t(e.lt)?e.lt:t(e.lte)?e.lte:t(e.max)?e.max:t(e.start)&&e.reverse?e.start:t(e.end)&&!e.reverse?e.end:void 0};r.contains=function(e,s,u){u=u||r.compare;var f=n(e);if(t(f)){var c=u(s,f);if(c<0||0===c&&i(e))return!1}var l=a(e);if(t(l)){var c=u(s,l);if(c>0||0===c&&o(e))return!1}return!0},r.filter=function(e,t){return function(n){return r.contains(e,n,t)}}}).call(this,{isBuffer:e(26)})},{26:26}],50:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{16:16}],51:[function(e,t,r){function n(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*l;case"days":case"day":case"d":return r*c;case"hours":case"hour":case"hrs":case"hr":case"h":return r*f;case"minutes":case"minute":case"mins":case"min":case"m":return r*u;case"seconds":case"second":case"secs":case"sec":case"s":return r*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=f?Math.round(e/f)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,c,"day")||a(e,f,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,r){if(!(e1)for(var r=1;r0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event"); -e.emit("error",s)}else!t.decoder||i||n||(r=t.decoder.write(r)),t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):(t.reading=!1,t.buffer.push(r)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var r=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function c(e,t){if(t.decoder&&!t.ended){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.length>0?l(e):m(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?r.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(function(){p(e,t)}))}function p(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===n.pipesCount?(n.flowing=!1,void(x.listenerCount(e,"data")>0&&_(e))):void(n.ranOut=!0)}function y(){this._readableState.ranOut&&(this._readableState.ranOut=!1,v(this))}function _(e,t){var n=e._readableState;if(n.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=B.prototype.pipe,e.on=e.addListener=B.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?r.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function b(e,t){var r,n=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===n.length)return null;if(0===i)r=null;else if(a)r=n.shift();else if(!e||e>=i)r=o?n.join(""):S.concat(n,i),n.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,r.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var r=0,n=e.length;r0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return r=null,t.length>0&&t.decoder&&(r=b(e,t),t.length-=r.length),0===t.length&&m(this),r;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(n,t)),r=e>0?b(e,t):null,null===r&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&m(this),r},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function n(e){e===c&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",n),c.removeListener("end",i),c.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){f(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),f()}function u(){e.removeListener("close",s),f()}function f(){c.unpipe(e)}var c=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e];break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==r.stdout&&e!==r.stderr,d=h?i:o;l.endEmitted?r.nextTick(d):c.once("end",d),e.on("unpipe",n);var p=g(c);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s),e.once("finish",u),e.emit("pipe",c),l.flowing||(this.on("readable",y),l.flowing=!0,r.nextTick(function(){v(c)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",y),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",y),t.flowing=!1;for(var i=0;i>>32-i,r)}function r(e,r,n,i,o,a,s){return t(r&n|~r&i,e,r,o,a,s)}function n(e,r,n,i,o,a,s){return t(r&i|n&~i,e,r,o,a,s)}function i(e,r,n,i,o,a,s){return t(r^n^i,e,r,o,a,s)}function o(e,r,n,i,o,a,s){return t(n^(r|~i),e,r,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],f=e[3];a=r(a,s,u,f,t[0],7,-680876936),f=r(f,a,s,u,t[1],12,-389564586),u=r(u,f,a,s,t[2],17,606105819),s=r(s,u,f,a,t[3],22,-1044525330),a=r(a,s,u,f,t[4],7,-176418897),f=r(f,a,s,u,t[5],12,1200080426),u=r(u,f,a,s,t[6],17,-1473231341),s=r(s,u,f,a,t[7],22,-45705983),a=r(a,s,u,f,t[8],7,1770035416),f=r(f,a,s,u,t[9],12,-1958414417),u=r(u,f,a,s,t[10],17,-42063),s=r(s,u,f,a,t[11],22,-1990404162),a=r(a,s,u,f,t[12],7,1804603682),f=r(f,a,s,u,t[13],12,-40341101),u=r(u,f,a,s,t[14],17,-1502002290),s=r(s,u,f,a,t[15],22,1236535329),a=n(a,s,u,f,t[1],5,-165796510),f=n(f,a,s,u,t[6],9,-1069501632),u=n(u,f,a,s,t[11],14,643717713),s=n(s,u,f,a,t[0],20,-373897302),a=n(a,s,u,f,t[5],5,-701558691),f=n(f,a,s,u,t[10],9,38016083),u=n(u,f,a,s,t[15],14,-660478335),s=n(s,u,f,a,t[4],20,-405537848),a=n(a,s,u,f,t[9],5,568446438),f=n(f,a,s,u,t[14],9,-1019803690),u=n(u,f,a,s,t[3],14,-187363961),s=n(s,u,f,a,t[8],20,1163531501),a=n(a,s,u,f,t[13],5,-1444681467),f=n(f,a,s,u,t[2],9,-51403784),u=n(u,f,a,s,t[7],14,1735328473),s=n(s,u,f,a,t[12],20,-1926607734),a=i(a,s,u,f,t[5],4,-378558),f=i(f,a,s,u,t[8],11,-2022574463),u=i(u,f,a,s,t[11],16,1839030562),s=i(s,u,f,a,t[14],23,-35309556),a=i(a,s,u,f,t[1],4,-1530992060),f=i(f,a,s,u,t[4],11,1272893353),u=i(u,f,a,s,t[7],16,-155497632),s=i(s,u,f,a,t[10],23,-1094730640),a=i(a,s,u,f,t[13],4,681279174),f=i(f,a,s,u,t[0],11,-358537222),u=i(u,f,a,s,t[3],16,-722521979),s=i(s,u,f,a,t[6],23,76029189),a=i(a,s,u,f,t[9],4,-640364487),f=i(f,a,s,u,t[12],11,-421815835),u=i(u,f,a,s,t[15],16,530742520),s=i(s,u,f,a,t[2],23,-995338651),a=o(a,s,u,f,t[0],6,-198630844),f=o(f,a,s,u,t[7],10,1126891415),u=o(u,f,a,s,t[14],15,-1416354905),s=o(s,u,f,a,t[5],21,-57434055),a=o(a,s,u,f,t[12],6,1700485571),f=o(f,a,s,u,t[3],10,-1894986606),u=o(u,f,a,s,t[10],15,-1051523),s=o(s,u,f,a,t[1],21,-2054922799),a=o(a,s,u,f,t[8],6,1873313359),f=o(f,a,s,u,t[15],10,-30611744),u=o(u,f,a,s,t[6],15,-1560198380),s=o(s,u,f,a,t[13],21,1309151649),a=o(a,s,u,f,t[4],6,-145523070),f=o(f,a,s,u,t[11],10,-1120210379),u=o(u,f,a,s,t[2],15,718787259),s=o(s,u,f,a,t[9],21,-343485551),e[0]=b(a,e[0]),e[1]=b(s,e[1]),e[2]=b(u,e[2]),e[3]=b(f,e[3])}function s(e){var t,r=[];for(t=0;t<64;t+=4)r[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return r}function u(e){var t,r=[];for(t=0;t<64;t+=4)r[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return r}function f(e){var t,r,n,i,o,u,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,s(e.substring(t-64,t)));for(e=e.substring(t-64),r=e.length,n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(n[t>>2]|=128<<(t%4<<3),t>55)for(a(c,n),t=0;t<16;t+=1)n[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,n[14]=o,n[15]=u,a(c,n),c}function c(e){var t,r,n,i,o,s,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(n[t>>2]|=128<<(t%4<<3),t>55)for(a(c,n),t=0;t<16;t+=1)n[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,n[14]=o,n[15]=s,a(c,n),c}function l(e){var t,r="";for(t=0;t<4;t+=1)r+=m[e>>8*t+4&15]+m[e>>8*t&15];return r}function h(e){var t;for(t=0;t>16)+(t>>16)+(r>>16);return n<<16|65535&r}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(r,n){var i,o,a,s,u=this.byteLength,f=t(r,u),c=u;return n!==e&&(c=t(n,u)),f>c?new ArrayBuffer(0):(i=c-f,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,f,i),a.set(s),o)}}(),_.prototype.append=function(e){return this.appendBinary(d(e)),this},_.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,r=this._buff.length;for(t=64;t<=r;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},_.prototype.end=function(e){var t,r,n=this._buff,i=n.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=n.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),r=h(this._hash),e&&(r=y(r)),this.reset(),r},_.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},_.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},_.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},_.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},_.prototype._finish=function(e,t){var r,n,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;r=8*this._length,r=r.toString(16).match(/(.*?)(.{0,8})$/),n=parseInt(r[2],16),i=parseInt(r[1],16)||0,e[14]=n,e[15]=i,a(this._hash,e)},_.hash=function(e,t){return _.hashBinary(d(e),t)},_.hashBinary=function(e,t){var r=f(e),n=h(r);return t?y(n):n},_.ArrayBuffer=function(){this.reset()},_.ArrayBuffer.prototype.append=function(e){var t,r=v(this._buff.buffer,e,!0),n=r.length;for(this._length+=e.byteLength,t=64;t<=n;t+=64)a(this._hash,u(r.subarray(t-64,t)));return this._buff=t-64>2]|=n[t]<<(t%4<<3);return this._finish(o,i),r=h(this._hash),e&&(r=y(r)),this.reset(),r},_.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},_.ArrayBuffer.prototype.getState=function(){var e=_.prototype.getState.call(this);return e.buff=g(e.buff),e},_.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),_.prototype.setState.call(this,e)},_.ArrayBuffer.prototype.destroy=_.prototype.destroy,_.ArrayBuffer.prototype._finish=_.prototype._finish,_.ArrayBuffer.hash=function(e,t){var r=c(new Uint8Array(e)),n=h(r);return t?y(n):n},_})},{}],63:[function(e,t,r){function n(){i.call(this)}t.exports=n;var i=e(21).EventEmitter,o=e(25);o(n,i),n.Readable=e(72),n.Writable=e(74),n.Duplex=e(64),n.Transform=e(73),n.PassThrough=e(71),n.Stream=n,n.prototype.pipe=function(e,t){function r(t){e.writable&&!1===e.write(t)&&f.pause&&f.pause()}function n(){f.readable&&f.resume&&f.resume()}function o(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){f.removeListener("data",r),e.removeListener("drain",n),f.removeListener("end",o),f.removeListener("close",a),f.removeListener("error",s),e.removeListener("error",s),f.removeListener("end",u),f.removeListener("close",u),e.removeListener("close",u)}var f=this;f.on("data",r),e.on("drain",n),e._isStdio||t&&t.end===!1||(f.on("end",o),f.on("close",a));var c=!1;return f.on("error",s),e.on("error",s),f.on("end",u),f.on("close",u),e.on("close",u),e.emit("pipe",f),e}},{21:21,25:25,64:64,71:71,72:72,73:73,74:74}],64:[function(e,t,r){t.exports=e(65)},{65:65}],65:[function(e,t,r){"use strict";function n(e){return this instanceof n?(f.call(this,e),c.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new n(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=n;var s=e(52),u=e(6);u.inherits=e(25);var f=e(67),c=e(69);u.inherits(n,f);for(var l=a(c.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var f;!t.decoder||i||n||(r=t.decoder.write(r),f=!t.objectMode&&0===r.length),i||(t.reading=!1),f||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function c(e,t){var r=null;return L.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function l(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(P("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){P("emit readable"),e.emit("readable"),m(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=E(e,t.buffer,t.decoder),r}function E(e,t,r){var n;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}function S(e,t){var r=C.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),e-=a,0===e){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(B,t,e))}function B(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function R(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return P("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var n=t.needReadable;P("need readable",n),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){P("onunpipe"),e===h&&a()}function o(){P("onend"),e.end()}function a(){P("cleanup"),e.removeListener("close",f),e.removeListener("finish",c),e.removeListener("drain",y),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),_=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function s(t){P("ondata"),b=!1;var r=e.write(t);!1!==r||b||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!_&&(P("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,b=!0),h.pause())}function u(t){P("onerror",t),l(),e.removeListener("error",u),0===T(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",c),l()}function c(){P("onfinish"),e.removeListener("close",f),l()}function l(){P("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,P("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==r.stdout&&e!==r.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var y=v(h);e.on("drain",y);var _=!1,b=!1;return h.on("data",s),n(e,"error",u),e.once("close",f),e.once("finish",c),e.emit("pipe",h),d.flowing||(P("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(6);x.inherits=e(25);var B,R={deprecate:e(83)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(21).EventEmitter)}}();var A=e(5).Buffer,j=e(4);x.inherits(a,B);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:R.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,r){var i=this._writableState,o=!1;return"function"==typeof t&&(r=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=n),i.ended?s(this,r):u(this,i,e,r)&&(i.pendingcb++,o=c(this,i,e,t,r)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,r){r(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||w(this,n,r)}}).call(this,e(53))},{21:21,25:25,4:4,5:5,52:52,53:53,6:6,65:65,83:83}],70:[function(e,t,r){"use strict";function n(){this.head=null,this.tail=null,this.length=0}var i=(e(5).Buffer,e(4));t.exports=n,n.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},n.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},n.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},n.prototype.clear=function(){this.head=this.tail=null,this.length=0},n.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},n.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t}},{4:4,5:5}],71:[function(e,t,r){t.exports=e(66)},{66:66}],72:[function(e,t,r){(function(n){var i=function(){try{return e("stream")}catch(e){}}();r=t.exports=e(67),r.Stream=i||r,r.Readable=r,r.Writable=e(69),r.Duplex=e(65),r.Transform=e(68),r.PassThrough=e(66),!n.browser&&"disable"===n.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(53))},{53:53,65:65,66:66,67:67,68:68,69:69}],73:[function(e,t,r){t.exports=e(68)},{68:68}],74:[function(e,t,r){t.exports=e(69)},{69:69}],75:[function(e,t,r){function n(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(5).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},f=r.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),n(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};f.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&n<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,n=t.charCodeAt(i);if(n>=55296&&n<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},f.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},f.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t}},{5:5}],76:[function(e,t,r){arguments[4][65][0].apply(r,arguments)},{25:25,52:52,6:6,65:65,77:77,79:79}],77:[function(e,t,r){(function(r){"use strict";function n(t,r){C=C||e(76),t=t||{},this.objectMode=!!t.objectMode,r instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var n=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=n||0===n?n:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(L||(L=e(75).StringDecoder),this.decoder=new L(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(76),this instanceof i?(this._readableState=new n(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,r,n,i){var o=f(t,r);if(o)e.emit("error",o);else if(null===r)t.reading=!1,c(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||n||(r=t.decoder.write(r),u=!t.objectMode&&0===r.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=D?e=D:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var r=null;return R.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function c(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(T("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){T("emit readable"),e.emit("readable"),b(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)r=o?n.join(""):1===n.length?n[0]:R.concat(n,i),n.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var r=0,n=e.length;r0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return T("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var n=t.needReadable;T("need readable",n),(0===t.length||t.length-e0?m(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),r!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function n(e){T("onunpipe"),e===l&&o()}function i(){T("onend"),e.end()}function o(){T("cleanup"),e.removeListener("close",u),e.removeListener("finish",f),e.removeListener("drain",v),e.removeListener("error",s),e.removeListener("unpipe",n),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),y=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function a(t){T("ondata");var r=e.write(t);!1===r&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||y||(T("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){T("onerror",t),c(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",f),c()}function f(){T("onfinish"),e.removeListener("close",u),c()}function c(){T("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,T("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==r.stdout&&e!==r.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",n);var v=g(l);e.on("drain",v);var y=!1;return l.on("data",a),e._events&&e._events.error?B(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",f),e.emit("pipe",l),h.flowing||(T("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(5).Buffer;a.WritableState=o;var B=e(6);B.inherits=e(25);var R,A={deprecate:e(83)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(21).EventEmitter)}}();var x=e(5).Buffer;B.inherits(a,R);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,r){var i=this._writableState,o=!1;return"function"==typeof t&&(r=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=n),i.ended?s(this,r):u(this,i,e,r)&&(i.pendingcb++,o=c(this,i,e,t,r)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,r){r(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||w(this,n,r)}}).call(this,e(53))},{21:21,25:25,5:5,52:52,53:53,6:6,76:76,83:83}],80:[function(e,t,r){arguments[4][73][0].apply(r,arguments)},{73:73,78:78}],81:[function(e,t,r){arguments[4][16][0].apply(r,arguments)},{16:16}],82:[function(e,t,r){(function(r){function n(e){a.call(this,e),this._destroyed=!1}function i(e,t,r){r(null,e)}function o(e){return function(t,r,n){return"function"==typeof t&&(n=r,r=t,t={}),"function"!=typeof r&&(r=i),"function"!=typeof n&&(n=null),e(t,r,n)}}var a=e(80),s=e(85).inherits,u=e(81);s(n,a),n.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;r.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,r){var i=new n(e);return i._transform=t,r&&(i._flush=r),i}),t.exports.ctor=o(function(e,t,r){function i(t){return this instanceof i?(this.options=u(e,t),void n.call(this,this.options)):new i(t)}return s(i,n),i.prototype._transform=t,r&&(i.prototype._flush=r),i}),t.exports.obj=o(function(e,t,r){var i=new n(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,r&&(i._flush=r),i})}).call(this,e(53))},{53:53,80:80,81:81,85:85}],83:[function(e,t,r){(function(e){function r(e,t){function r(){if(!i){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(n("noDeprecation"))return e;var i=!1;return r}function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],84:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],85:[function(e,t,r){(function(t,n){function i(e,t){var n={seen:[],stylize:a};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&r._extend(n,t),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),u(n,e,n.depth)}function o(e,t){var r=i.styles[t];return r?"["+i.colors[r][0]+"m"+e+"["+i.colors[r][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}function u(e,t,n){if(e.customInspect&&t&&B(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return b(i)||(i=u(e,i,n)),i}var o=f(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(B(t)){var v=t.name?": "+t.name:"";return e.stylize("[Function"+v+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return c(t)}var y="",_=!1,m=["{","}"];if(p(t)&&(_=!0,m=["[","]"]),B(t)){var w=t.name?": "+t.name:"";y=" [Function"+w+"]"}if(E(t)&&(y=" "+RegExp.prototype.toString.call(t)),S(t)&&(y=" "+Date.prototype.toUTCString.call(t)),x(t)&&(y=" "+c(t)),0===a.length&&(!_||0==t.length))return m[0]+y+m[1];if(n<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=_?l(e,t,n,g,a):a.map(function(r){return h(e,t,n,g,r,_)}),e.seen.pop(),d(k,y,m)}function f(e,t){if(w(t))return e.stylize("undefined","undefined");if(b(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string"); -}return _(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,r){var n=0,i=e.reduce(function(e,t){return n++,t.indexOf("\n")>=0&&n++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function v(e){return null===e}function y(e){return null==e}function _(e){return"number"==typeof e}function b(e){return"string"==typeof e}function m(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function B(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var T=/%[sdj%]/g;r.format=function(e){if(!b(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),s=n[r];r=0;a--)s=0===a?"":",",t.push({obj:n[a],prefix:s});t.push({val:"["})}else{u=[];for(f in n)n.hasOwnProperty(f)&&u.push(f);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)c=u[a],l=n[c],h=a>0?",":"",h+=JSON.stringify(c)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},r.parse=function(e){for(var t,r,i,o,a,s,u,f,c,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,n(null,l,h);break;case"t":d+=3,n(!0,l,h);break;case"f":d+=4,n(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(r="",d--;;){if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}r+=i}n(parseFloat(r),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}n(JSON.parse('"'+o+'"'),l,h);break;case"[":f={element:[],index:l.length},l.push(f.element),h.push(f);break;case"{":c={element:{},index:l.length},l.push(c.element),h.push(c);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();n(l.pop(),l,h)}}},{}],87:[function(e,t,r){(function(t,r,n){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function o(e){return"function"==typeof e}function a(e){return o(e.prefix)?e.prefix():e}function s(e){var t={};for(var r in e)t[r]=e[r];return t}function u(e,t,r){function n(e,n,i,o){return t.encode([e,r.encodeKey(n,i,o)])}function i(e,t){return t&&t.options&&(e.keyEncoding=e.keyEncoding||t.options.keyEncoding,e.valueEncoding=e.valueEncoding||t.options.valueEncoding),e}return e.open(function(){}),{apply:function(t,o,s){o=o||{};for(var u=[],f=-1,c=t.length;++f>>1,r(e[n],t)<0?i=n+1:o=n;return i}function H(e,t,r){var n=V(e,t,r);e.splice(n,0,t)}function $(e,t){for(var r,n,i=t,o=e.length;i0;){var i=r.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var v=g.ids[2],y=0,_=v.length;y<_;y++)p.push({ids:v[y],diff:g.diff-1,parent:g.ids,parentIdx:y});else g.ids[0]===l.ids[0]&&d.push(g)}var b=d[0];b?(n=X(b.ids,l.ids),b.parent[2][b.parentIdx]=n.tree,i.push({pos:c.pos,ids:c.ids}),o=o||n.conflicts,a=!0):i.push(f)}else i.push(f)}return a||i.push(t),i.sort(J),{tree:i,conflicts:o||"internal_node"}}function Q(e,t){for(var r,n=Y(e),i={},o=0,a=n.length;o0||n0||ni.end)return t(null,{total_rows:n,offset:e.skip,rows:[]});var u=[],f=E.docStore.readStream(i),c=We.obj(function(t,r,n){function i(t){var r={id:a.id,key:a.id,value:{rev:c}};if(e.include_docs){r.doc=t,r.doc._rev=r.value.rev,e.conflicts&&(r.doc._conflicts=z(a));for(var i in r.doc._attachments)r.doc._attachments.hasOwnProperty(i)&&(r.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return n();if(l){if("ok"!==e.deleted)return n();r.value.deleted=!0,r.doc=null}u.push(r),n()}var a=t.value,c=Re(a),l=Ae(a,c);if(l){if("ok"!==e.deleted)return void n()}else{if(o-- >0)return void n();if("number"==typeof s&&s--<=0)return f.unpipe(),f.destroy(),void n()}if(e.include_docs){var h=a.rev_map[c];E.bySeqStore.get(d(h),function(e,t){i(t)})}else i()},function(r){at.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,E,e)}).then(function(){t(null,{total_rows:n,offset:e.skip,rows:u})},t),r()}).on("unpipe",function(){c.end()});f.on("error",t),f.pipe(c)})}),w._changes=function(e){function t(){e.done=!0,f&&e.limit&&e.limit0&&(n=e.limit),u.reverse||(u.start=d(e.since||0));var f,c=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;f="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var y=E.bySeqStore.readStream(u),_=We.obj(function(r,u,p){function g(t){function r(r){var n=e.processChange(r,t,e);n.seq=t.seq;var i=l(n);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([n],E,e).then(function(){e.onChange(n)}):e.onChange(n),f&&o.push(n)),void p())}var n=Re(t);if(t.seq!==y)return p();if(a=y,n===_._rev)return r(_);var i=t.rev_map[n];E.bySeqStore.get(d(i),function(e,t){r(t)})}if(n&&s>=n)return t(),p();if(e.cancelled||e.done)return p();var y=v(r.key),_=r.value;if(y===e.since&&!i)return p();if(c&&!c.has(_._id))return p();var m;return(m=h.get(_._id))?g(m):void E.docStore.get(_._id,function(t,r){return e.cancelled||e.done||b.isClosed()||ie(r.id)?p():(h.set(_._id,r),void g(r))})},function(t){return e.cancelled?t():(f&&e.limit&&e.limitn.since&&!n.cancelled&&(n.since=e.seq,n.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(qe.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Ne(R,Error),R.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var ft,ct=(new R({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new R({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new R({status:404,error:"not_found",reason:"missing"})),lt=new R({status:409,error:"conflict",reason:"Document update conflict"}),ht=new R({status:400,error:"bad_request",reason:"_id field must contain a string"}),dt=new R({status:412,error:"missing_id",reason:"_id is required for puts"}),pt=new R({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),gt=new R({status:412,error:"precondition_failed",reason:"Database not open"}),vt=(new R({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new R({status:500,error:"badarg",reason:"Some query argument is invalid"})),yt=(new R({status:400,error:"invalid_request",reason:"Request was invalid"}),new R({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new R({status:500,error:"doc_validation",reason:"Bad special document member"})),_t=new R({status:400,error:"bad_request",reason:"Something wrong with the request"}),bt=(new R({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new R({status:404,error:"not_found",reason:"Database not found"}),new R({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new R({status:500,error:"web_sql_went_bad",reason:"unknown"}),new R({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new R({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new R({status:400,error:"bad_request",reason:"Invalid rev format"})),mt=(new R({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new R({status:412,error:"missing_stub"})),wt=(new R({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),M.name);ft=wt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var Et=ft,kt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),St=D(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),xt=D(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),Bt=function(e){return atob(e)},Rt=function(e){return btoa(e)},At=r.setImmediate||r.setTimeout,jt=32768;Be.prototype.get=function(e,r,n){var i=xe(this,e),o=i.get(r);return o?t.nextTick(function(){n(null,o)}):null===o?t.nextTick(function(){n({name:"NotFoundError"})}):void e.get(r,function(e,t){return e?("NotFoundError"===e.name&&i.set(r,null),n(e)):(i.set(r,t),void n(null,t))})},Be.prototype.batch=function(e){for(var t=0,r=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;r.has(a)||(r.add(a),n.push(o))}e.batch(n,t)};var Ot="document-store",Mt="by-sequence",Tt="attach-store",Lt="attach-binary-store",Ct="local-store",Dt="meta-store",qt=new p,Pt="_local_last_update_seq",Nt="_local_doc_count",It="_local_uuid",Ut="md5-",Wt={encode:we,decode:me,buffer:!1,type:"cheap-json"},Ft=new x;Te.valid=function(){return!0},Te.use_prefix=!1;var zt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");zt?Le(zt):B("error",'memory adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(5).Buffer)},{1:1,17:17,21:21,25:25,28:28,29:29,35:35,41:41,42:42,43:43,5:5,53:53,61:61,62:62,7:7,82:82,86:86,pouchdb:"pouchdb"}]},{},[87]); +!function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-r(e)}function o(e){var t,n,i,o,a,s,u=e.length;a=r(e),s=new l(3*u/4-a),i=a>0?u-4:u;var f=0;for(t=0,n=0;t>16&255,s[f++]=o>>8&255,s[f++]=255&o;return 2===a?(o=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,s[f++]=255&o):1===a&&(o=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,s[f++]=o>>8&255,s[f++]=255&o),s}function a(e){return f[e>>18&63]+f[e>>12&63]+f[e>>6&63]+f[63&e]}function s(e,t,n){for(var r,i=[],o=t;oc?c:u+a));return 1===r?(t=e[n-1],i+=f[t>>2],i+=f[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=f[t>>10],i+=f[t>>4&63],i+=f[t<<2&63],i+="="),o.push(i),o.join("")}n.byteLength=i,n.toByteArray=o,n.fromByteArray=u;for(var f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;da)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),f=u.length,c=-1;++ca)throw new RangeError("size is too large");return new i(e)},n.from=function(e,n,r){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,n,r);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,n);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(e);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=e.byteLength-o),o>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(e.slice(o,o+a))}if(i.isBuffer(e)){var s=new i(e.length);return e.copy(s,0,0,e.length),s}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},n.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{5:5}],5:[function(e,t,n){(function(t){"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function v(e){return+e!=e&&(e=0),a.alloc(+e)}function y(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return K(e).length;t=(""+t).toLowerCase(),r=!0}}function _(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return L(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function m(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:w(e,t,n,r,i);if("number"==typeof t)return t=255&t,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var f;if(i){var c=-1;for(f=n;fs&&(n=s-u),f=n;f>=0;f--){for(var l=!0,h=0;hi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,f,c,l;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(l=(31&o)<<6|63&u,l>127&&(a=l));break;case 3:u=e[i+1],f=e[i+2],128===(192&u)&&128===(192&f)&&(l=(15&o)<<12|(63&u)<<6|63&f,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:u=e[i+1],f=e[i+2],c=e[i+3],128===(192&u)&&128===(192&f)&&128===(192&c)&&(l=(15&o)<<18|(63&u)<<12|(63&f)<<6|63&c,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return O(r)}function O(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function q(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function I(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,i){return i||I(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function W(e,t,n,r,i){return i||I(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function F(e){if(e=z(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function K(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function J(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function H(e){return X.toByteArray(F(e))}function $(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var X=e(2),Z=e(23),Q=e(27);n.Buffer=a,n.SlowBuffer=v,n.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return f(null,e,t,n)},a.allocUnsafe=function(e){return c(null,e)},a.allocUnsafeSlow=function(e){return c(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),f=this.slice(r,i),c=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return R(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e=0|e,t=0|t,n||D(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t=0|t,n=0|n,!r){var i=Math.pow(2,8*n)-1;P(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):q(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):q(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);P(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t=0|t,!r){var i=Math.pow(2,8*n-1);P(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):q(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t=0|t,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):q(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return W(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return W(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o=31}function i(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function s(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(8),n.log=o,n.formatArgs=i,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{8:8}],8:[function(e,t,n){function r(){return n.colors[c++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(f||t);e.diff=o,e.prev=f,e.curr=t,f=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var i=n.formatters[r];if("function"==typeof i){var o=a[s];t=i.call(e,o),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=i.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function a(e){if("number"!=typeof e){if(!s(e))return 16;e=e.length}return o(Math.min(Math.max(16,e),1073741824))}r.prototype.toArray=function(){for(var e=this._length,t=new Array(e),n=this._front,r=this._capacity,i=0;i1){var r=this._capacity;if(n+t>r){for(var i=0;i1){var r=this._capacity;if(t+n>r){for(var i=n-1;i>=0;i--){this._checkCapacity(t+1);var r=this._capacity,o=(this._front-1&r-1^r)-r;this[o]=arguments[i],t++,this._length=t,this._front=o}return t}for(var a=this._front,i=n-1;i>=0;i--){var o=(a-1&r-1^r)-r;this[o]=arguments[i],a=o}return this._front=a,this._length=t+n,t+n}if(0===n)return t;this._checkCapacity(t+1);var r=this._capacity,i=(this._front-1&r-1^r)-r;return this[i]=e,this._length=t+1,this._front=i,t+1},r.prototype.peekBack=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1;return this[t]}},r.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},r.prototype.get=function(e){var t=e;if(t===(0|t)){var n=this._length;if(t<0&&(t+=n),!(t<0||t>=n))return this[this._front+t&this._capacity-1]}},r.prototype.isEmpty=function(){return 0===this._length},r.prototype.clear=function(){for(var e=this._length,t=this._front,n=this._capacity,r=0;rt){var o=n+r&t-1;i(this,0,this,t,o)}};var s=Array.isArray;t.exports=r},{}],18:[function(e,t,n){function r(e,t,n){a(this,{type:e,name:e,cause:"string"!=typeof t?t:n,message:t&&"string"!=typeof t?t.message:t},"ewr")}function i(e,t){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),r.call(this,"CustomError",e,t)}function o(e,t,n){var o=function(n,i){r.call(this,t,n,i),"FilesystemError"==t&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(e.errno[this.cause.errno]?e.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return o.prototype=n?new n:new i,o}var a=e(20);i.prototype=new Error,t.exports=function(e){var t=function(t,n){return o(e,t,n)};return{CustomError:i,FilesystemError:t("FilesystemError"),createError:t}}},{20:20}],19:[function(e,t,n){var r=t.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];t.exports.errno={},t.exports.code={},r.forEach(function(e){t.exports.errno[e.errno]=e,t.exports.code[e.code]=e}),t.exports.custom=e(18)(t.exports),t.exports.create=t.exports.custom.createError},{18:18}],20:[function(e,t,n){!function(e,n,r){"undefined"!=typeof t&&t.exports?t.exports=r():n[e]=r()}("prr",this,function(){var e="function"==typeof Object.defineProperty?function(e,t,n){return Object.defineProperty(e,t,n),e}:function(e,t,n){return e[t]=n.value,e},t=function(e,t){var n="object"==typeof t,r=!n&&"string"==typeof t,i=function(e){return n?!!t[e]:!!r&&t.indexOf(e[0])>-1};return{enumerable:i("enumerable"),configurable:i("configurable"),writable:i("writable"),value:e}},n=function(n,r,i,o){var a;if(o=t(i,o),"object"==typeof r){for(a in r)Object.hasOwnProperty.call(r,a)&&(o.value=r[a],e(n,a,o));return n}return e(n,r,o)};return n})},{}],21:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,f;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),f=n.slice(),r=f.length,u=0;u0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],22:[function(e,t,n){"use strict";function r(e,t,n,r,i,o){this._color=e,this.key=t,this.value=n,this.left=r,this.right=i,this._count=o}function i(e){return new r(e._color,e.key,e.value,e.left,e.right,e._count)}function o(e,t){return new r(e,t.key,t.value,t.left,t.right,t._count)}function a(e){e._count=1+(e.left?e.left._count:0)+(e.right?e.right._count:0)}function s(e,t){this._compare=e,this.root=t}function u(e,t){if(t.left){var n=u(e,t.left);if(n)return n}var n=e(t.key,t.value);return n?n:t.right?u(e,t.right):void 0}function f(e,t,n,r){var i=t(e,r.key);if(i<=0){if(r.left){var o=f(e,t,n,r.left);if(o)return o}var o=n(r.key,r.value);if(o)return o}if(r.right)return f(e,t,n,r.right)}function c(e,t,n,r,i){var o,a=n(e,i.key),s=n(t,i.key);if(a<=0){if(i.left&&(o=c(e,t,n,r,i.left)))return o;if(s>0&&(o=r(i.key,i.value)))return o}if(s>0&&i.right)return c(e,t,n,r,i.right)}function l(e,t){this.tree=e,this._stack=t}function h(e,t){e.key=t.key,e.value=t.value,e.left=t.left,e.right=t.right,e._color=t._color,e._count=t._count}function d(e){for(var t,n,r,s,u=e.length-1;u>=0;--u){if(t=e[u],0===u)return void(t._color=y);if(n=e[u-1],n.left===t){if(r=n.right,r.right&&r.right._color===v){if(r=n.right=i(r),s=r.right=i(r.right),n.right=r.left,r.left=n,r.right=s,r._color=n._color,t._color=y,n._color=y,s._color=y,a(n),a(r),u>1){var f=e[u-2];f.left===n?f.left=r:f.right=r}return void(e[u-1]=r)}if(r.left&&r.left._color===v){if(r=n.right=i(r),s=r.left=i(r.left),n.right=s.left,r.left=s.right,s.left=n,s.right=r,s._color=n._color,n._color=y,r._color=y,t._color=y,a(n),a(r),a(s),u>1){var f=e[u-2];f.left===n?f.left=s:f.right=s}return void(e[u-1]=s)}if(r._color===y){if(n._color===v)return n._color=y,void(n.right=o(v,r));n.right=o(v,r);continue}if(r=i(r),n.right=r.left,r.left=n,r._color=n._color,n._color=v,a(n),a(r),u>1){var f=e[u-2];f.left===n?f.left=r:f.right=r}e[u-1]=r,e[u]=n,u+11){var f=e[u-2];f.right===n?f.right=r:f.left=r}return void(e[u-1]=r)}if(r.right&&r.right._color===v){if(r=n.left=i(r),s=r.right=i(r.right),n.left=s.right,r.right=s.left,s.right=n,s.left=r,s._color=n._color,n._color=y,r._color=y,t._color=y,a(n),a(r),a(s),u>1){var f=e[u-2];f.right===n?f.right=s:f.left=s}return void(e[u-1]=s)}if(r._color===y){if(n._color===v)return n._color=y,void(n.left=o(v,r));n.left=o(v,r);continue}if(r=i(r),n.left=r.right,r.right=n,r._color=n._color,n._color=v,a(n),a(r),u>1){var f=e[u-2];f.right===n?f.right=r:f.left=r}e[u-1]=r,e[u]=n,u+1t?1:0}function g(e){return new s(e||p,null)}t.exports=g;var v=0,y=1,_=s.prototype;Object.defineProperty(_,"keys",{get:function(){var e=[];return this.forEach(function(t,n){e.push(t)}),e}}),Object.defineProperty(_,"values",{get:function(){var e=[];return this.forEach(function(t,n){e.push(n)}),e}}),Object.defineProperty(_,"length",{get:function(){return this.root?this.root._count:0}}),_.insert=function(e,t){for(var n=this._compare,i=this.root,u=[],f=[];i;){var c=n(e,i.key);u.push(i),f.push(c),i=c<=0?i.left:i.right}u.push(new r(v,e,t,null,null,1));for(var l=u.length-2;l>=0;--l){var i=u[l];f[l]<=0?u[l]=new r(i._color,i.key,i.value,u[l+1],i.right,i._count+1):u[l]=new r(i._color,i.key,i.value,i.left,u[l+1],i._count+1)}for(var l=u.length-1;l>1;--l){var h=u[l-1],i=u[l];if(h._color===y||i._color===y)break;var d=u[l-2];if(d.left===h)if(h.left===i){var p=d.right;if(!p||p._color!==v){if(d._color=v,d.left=h.right,h._color=y,h.right=d,u[l-2]=h,u[l-1]=i,a(d),a(h),l>=3){var g=u[l-3];g.left===d?g.left=h:g.right=h}break}h._color=y,d.right=o(y,p),d._color=v,l-=1}else{var p=d.right;if(!p||p._color!==v){if(h.right=i.left,d._color=v,d.left=i.right,i._color=y,i.left=h,i.right=d,u[l-2]=i,u[l-1]=h,a(d),a(h),a(i),l>=3){var g=u[l-3];g.left===d?g.left=i:g.right=i}break}h._color=y,d.right=o(y,p),d._color=v,l-=1}else if(h.right===i){var p=d.left;if(!p||p._color!==v){if(d._color=v,d.right=h.left,h._color=y,h.left=d,u[l-2]=h,u[l-1]=i,a(d),a(h),l>=3){var g=u[l-3];g.right===d?g.right=h:g.left=h}break}h._color=y,d.left=o(y,p),d._color=v,l-=1}else{var p=d.left;if(!p||p._color!==v){if(h.left=i.right,d._color=v,d.right=i.left,i._color=y,i.right=h,i.left=d,u[l-2]=i,u[l-1]=h,a(d),a(h),a(i),l>=3){var g=u[l-3];g.right===d?g.right=i:g.left=i}break}h._color=y,d.left=o(y,p),d._color=v,l-=1}}return u[0]._color=y,new s(n,u[0])},_.forEach=function(e,t,n){if(this.root)switch(arguments.length){case 1:return u(e,this.root);case 2:return f(t,this._compare,e,this.root);case 3:if(this._compare(t,n)>=0)return;return c(t,n,this._compare,e,this.root)}},Object.defineProperty(_,"begin",{get:function(){for(var e=[],t=this.root;t;)e.push(t),t=t.left;return new l(this,e)}}),Object.defineProperty(_,"end",{get:function(){for(var e=[],t=this.root;t;)e.push(t),t=t.right;return new l(this,e)}}),_.at=function(e){if(e<0)return new l(this,[]);for(var t=this.root,n=[];;){if(n.push(t),t.left){if(e=t.right._count)break;t=t.right}return new l(this,[])},_.ge=function(e){for(var t=this._compare,n=this.root,r=[],i=0;n;){var o=t(e,n.key);r.push(n),o<=0&&(i=r.length),n=o<=0?n.left:n.right}return r.length=i,new l(this,r)},_.gt=function(e){for(var t=this._compare,n=this.root,r=[],i=0;n;){var o=t(e,n.key);r.push(n),o<0&&(i=r.length),n=o<0?n.left:n.right}return r.length=i,new l(this,r)},_.lt=function(e){for(var t=this._compare,n=this.root,r=[],i=0;n;){var o=t(e,n.key);r.push(n),o>0&&(i=r.length),n=o<=0?n.left:n.right}return r.length=i,new l(this,r)},_.le=function(e){for(var t=this._compare,n=this.root,r=[],i=0;n;){var o=t(e,n.key);r.push(n),o>=0&&(i=r.length),n=o<0?n.left:n.right}return r.length=i,new l(this,r)},_.find=function(e){for(var t=this._compare,n=this.root,r=[];n;){var i=t(e,n.key);if(r.push(n),0===i)return new l(this,r);n=i<=0?n.left:n.right}return new l(this,[])},_.remove=function(e){var t=this.find(e);return t?t.remove():this},_.get=function(e){for(var t=this._compare,n=this.root;n;){var r=t(e,n.key);if(0===r)return n.value;n=r<=0?n.left:n.right}};var m=l.prototype;Object.defineProperty(m,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(m,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),m.clone=function(){return new l(this.tree,this._stack.slice())},m.remove=function(){var e=this._stack;if(0===e.length)return this.tree;var t=new Array(e.length),n=e[e.length-1];t[t.length-1]=new r(n._color,n.key,n.value,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i){var n=e[i];n.left===e[i+1]?t[i]=new r(n._color,n.key,n.value,t[i+1],n.right,n._count):t[i]=new r(n._color,n.key,n.value,n.left,t[i+1],n._count)}if(n=t[t.length-1],n.left&&n.right){var o=t.length;for(n=n.left;n.right;)t.push(n),n=n.right;var a=t[o-1];t.push(new r(n._color,a.key,a.value,n.left,n.right,n._count)),t[o-1].key=n.key,t[o-1].value=n.value;for(var i=t.length-2;i>=o;--i)n=t[i],t[i]=new r(n._color,n.key,n.value,n.left,t[i+1],n._count);t[o-1].left=t[o]}if(n=t[t.length-1],n._color===v){var u=t[t.length-2];u.left===n?u.left=null:u.right===n&&(u.right=null),t.pop();for(var i=0;i0)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(m,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(m,"index",{get:function(){var e=0,t=this._stack;if(0===t.length){var n=this.tree.root;return n?n._count:0}t[t.length-1].left&&(e=t[t.length-1].left._count);for(var r=t.length-2;r>=0;--r)t[r+1]===t[r].right&&(++e,t[r].left&&(e+=t[r].left._count));return e},enumerable:!0}),m.next=function(){var e=this._stack;if(0!==e.length){var t=e[e.length-1];if(t.right)for(t=t.right;t;)e.push(t),t=t.left;else for(e.pop();e.length>0&&e[e.length-1].right===t;)t=e[e.length-1],e.pop()}},Object.defineProperty(m,"hasNext",{get:function(){var e=this._stack;if(0===e.length)return!1;if(e[e.length-1].right)return!0;for(var t=e.length-1;t>0;--t)if(e[t-1].left===e[t])return!0;return!1}}),m.update=function(e){var t=this._stack;if(0===t.length)throw new Error("Can't update empty node!");var n=new Array(t.length),i=t[t.length-1];n[n.length-1]=new r(i._color,i.key,e,i.left,i.right,i._count);for(var o=t.length-2;o>=0;--o)i=t[o],i.left===t[o+1]?n[o]=new r(i._color,i.key,i.value,n[o+1],i.right,i._count):n[o]=new r(i._color,i.key,i.value,i.left,n[o+1],i._count);return new s(this.tree._compare,n[0])},m.prev=function(){var e=this._stack;if(0!==e.length){var t=e[e.length-1];if(t.left)for(t=t.left;t;)e.push(t),t=t.right;else for(e.pop();e.length>0&&e[e.length-1].left===t;)t=e[e.length-1],e.pop()}},Object.defineProperty(m,"hasPrev",{get:function(){var e=this._stack;if(0===e.length)return!1;if(e[e.length-1].left)return!0;for(var t=e.length-1;t>0;--t)if(e[t-1].right===e[t])return!0;return!1}})},{}],23:[function(e,t,n){n.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,u=(1<>1,c=-7,l=n?i-1:0,h=n?-1:1,d=e[t+l];for(l+=h,o=d&(1<<-c)-1,d>>=-c,c+=s;c>0;o=256*o+e[t+l],l+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=r;c>0;a=256*a+e[t+l],l+=h,c-=8);if(0===o)o=1-f;else{if(o===u)return a?NaN:(d?-1:1)*(1/0);a+=Math.pow(2,r),o-=f}return(d?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,i,o){var a,s,u,f=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+l>=1?h/u:h*Math.pow(2,1-l),t*u>=2&&(a++,u/=2),a+l>=c?(s=0,a=c):a+l>=1?(s=(t*u-1)*Math.pow(2,i),a+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,f-=8);e[n+d-p]|=128*g}},{}],24:[function(e,t,n){(function(e){"use strict";function n(){c=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e-1?t.encodeKey(e[r],e):e[r]}),n},r.prototype.createStreamDecoder=function(e){var t=this;return e.keys&&e.values?function(n,r){return{key:t.decodeKey(n,e),value:t.decodeValue(r,e)}}:e.keys?function(n){return t.decodeKey(n,e)}:e.values?function(n,r){return t.decodeValue(r,e)}:function(){}},r.prototype.keyAsBuffer=function(e){return this._keyEncoding(e).buffer},r.prototype.valueAsBuffer=function(e){return this._valueEncoding(e).buffer}},{30:30}],30:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.none={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"},n.id=n.none;var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(5).Buffer)},{5:5}],31:[function(e,t,n){var r=e(19).create,i=r("LevelUPError"),o=r("NotFoundError",i);o.prototype.notFound=!0,o.prototype.status=404,t.exports={LevelUPError:i,InitializationError:r("InitializationError",i),OpenError:r("OpenError",i),ReadError:r("ReadError",i),WriteError:r("WriteError",i),NotFoundError:o,EncodingError:r("EncodingError",i)}},{19:19}],32:[function(e,t,n){function r(e,t){return this instanceof r?(o.call(this,a(t,{objectMode:!0})),this._iterator=e,this._destroyed=!1,this._decoder=null,t&&t.decoder&&(this._decoder=t.decoder),void this.on("end",this._cleanup.bind(this))):new r(e,t)}var i=e(25),o=e(61).Readable,a=e(33),s=e(31).EncodingError; +t.exports=r,i(r,o),r.prototype._read=function(){var e=this;this._destroyed||this._iterator.next(function(t,n,r){if(!e._destroyed){if(t)return e.emit("error",t);if(void 0===n&&void 0===r)e.push(null);else{if(!e._decoder)return e.push({key:n,value:r});try{var r=e._decoder(n,r)}catch(t){return e.emit("error",new s(t)),void e.push(null)}e.push(r)}}})},r.prototype.destroy=r.prototype._cleanup=function(){var e=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(t){return t?e.emit("error",t):void e.emit("close")}))}},{25:25,31:31,33:33,61:61}],33:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{16:16}],34:[function(e,t,n){function r(e,t){this._levelup=e,this._codec=t,this.batch=e.db.batch(),this.ops=[],this.length=0}var i=e(36),o=e(31).WriteError,a=i.getOptions,s=i.dispatchError;r.prototype.put=function(e,t,n){n=a(n);var r=this._codec.encodeKey(e,n),i=this._codec.encodeValue(t,n);try{this.batch.put(r,i)}catch(e){throw new o(e)}return this.ops.push({type:"put",key:r,value:i}),this.length++,this},r.prototype.del=function(e,t){t=a(t);var n=this._codec.encodeKey(e,t);try{this.batch.del(n)}catch(e){throw new o(e)}return this.ops.push({type:"del",key:n}),this.length++,this},r.prototype.clear=function(){try{this.batch.clear()}catch(e){throw new o(e)}return this.ops=[],this.length=0,this},r.prototype.write=function(e){var t=this._levelup,n=this.ops;try{this.batch.write(function(r){return r?s(t,new o(r),e):(t.emit("batch",n),void(e&&e()))})}catch(e){throw new o(e)}},t.exports=r},{31:31,36:36}],35:[function(e,t,n){(function(n){function r(e,t){return"function"==typeof e?e:t}function i(e,t,r){if(!(this instanceof i))return new i(e,t,r);var o;if(f.call(this),this.setMaxListeners(1/0),"function"==typeof e?(t="object"==typeof t?t:{},t.db=e,e=null):"object"==typeof e&&"function"==typeof e.db&&(t=e,e=null),"function"==typeof t&&(r=t,t={}),(!t||"function"!=typeof t.db)&&"string"!=typeof e){if(o=new E("Must provide a location for the database"),r)return n.nextTick(function(){r(o)});throw o}t=R(t),this.options=h(B,t),this._codec=new x(this.options),this._status="new",d(this,"location",e,"e"),this.open(r)}function o(e,t,n){if(!e._isOpening()&&!e.isOpen())return j(e,new _("Database is not open"),n),!0}function a(e,t,n){j(e,new y(t),n)}function s(e,t,n){j(e,new _(t),n)}function u(e){return function(t,n){A()[e](t,n||function(){})}}var f=e(21).EventEmitter,c=e(86).inherits,l=e(86).deprecate,h=e(39),d=e(54),p=e(10),g=e(32),v=e(31),y=v.WriteError,_=v.ReadError,m=v.NotFoundError,b=v.OpenError,w=v.EncodingError,E=v.InitializationError,k=e(36),S=e(34),x=e(37),R=k.getOptions,B=k.defaultOptions,A=k.getLevelDOWN,j=k.dispatchError;k.isDefined;c(i,f),i.prototype.open=function(e){var t,r,i=this;return this.isOpen()?(e&&n.nextTick(function(){e(null,i)}),this):this._isOpening()?e&&this.once("open",function(){e(null,i)}):(this.emit("opening"),this._status="opening",this.db=new p(this.location),t=this.options.db||A(),r=t(this.location),void r.open(this.options,function(t){return t?j(i,new b(t),e):(i.db.setDb(r),i.db=r,i._status="open",e&&e(null,i),i.emit("open"),i.emit("ready"),void 0)}))},i.prototype.close=function(e){var t=this;if(this.isOpen())this._status="closing",this.db.close(function(){t._status="closed",t.emit("closed"),e&&e.apply(null,arguments)}),this.emit("closing"),this.db=new p(this.location);else{if("closed"==this._status&&e)return n.nextTick(e);"closing"==this._status&&e?this.once("closed",e):this._isOpening()&&this.once("open",function(){t.close(e)})}},i.prototype.isOpen=function(){return"open"==this._status},i.prototype._isOpening=function(){return"opening"==this._status},i.prototype.isClosed=function(){return/^clos/.test(this._status)},i.prototype.get=function(e,t,n){var i,a=this;if(n=r(t,n),!o(this,t,n)){if(null===e||void 0===e||"function"!=typeof n)return s(this,"get() requires key and callback arguments",n);t=k.getOptions(t),i=this._codec.encodeKey(e,t),t.asBuffer=this._codec.valueAsBuffer(t),this.db.get(i,t,function(r,i){if(r)return r=/notfound/i.test(r)||r.notFound?new m("Key not found in database ["+e+"]",r):new _(r),j(a,r,n);if(n){try{i=a._codec.decodeValue(i,t)}catch(e){return n(new w(e))}n(null,i)}})}},i.prototype.put=function(e,t,n,i){var s,u,f=this;return i=r(n,i),null===e||void 0===e?a(this,"put() requires a key argument",i):void(o(this,n,i)||(n=R(n),s=this._codec.encodeKey(e,n),u=this._codec.encodeValue(t,n),this.db.put(s,u,n,function(n){return n?j(f,new y(n),i):(f.emit("put",e,t),void(i&&i()))})))},i.prototype.del=function(e,t,n){var i,s=this;return n=r(t,n),null===e||void 0===e?a(this,"del() requires a key argument",n):void(o(this,t,n)||(t=R(t),i=this._codec.encodeKey(e,t),this.db.del(i,t,function(t){return t?j(s,new y(t),n):(s.emit("del",e),void(n&&n()))})))},i.prototype.batch=function(e,t,n){var i,s=this;return arguments.length?(n=r(t,n),Array.isArray(e)?void(o(this,t,n)||(t=R(t),i=s._codec.encodeBatch(e,t),i=i.map(function(e){return e.type||void 0===e.key||void 0===e.value||(e.type="put"),e}),this.db.batch(i,t,function(t){return t?j(s,new y(t),n):(s.emit("batch",e),void(n&&n()))}))):a(this,"batch() requires an array argument",n)):new S(this,this._codec)},i.prototype.approximateSize=l(function(e,t,n,i){var o,a,u=this;return i=r(n,i),n=R(n),null===e||void 0===e||null===t||void 0===t||"function"!=typeof i?s(this,"approximateSize() requires start, end and callback arguments",i):(o=this._codec.encodeKey(e,n),a=this._codec.encodeKey(t,n),void this.db.approximateSize(o,a,function(e,t){return e?j(u,new b(e),i):void(i&&i(null,t))}))},"db.approximateSize() is deprecated. Use db.db.approximateSize() instead"),i.prototype.readStream=i.prototype.createReadStream=function(e){return e=h({keys:!0,values:!0},this.options,e),e.keyEncoding=e.keyEncoding,e.valueEncoding=e.valueEncoding,e=this._codec.encodeLtgt(e),e.keyAsBuffer=this._codec.keyAsBuffer(e),e.valueAsBuffer=this._codec.valueAsBuffer(e),"number"!=typeof e.limit&&(e.limit=-1),new g(this.db.iterator(e),h(e,{decoder:this._codec.createStreamDecoder(e)}))},i.prototype.keyStream=i.prototype.createKeyStream=function(e){return this.createReadStream(h(e,{keys:!0,values:!1}))},i.prototype.valueStream=i.prototype.createValueStream=function(e){return this.createReadStream(h(e,{keys:!1,values:!0}))},i.prototype.toString=function(){return"LevelUP"},t.exports=i,t.exports.errors=e(31),t.exports.destroy=l(u("destroy"),"levelup.destroy() is deprecated. Use leveldown.destroy() instead"),t.exports.repair=l(u("repair"),"levelup.repair() is deprecated. Use leveldown.repair() instead")}).call(this,e(53))},{10:10,21:21,31:31,32:32,34:34,36:36,37:37,39:39,53:53,54:54,86:86}],36:[function(e,t,n){function r(e){return"string"==typeof e&&(e={valueEncoding:e}),"object"!=typeof e&&(e={}),e}function i(){if(u)return u;var t,n=e(40).devDependencies.leveldown;try{t=e(3).version}catch(e){throw o(e)}if(!e(3).satisfies(t,n))throw new f("Installed version of LevelDOWN ("+t+") does not match required version ("+n+")");try{return u=e(3)}catch(e){throw o(e)}}function o(e){var t="Failed to require LevelDOWN (%s). Try `npm install leveldown` if it's missing";return new f(c(t,e.message))}function a(e,t,n){"function"==typeof n?n(t):e.emit("error",t)}function s(e){return"undefined"!=typeof e}var u,f=(e(39),e(31).LevelUPError),c=e(86).format,l={createIfMissing:!0,errorIfExists:!1,keyEncoding:"utf8",valueEncoding:"utf8",compression:!0};t.exports={defaultOptions:l,getOptions:r,getLevelDOWN:i,dispatchError:a,isDefined:s}},{3:3,31:31,39:39,40:40,86:86}],37:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{29:29,38:38}],38:[function(e,t,n){(function(e){function t(e){return e}function r(t){return void 0===t||null===t||e.isBuffer(t)}n.utf8=n["utf-8"]={encode:function(e){return r(e)?e:String(e)},decode:t,buffer:!1,type:"utf8"},n.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},n.binary={encode:function(t){return r(t)?t:new e(t)},decode:t,buffer:!0,type:"binary"},n.id={encode:function(e){return e},decode:function(e){return e},buffer:!1,type:"id"};var i=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];i.forEach(function(t){n[t]={encode:function(n){return r(n)?n:new e(n,t)},decode:function(e){return e.toString(t)},buffer:!0,type:t}})}).call(this,e(5).Buffer)},{5:5}],39:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{16:16}],40:[function(e,t,n){t.exports={_args:[[{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},"/Users/nolan/workspace/pouchdb"]],_from:"levelup@1.3.2",_id:"levelup@1.3.2",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"6.1.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.2.tgz_1463496525467_0.4644940535072237"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"3.8.6",_phantomChildren:{},_requested:{raw:"levelup@1.3.2",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"1.3.2",spec:"1.3.2",type:"version"},_requiredBy:["/","/pouchdb","/pouchdb-adapter-leveldb-core"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz",_shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",_shrinkwrap:null,_spec:"levelup@1.3.2",_where:"/Users/nolan/workspace/pouchdb",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"b321d3071f0e75c2dfaf2f0fe8864e5b9a387bc9",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.2.tgz"},gitHead:"bcc242cfc4ec035f9228a5cd54903cb126659a00",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.2"}},{}],41:[function(e,t,n){"use strict";function r(){}function i(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=_,this.queue=[],this.outcome=void 0,e!==r&&u(this,e)}function o(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function a(e,t,n){p(function(){var r;try{r=t(n)}catch(t){return g.reject(e,t)}r===e?g.reject(e,new TypeError("Cannot resolve promise with itself")):g.resolve(e,r)})}function s(e){var t=e&&e.then;if(e&&"object"==typeof e&&"function"==typeof t)return function(){t.apply(e,arguments)}}function u(e,t){function n(t){o||(o=!0,g.reject(e,t))}function r(t){o||(o=!0,g.resolve(e,t))}function i(){t(r,n)}var o=!1,a=f(i);"error"===a.status&&n(a.value)}function f(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}function c(e){return e instanceof this?e:g.resolve(new this(r),e)}function l(e){var t=new this(r);return g.reject(t,e)}function h(e){function t(e,t){function r(e){a[t]=e,++s!==i||o||(o=!0,g.resolve(f,a))}n.resolve(e).then(r,function(e){o||(o=!0,g.reject(f,e))})}var n=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,o=!1;if(!i)return this.resolve([]);for(var a=new Array(i),s=0,u=-1,f=new this(r);++un?1:0};var a=n.lowerBoundKey=function(e){return i(e,"gt")||i(e,"gte")||i(e,"min")||(e.reverse?i(e,"end"):i(e,"start"))||void 0},s=n.lowerBound=function(e){var t=a(e);return t&&e[t]};n.lowerBoundInclusive=function(e){return!t(e,"gt")},n.upperBoundInclusive=function(e){return!(t(e,"lt")||!e.minEx)};var u=n.lowerBoundExclusive=function(e){return!(!t(e,"gt")&&!e.minEx)},f=n.upperBoundExclusive=function(e){return!!t(e,"lt")},c=n.upperBoundKey=function(e){return i(e,"lt")||i(e,"lte")||i(e,"max")||(e.reverse?i(e,"start"):i(e,"end"))||void 0},l=n.upperBound=function(e){var t=c(e);return t&&e[t]};n.toLtgt=function(e,r,i,a,s){r=r||{},i=i||o;var u=arguments.length>3,f=n.lowerBoundKey(e),c=n.upperBoundKey(e);return f?"gt"===f?r.gt=i(e.gt,!1):r.gte=i(e[f],!1):u&&(r.gte=i(a,!1)),c?"lt"===c?r.lt=i(e.lt,!0):r.lte=i(e[c],!0):u&&(r.lte=i(s,!0)),null!=e.reverse&&(r.reverse=!!e.reverse),t(r,"max")&&delete r.max,t(r,"min")&&delete r.min,t(r,"start")&&delete r.start,t(r,"end")&&delete r.end,r},n.contains=function(e,t,i){i=i||n.compare;var o=s(e);if(r(o)){var a=i(t,o);if(a<0||0===a&&u(e))return!1}var c=l(e);if(r(c)){var a=i(t,c);if(a>0||0===a&&f(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(26)})},{26:26}],43:[function(e,t,n){(function(n,r,i){function o(e){return p.compare(e,this._end)>0}function a(e){return p.compare(e,this._end)>=0}function s(e){return p.compare(e,this._end)<0}function u(e){return p.compare(e,this._end)<=0}function f(e,t){d.call(this,e),this._limit=t.limit,this._limit===-1&&(this._limit=1/0);var n=e._store[e._location];this.keyAsBuffer=t.keyAsBuffer!==!1,this.valueAsBuffer=t.valueAsBuffer!==!1,this._reverse=t.reverse,this._options=t,this._done=0,this._reverse?(this._incr="prev",this._start=p.upperBound(t),this._end=p.lowerBound(t),"undefined"==typeof this._start?this._tree=n.end:p.upperBoundInclusive(t)?this._tree=n.le(this._start):this._tree=n.lt(this._start),this._end&&(p.lowerBoundInclusive(t)?this._test=a:this._test=o)):(this._incr="next",this._start=p.lowerBound(t),this._end=p.upperBound(t),"undefined"==typeof this._start?this._tree=n.begin:p.lowerBoundInclusive(t)?this._tree=n.ge(this._start):this._tree=n.gt(this._start),this._end&&(p.upperBoundInclusive(t)?this._test=u:this._test=s))}function c(e){return this instanceof c?(h.call(this,"string"==typeof e?e:""),this._location=this.location?"$"+this.location:"_tree",this._store=this.location?v:this,void(this._store[this._location]=this._store[this._location]||g(p.compare))):new c(e)}var l=e(25),h=e(47).AbstractLevelDOWN,d=e(47).AbstractIterator,p=e(49),g=e(22),v={},y=r.setImmediate||n.nextTick;l(f,d),f.prototype._next=function(e){var t,n;return this._done++>=this._limit?y(e):this._tree.valid?(t=this._tree.key,n=this._tree.value,this._test(t)?(this.keyAsBuffer&&(t=new i(t)),this.valueAsBuffer&&(n=new i(n)),this._tree[this._incr](),void y(function(){e(null,t,n)})):y(e)):y(e)},f.prototype._test=function(){return!0},c.clearGlobalStore=function(e){e?Object.keys(v).forEach(function(e){delete v[e]}):v={}},l(c,h),c.prototype._open=function(e,t){var n=this;y(function(){t(null,n)})},c.prototype._put=function(e,t,n,r){"undefined"!=typeof t&&null!==t||(t="");var i=this._store[this._location].find(e);i.valid?this._store[this._location]=i.update(t):this._store[this._location]=this._store[this._location].insert(e,t),y(r)},c.prototype._get=function(e,t,n){var r=this._store[this._location].get(e);return"undefined"==typeof r?y(function(){n(new Error("NotFound"))}):(t.asBuffer===!1||this._isBuffer(r)||(r=new i(String(r))),void y(function(){n(null,r)}))},c.prototype._del=function(e,t,n){this._store[this._location]=this._store[this._location].remove(e),y(n)},c.prototype._batch=function(e,t,n){for(var r,i,o,a=-1,s=e.length,u=this._store[this._location];++an?1:0};var r=n.lowerBound=function(e){return t(e.gt)?e.gt:t(e.gte)?e.gte:t(e.min)?e.min:t(e.start)&&!e.reverse?e.start:t(e.end)&&e.reverse?e.end:void 0};n.lowerBoundInclusive=function(e){return!t(e.gt)},n.upperBoundInclusive=function(e){return!t(e.lt)};var i=n.lowerBoundExclusive=function(e){return!!t(e.gt)},o=n.upperBoundExclusive=function(e){return!!t(e.lt)},a=n.upperBound=function(e){return t(e.lt)?e.lt:t(e.lte)?e.lte:t(e.max)?e.max:t(e.start)&&e.reverse?e.start:t(e.end)&&!e.reverse?e.end:void 0};n.contains=function(e,s,u){u=u||n.compare;var f=r(e);if(t(f)){var c=u(s,f);if(c<0||0===c&&i(e))return!1}var l=a(e);if(t(l)){var c=u(s,l);if(c>0||0===c&&o(e))return!1}return!0},n.filter=function(e,t){return function(r){return n.contains(e,r,t)}}}).call(this,{isBuffer:e(26)})},{26:26}],50:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{16:16}],51:[function(e,t,n){function r(e){if(e=""+e,!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*f;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=f?Math.round(e/f)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,c,"day")||a(e,f,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e1)for(var n=1;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else!t.decoder||i||r||(n=t.decoder.write(n)),t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):(t.reading=!1,t.buffer.push(n)),t.needReadable&&l(e),d(e,t);else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=j)e=j;else{e--;for(var t=1;t<32;t<<=1)e|=e>>t;e++}return e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return S.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(t.decoder&&!t.ended){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.length>0?l(e):b(e)}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,t.sync?n.nextTick(function(){h(e)}):h(e))}function h(e){e.emit("readable")}function d(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(function(){p(e,t)}))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length0)return;return 0===r.pipesCount?(r.flowing=!1,void(x.listenerCount(e,"data")>0&&_(e))):void(r.ranOut=!0)}function y(){this._readableState.ranOut&&(this._readableState.ranOut=!1,v(this))}function _(e,t){var r=e._readableState;if(r.flowing)throw new Error("Cannot switch to old mode now.");var i=t||!1,o=!1;e.readable=!0,e.pipe=R.prototype.pipe,e.on=e.addListener=R.prototype.on,e.on("readable",function(){o=!0;for(var t;!i&&null!==(t=e.read());)e.emit("data",t);null===t&&(o=!1,e._readableState.needReadable=!0)}),e.pause=function(){i=!0,this.emit("pause")},e.resume=function(){i=!1,o?n.nextTick(function(){e.emit("readable")}):this.read(0),this.emit("resume")},e.emit("readable")}function m(e,t){var n,r=t.buffer,i=t.length,o=!!t.decoder,a=!!t.objectMode;if(0===r.length)return null;if(0===i)n=null;else if(a)n=r.shift();else if(!e||e>=i)n=o?r.join(""):S.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");!t.endEmitted&&t.calledRead&&(t.ended=!0,n.nextTick(function(){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}))}function w(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return l(this),null;if(e=u(e,t),0===e&&t.ended)return n=null,t.length>0&&t.decoder&&(n=m(e,t),t.length-=n.length),0===t.length&&b(this),n;var i=t.needReadable;return t.length-e<=t.highWaterMark&&(i=!0),(t.ended||t.reading)&&(i=!1),i&&(t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1),i&&!t.reading&&(e=u(r,t)),n=e>0?m(e,t):null,null===n&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),t.ended&&!t.endEmitted&&0===t.length&&b(this),n},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){e===c&&o()}function i(){e.end()}function o(){e.removeListener("close",s),e.removeListener("finish",u),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),c.removeListener("end",i),c.removeListener("end",o),e._writableState&&!e._writableState.needDrain||p()}function a(t){f(),e.removeListener("error",a),0===x.listenerCount(e,"error")&&e.emit("error",t)}function s(){e.removeListener("finish",u),f()}function u(){e.removeListener("close",s),f()}function f(){c.unpipe(e)}var c=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=e;break;case 1:l.pipes=[l.pipes,e];break;default:l.pipes.push(e)}l.pipesCount+=1;var h=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,d=h?i:o;l.endEmitted?n.nextTick(d):c.once("end",d),e.on("unpipe",r);var p=g(c);return e.on("drain",p),e._events&&e._events.error?k(e._events.error)?e._events.error.unshift(a):e._events.error=[a,e._events.error]:e.on("error",a),e.once("close",s), +e.once("finish",u),e.emit("pipe",c),l.flowing||(this.on("readable",y),l.flowing=!0,n.nextTick(function(){v(c)})),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,this.removeListener("readable",y),t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,this.removeListener("readable",y),t.flowing=!1;for(var i=0;i>>32-i,n)}function n(e,n,r,i,o,a,s){return t(n&r|~n&i,e,n,o,a,s)}function r(e,n,r,i,o,a,s){return t(n&i|r&~i,e,n,o,a,s)}function i(e,n,r,i,o,a,s){return t(n^r^i,e,n,o,a,s)}function o(e,n,r,i,o,a,s){return t(r^(n|~i),e,n,o,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],f=e[3];a=n(a,s,u,f,t[0],7,-680876936),f=n(f,a,s,u,t[1],12,-389564586),u=n(u,f,a,s,t[2],17,606105819),s=n(s,u,f,a,t[3],22,-1044525330),a=n(a,s,u,f,t[4],7,-176418897),f=n(f,a,s,u,t[5],12,1200080426),u=n(u,f,a,s,t[6],17,-1473231341),s=n(s,u,f,a,t[7],22,-45705983),a=n(a,s,u,f,t[8],7,1770035416),f=n(f,a,s,u,t[9],12,-1958414417),u=n(u,f,a,s,t[10],17,-42063),s=n(s,u,f,a,t[11],22,-1990404162),a=n(a,s,u,f,t[12],7,1804603682),f=n(f,a,s,u,t[13],12,-40341101),u=n(u,f,a,s,t[14],17,-1502002290),s=n(s,u,f,a,t[15],22,1236535329),a=r(a,s,u,f,t[1],5,-165796510),f=r(f,a,s,u,t[6],9,-1069501632),u=r(u,f,a,s,t[11],14,643717713),s=r(s,u,f,a,t[0],20,-373897302),a=r(a,s,u,f,t[5],5,-701558691),f=r(f,a,s,u,t[10],9,38016083),u=r(u,f,a,s,t[15],14,-660478335),s=r(s,u,f,a,t[4],20,-405537848),a=r(a,s,u,f,t[9],5,568446438),f=r(f,a,s,u,t[14],9,-1019803690),u=r(u,f,a,s,t[3],14,-187363961),s=r(s,u,f,a,t[8],20,1163531501),a=r(a,s,u,f,t[13],5,-1444681467),f=r(f,a,s,u,t[2],9,-51403784),u=r(u,f,a,s,t[7],14,1735328473),s=r(s,u,f,a,t[12],20,-1926607734),a=i(a,s,u,f,t[5],4,-378558),f=i(f,a,s,u,t[8],11,-2022574463),u=i(u,f,a,s,t[11],16,1839030562),s=i(s,u,f,a,t[14],23,-35309556),a=i(a,s,u,f,t[1],4,-1530992060),f=i(f,a,s,u,t[4],11,1272893353),u=i(u,f,a,s,t[7],16,-155497632),s=i(s,u,f,a,t[10],23,-1094730640),a=i(a,s,u,f,t[13],4,681279174),f=i(f,a,s,u,t[0],11,-358537222),u=i(u,f,a,s,t[3],16,-722521979),s=i(s,u,f,a,t[6],23,76029189),a=i(a,s,u,f,t[9],4,-640364487),f=i(f,a,s,u,t[12],11,-421815835),u=i(u,f,a,s,t[15],16,530742520),s=i(s,u,f,a,t[2],23,-995338651),a=o(a,s,u,f,t[0],6,-198630844),f=o(f,a,s,u,t[7],10,1126891415),u=o(u,f,a,s,t[14],15,-1416354905),s=o(s,u,f,a,t[5],21,-57434055),a=o(a,s,u,f,t[12],6,1700485571),f=o(f,a,s,u,t[3],10,-1894986606),u=o(u,f,a,s,t[10],15,-1051523),s=o(s,u,f,a,t[1],21,-2054922799),a=o(a,s,u,f,t[8],6,1873313359),f=o(f,a,s,u,t[15],10,-30611744),u=o(u,f,a,s,t[6],15,-1560198380),s=o(s,u,f,a,t[13],21,1309151649),a=o(a,s,u,f,t[4],6,-145523070),f=o(f,a,s,u,t[11],10,-1120210379),u=o(u,f,a,s,t[2],15,718787259),s=o(s,u,f,a,t[9],21,-343485551),e[0]=m(a,e[0]),e[1]=m(s,e[1]),e[2]=m(u,e[2]),e[3]=m(f,e[3])}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function f(e){var t,n,r,i,o,u,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),u=parseInt(i[1],16)||0,r[14]=o,r[15]=u,a(c,r),c}function c(e){var t,n,r,i,o,s,f=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=f;t+=64)a(c,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(c,r),t=0;t<16;t+=1)r[t]=0;return i=8*f,i=i.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(i[2],16),s=parseInt(i[1],16)||0,r[14]=o,r[15]=s,a(c,r),c}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=b[e>>8*t+4&15]+b[e>>8*t&15];return n}function h(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,a,s,u=this.byteLength,f=t(n,u),c=u;return r!==e&&(c=t(r,u)),f>c?new ArrayBuffer(0):(i=c-f,o=new ArrayBuffer(i),a=new Uint8Array(o),s=new Uint8Array(this,f,i),a.set(s),o)}}(),_.prototype.append=function(e){return this.appendBinary(d(e)),this},_.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},_.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=y(n)),this.reset(),n},_.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},_.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},_.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},_.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},_.prototype._finish=function(e,t){var n,r,i,o=t;if(e[o>>2]|=128<<(o%4<<3),o>55)for(a(this._hash,e),o=0;o<16;o+=1)e[o]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=r,e[15]=i,a(this._hash,e)},_.hash=function(e,t){return _.hashBinary(d(e),t)},_.hashBinary=function(e,t){var n=f(e),r=h(n);return t?y(r):r},_.ArrayBuffer=function(){this.reset()},_.ArrayBuffer.prototype.append=function(e){var t,n=v(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=h(this._hash),e&&(n=y(n)),this.reset(),n},_.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},_.ArrayBuffer.prototype.getState=function(){var e=_.prototype.getState.call(this);return e.buff=g(e.buff),e},_.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),_.prototype.setState.call(this,e)},_.ArrayBuffer.prototype.destroy=_.prototype.destroy,_.ArrayBuffer.prototype._finish=_.prototype._finish,_.ArrayBuffer.hash=function(e,t){var n=c(new Uint8Array(e)),r=h(n);return t?y(r):r},_})},{}],63:[function(e,t,n){function r(){i.call(this)}t.exports=r;var i=e(21).EventEmitter,o=e(25);o(r,i),r.Readable=e(72),r.Writable=e(74),r.Duplex=e(64),r.Transform=e(73),r.PassThrough=e(71),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&f.pause&&f.pause()}function r(){f.readable&&f.resume&&f.resume()}function o(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){f.removeListener("data",n),e.removeListener("drain",r),f.removeListener("end",o),f.removeListener("close",a),f.removeListener("error",s),e.removeListener("error",s),f.removeListener("end",u),f.removeListener("close",u),e.removeListener("close",u)}var f=this;f.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(f.on("end",o),f.on("close",a));var c=!1;return f.on("error",s),e.on("error",s),f.on("end",u),f.on("close",u),e.on("close",u),e.emit("pipe",f),e}},{21:21,25:25,64:64,71:71,72:72,73:73,74:74}],64:[function(e,t,n){t.exports=e(65)},{65:65}],65:[function(e,t,n){"use strict";function r(e){return this instanceof r?(f.call(this,e),c.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var s=e(52),u=e(6);u.inherits=e(25);var f=e(67),c=e(69);u.inherits(r,f);for(var l=a(c.prototype),h=0;h0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var f;!t.decoder||i||r||(n=t.decoder.write(n),f=!t.objectMode&&0===n.length),i||(t.reading=!1),f||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e))),p(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=W?e=W:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function f(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function c(e,t){var n=null;return T.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function l(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(N("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?j(d,e):d(e))}function d(e){N("emit readable"),e.emit("readable"),b(e)}function p(e,t){t.readingMore||(t.readingMore=!0,j(g,e,t))}function g(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=E(e,t.buffer,t.decoder),n}function E(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=C.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function x(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,j(R,t,e))}function R(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function B(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return N("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?x(this):h(this),null;if(e=f(e,t),0===e&&t.ended)return 0===t.length&&x(this),null;var r=t.needReadable;N("need readable",r),(0===t.length||t.length-e0?w(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&x(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("not implemented"))},o.prototype.pipe=function(e,t){function i(e){N("onunpipe"),e===h&&a()}function o(){N("onend"),e.end()}function a(){N("cleanup"),e.removeListener("close",f),e.removeListener("finish",c),e.removeListener("drain",y),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",o),h.removeListener("end",a),h.removeListener("data",s),_=!0,!d.awaitDrain||e._writableState&&!e._writableState.needDrain||y()}function s(t){N("ondata"),m=!1;var n=e.write(t);!1!==n||m||((1===d.pipesCount&&d.pipes===e||d.pipesCount>1&&A(d.pipes,e)!==-1)&&!_&&(N("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,m=!0),h.pause())}function u(t){N("onerror",t),l(),e.removeListener("error",u),0===L(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",c),l()}function c(){N("onfinish"),e.removeListener("close",f),l()}function l(){N("unpipe"),h.unpipe(e)}var h=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=e;break;case 1:d.pipes=[d.pipes,e];break;default:d.pipes.push(e)}d.pipesCount+=1,N("pipe count=%d opts=%j",d.pipesCount,t);var p=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,g=p?o:a;d.endEmitted?j(g):h.once("end",g),e.on("unpipe",i);var y=v(h);e.on("drain",y);var _=!1,m=!1;return h.on("data",s),r(e,"error",u),e.once("close",f),e.once("finish",c),e.emit("pipe",h),d.flowing||(N("pipe resume"),h.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k;a.WritableState=o;var x=e(6);x.inherits=e(25);var R,B={deprecate:e(83)};!function(){try{R=e("stream")}catch(e){}finally{R||(R=e(21).EventEmitter)}}();var A=e(5).Buffer,j=e(4);x.inherits(a,R);var O;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:B.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var O;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),A.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{21:21,25:25,4:4,5:5,52:52,53:53,6:6,65:65,83:83}],70:[function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(e(5).Buffer,e(4));t.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},{4:4,5:5}],71:[function(e,t,n){t.exports=e(66)},{66:66}],72:[function(e,t,n){(function(r){var i=function(){try{return e("stream")}catch(e){}}();n=t.exports=e(67),n.Stream=i||n,n.Readable=n,n.Writable=e(69),n.Duplex=e(65),n.Transform=e(68),n.PassThrough=e(66),!r.browser&&"disable"===r.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e(53))},{53:53,65:65,66:66,67:67,68:68,69:69}],73:[function(e,t,n){t.exports=e(68)},{68:68}],74:[function(e,t,n){t.exports=e(69)},{69:69}],75:[function(e,t,n){function r(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e(5).Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},f=n.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),r(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};f.prototype.write=function(e){for(var t="";this.charLength;){var n=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,n),this.charReceived+=n,this.charReceived=55296&&r<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,r=t.charCodeAt(i);if(r>=55296&&r<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},f.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var n=e[e.length-t];if(1==t&&n>>5==6){this.charLength=2;break}if(t<=2&&n>>4==14){this.charLength=3;break}if(t<=3&&n>>3==30){this.charLength=4;break}}this.charReceived=t},f.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var n=this.charReceived,r=this.charBuffer,i=this.encoding;t+=r.slice(0,n).toString(i)}return t}},{5:5}],76:[function(e,t,n){arguments[4][65][0].apply(n,arguments)},{25:25,52:52,6:6,65:65,77:77,79:79}],77:[function(e,t,n){(function(n){"use strict";function r(t,n){C=C||e(76),t=t||{},this.objectMode=!!t.objectMode,n instanceof C&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(T||(T=e(75).StringDecoder),this.decoder=new T(t.encoding),this.encoding=t.encoding)}function i(t){return C=C||e(76),this instanceof i?(this._readableState=new r(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),void A.call(this)):new i(t)}function o(e,t,n,r,i){var o=f(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,c(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||r||(n=t.decoder.write(n),u=!t.objectMode&&0===n.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&l(e))),d(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=D?e=D:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:e<=0?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function f(e,t){var n=null;return B.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function c(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,l(e)}}function l(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(L("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?x(h,e):h(e))}function h(e){L("emit readable"),e.emit("readable"),m(e)}function d(e,t){t.readingMore||(t.readingMore=!0,x(p,e,t))}function p(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)n=o?r.join(""):1===r.length?r[0]:B.concat(r,i),r.length=0;else if(e0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,x(E,t,e))}function E(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var n=0,r=e.length;n0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return L("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):l(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;L("need readable",r),(0===t.length||t.length-e0?b(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),n!==e&&t.ended&&0===t.length&&w(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function r(e){L("onunpipe"),e===l&&o()}function i(){L("onend"),e.end()}function o(){L("cleanup"),e.removeListener("close",u),e.removeListener("finish",f),e.removeListener("drain",v),e.removeListener("error",s),e.removeListener("unpipe",r),l.removeListener("end",i),l.removeListener("end",o),l.removeListener("data",a),y=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function a(t){L("ondata");var n=e.write(t);!1===n&&(1!==h.pipesCount||h.pipes[0]!==e||1!==l.listenerCount("data")||y||(L("false write response, pause",l._readableState.awaitDrain),l._readableState.awaitDrain++),l.pause())}function s(t){L("onerror",t),c(),e.removeListener("error",s),0===j(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",f),c()}function f(){L("onfinish"),e.removeListener("close",u),c()}function c(){L("unpipe"),l.unpipe(e)}var l=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,L("pipe count=%d opts=%j",h.pipesCount,t);var d=(!t||t.end!==!1)&&e!==n.stdout&&e!==n.stderr,p=d?i:o;h.endEmitted?x(p):l.once("end",p),e.on("unpipe",r);var v=g(l);e.on("drain",v);var y=!1;return l.on("data",a),e._events&&e._events.error?R(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",f),e.emit("pipe",l),h.flowing||(L("pipe resume"),l.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:k,x=e(5).Buffer;a.WritableState=o;var R=e(6);R.inherits=e(25);var B,A={deprecate:e(83)};!function(){try{B=e("stream")}catch(e){}finally{B||(B=e(21).EventEmitter)}}();var x=e(5).Buffer;R.inherits(a,B);var j;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var j;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,n){var i=this._writableState,o=!1;return"function"==typeof t&&(n=t,t=null),x.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=r),i.ended?s(this,n):u(this,i,e,n)&&(i.pendingcb++,o=c(this,i,e,t,n)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||y(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,n){n(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(this,e(53))},{21:21,25:25,5:5,52:52,53:53,6:6,76:76,83:83}],80:[function(e,t,n){arguments[4][73][0].apply(n,arguments)},{73:73,78:78}],81:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{16:16}],82:[function(e,t,n){(function(n){function r(e){a.call(this,e),this._destroyed=!1}function i(e,t,n){n(null,e)}function o(e){return function(t,n,r){return"function"==typeof t&&(r=n,n=t,t={}),"function"!=typeof n&&(n=i),"function"!=typeof r&&(r=null),e(t,n,r)}}var a=e(80),s=e(86).inherits,u=e(81);s(r,a),r.prototype.destroy=function(e){if(!this._destroyed){this._destroyed=!0;var t=this;n.nextTick(function(){e&&t.emit("error",e),t.emit("close")})}},t.exports=o(function(e,t,n){var i=new r(e);return i._transform=t,n&&(i._flush=n),i}),t.exports.ctor=o(function(e,t,n){function i(t){return this instanceof i?(this.options=u(e,t),void r.call(this,this.options)):new i(t)}return s(i,r),i.prototype._transform=t,n&&(i.prototype._flush=n),i}),t.exports.obj=o(function(e,t,n){var i=new r(u({objectMode:!0,highWaterMark:16},e));return i._transform=t,n&&(i._flush=n),i})}).call(this,e(53))},{53:53,80:80,81:81,86:86}],83:[function(e,t,n){(function(e){function n(e,t){function n(){if(!i){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var i=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],84:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{25:25}],85:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],86:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&R(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return m(i)||(i=u(e,i,r)),i}var o=f(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),x(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(R(t)){var v=t.name?": "+t.name:"";return e.stylize("[Function"+v+"]","special")}if(E(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(S(t))return e.stylize(Date.prototype.toString.call(t),"date");if(x(t))return c(t)}var y="",_=!1,b=["{","}"];if(p(t)&&(_=!0,b=["[","]"]),R(t)){var w=t.name?": "+t.name:"";y=" [Function"+w+"]"}if(E(t)&&(y=" "+RegExp.prototype.toString.call(t)),S(t)&&(y=" "+Date.prototype.toUTCString.call(t)),x(t)&&(y=" "+c(t)),0===a.length&&(!_||0==t.length))return b[0]+y+b[1];if(r<0)return E(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=_?l(e,t,r,g,a):a.map(function(n){return h(e,t,r,g,n,_)}),e.seen.pop(),d(k,y,b)}function f(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return _(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function v(e){return null===e}function y(e){return null==e}function _(e){return"number"==typeof e}function m(e){return"string"==typeof e}function b(e){return"symbol"==typeof e}function w(e){return void 0===e}function E(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===A(e)}function x(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function R(e){return"function"==typeof e}function B(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}function O(){var e=new Date,t=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var L=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(f in r)r.hasOwnProperty(f)&&u.push(f);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)c=u[a],l=r[c],h=a>0?",":"",h+=JSON.stringify(c)+":",t.push({obj:l,prefix:h});t.push({val:"{"})}return d},n.parse=function(e){for(var t,n,i,o,a,s,u,f,c,l=[],h=[],d=0;;)if(t=e[d++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":d+=3,r(null,l,h);break;case"t":d+=3,r(!0,l,h);break;case"f":d+=4,r(!1,l,h);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",d--;;){ +if(i=e[d++],!/[\d\.\-e\+]/.test(i)){d--;break}n+=i}r(parseFloat(n),l,h);break;case'"':for(o="",a=void 0,s=0;;){if(u=e[d++],'"'===u&&("\\"!==a||s%2!==1))break;o+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+o+'"'),l,h);break;case"[":f={element:[],index:l.length},l.push(f.element),h.push(f);break;case"{":c={element:{},index:l.length},l.push(c.element),h.push(c);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,h)}}},{}],88:[function(e,t,n){(function(t,n,r){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function o(e){return"function"==typeof e}function a(e){return o(e.prefix)?e.prefix():e}function s(e){var t={};for(var n in e)t[n]=e[n];return t}function u(e,t,n){function r(e,r,i,o){return t.encode([e,n.encodeKey(r,i,o)])}function i(e,t){return t&&t.options&&(e.keyEncoding=e.keyEncoding||t.options.keyEncoding,e.valueEncoding=e.valueEncoding||t.options.valueEncoding),e}return e.open(function(){}),{apply:function(t,o,s){o=o||{};for(var u=[],f=-1,c=t.length;++f>>1,n(e[r],t)<0?i=r+1:o=r;return i}function H(e,t,n){var r=V(e,t,n);e.splice(r,0,t)}function $(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,a=i.tree2;(o[1].status||a[1].status)&&(o[1].status="available"===o[1].status||"available"===a[1].status?"available":"missing");for(var s=0;s0;){var g=p.pop();if(0!==g.diff)for(var v=g.ids[2],y=0,_=v.length;y<_;y++)p.push({ids:v[y],diff:g.diff-1,parent:g.ids,parentIdx:y});else g.ids[0]===l.ids[0]&&d.push(g)}var m=d[0];m?(r=X(m.ids,l.ids),m.parent[2][m.parentIdx]=r.tree,i.push({pos:c.pos,ids:c.ids}),o=o||r.conflicts,a=!0):i.push(f)}else i.push(f)}return a||i.push(t),i.sort(J),{tree:i,conflicts:o||"internal_node"}}function Q(e,t){for(var n,r=K(e),i={},o=0,a=r.length;o0||r0||ri.end)return t(null,{total_rows:r,offset:e.skip,rows:[]});var u=[],f=k.docStore.readStream(i),c=We.obj(function(t,n,r){function i(t){var n={id:a.id,key:a.id,value:{rev:c}};if(e.include_docs){n.doc=t,n.doc._rev=n.value.rev,e.conflicts&&(n.doc._conflicts=z(a));for(var i in n.doc._attachments)n.doc._attachments.hasOwnProperty(i)&&(n.doc._attachments[i].stub=!0)}if(e.inclusive_end===!1&&a.id===e.endkey)return r();if(l){if("ok"!==e.deleted)return r();n.value.deleted=!0,n.doc=null}u.push(n),r()}var a=t.value,c=Be(a),l=Ae(a,c);if(l){if("ok"!==e.deleted)return void r()}else{if(o-- >0)return void r();if("number"==typeof s&&s--<=0)return f.unpipe(),f.destroy(),void r()}if(e.include_docs){var h=a.rev_map[c];k.bySeqStore.get(v(h),function(e,t){i(t)})}else i()},function(n){it.resolve().then(function(){if(e.include_docs&&e.attachments)return Oe(u,k,e)}).then(function(){t(null,{total_rows:r,offset:e.skip,rows:u})},t),n()}).on("unpipe",function(){c.end()});f.on("error",t),f.pipe(c)})}),E._changes=function(e){function t(){e.done=!0,f&&e.limit&&e.limit0&&(r=e.limit),u.reverse||(u.start=v(e.since||0));var f,c=e.doc_ids&&new g(e.doc_ids),l=O(e),h=new p;f="return_docs"in e?e.return_docs:!("returnDocs"in e)||e.returnDocs;var d=k.bySeqStore.readStream(u),_=We.obj(function(n,u,d){function p(t){function n(n){var r=e.processChange(n,t,e);r.seq=t.seq;var i=l(r);return"object"==typeof i?e.complete(i):(i&&(s++,e.attachments&&e.include_docs?Oe([r],k,e).then(function(){e.onChange(r)}):e.onChange(r),f&&o.push(r)),void d())}var r=Be(t);if(t.seq!==g)return d();if(a=g,r===_._rev)return n(_);var i=t.rev_map[r];k.bySeqStore.get(v(i),function(e,t){n(t)})}if(r&&s>=r)return t(),d();if(e.cancelled||e.done)return d();var g=y(n.key),_=n.value;if(g===e.since&&!i)return d();if(c&&!c.has(_._id))return d();var m;return(m=h.get(_._id))?p(m):void k.docStore.get(_._id,function(t,n){return e.cancelled||e.done||w.isClosed()||ie(n.id)?d():(h.set(_._id,n),void p(n))})},function(t){return e.cancelled?t():(f&&e.limit&&e.limitr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===a&&setTimeout(function(){i()},0),a=!1}).on("error",e)}}if(!this._listeners[t]){var o=this,a=!1;this._listeners[t]=i,this.on(e,i)}},x.prototype.removeListener=function(e,t){t in this._listeners&&(Pe.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},x.prototype.notifyLocalWindows=function(e){E()?chrome.storage.local.set({dbName:e}):k()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},x.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},qe(B,Error),B.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var st,ut=(new B({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new B({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),new B({status:404,error:"not_found",reason:"missing"})),ft=new B({status:409,error:"conflict",reason:"Document update conflict"}),ct=new B({status:400,error:"bad_request",reason:"_id field must contain a string"}),lt=new B({status:412,error:"missing_id",reason:"_id is required for puts"}),ht=new B({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),dt=new B({status:412,error:"precondition_failed",reason:"Database not open"}),pt=(new B({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),new B({status:500,error:"badarg",reason:"Some query argument is invalid"})),gt=(new B({status:400,error:"invalid_request",reason:"Request was invalid"}),new B({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),new B({status:500,error:"doc_validation",reason:"Bad special document member"})),vt=new B({status:400,error:"bad_request",reason:"Something wrong with the request" +}),yt=(new B({status:400,error:"bad_request",reason:"Document must be a JSON object"}),new B({status:404,error:"not_found",reason:"Database not found"}),new B({status:500,error:"indexed_db_went_bad",reason:"unknown"}),new B({status:500,error:"web_sql_went_bad",reason:"unknown"}),new B({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new B({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new B({status:400,error:"bad_request",reason:"Invalid rev format"})),_t=(new B({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new B({status:412,error:"missing_stub"})),mt=(new B({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),M.name);st=mt?function(e){return e.name}:function(e){return e.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]};var bt=st,wt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Et=D(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),kt=D(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]),St=function(e){return atob(e)},xt=function(e){return btoa(e)},Rt=n.setImmediate||n.setTimeout,Bt=32768;Re.prototype.get=function(e,n,r){var i=xe(this,e),o=i.get(n);return o?t.nextTick(function(){r(null,o)}):null===o?t.nextTick(function(){r({name:"NotFoundError"})}):void e.get(n,function(e,t){return e?("NotFoundError"===e.name&&i.set(n,null),r(e)):(i.set(n,t),void r(null,t))})},Re.prototype.batch=function(e){for(var t=0,n=e.length;t=0;i--){var o=this._batch[i],a=o.prefix.prefix()[0]+"ÿ"+o.key;n.has(a)||(n.add(a),r.push(o))}e.batch(r,t)};var At="document-store",jt="by-sequence",Ot="attach-store",Mt="attach-binary-store",Lt="local-store",Tt="meta-store",Ct=new p,Dt="_local_last_update_seq",Pt="_local_doc_count",Nt="_local_uuid",qt="md5-",It={encode:we,decode:be,buffer:!1,type:"cheap-json"},Ut=new x;Le.valid=function(){return!0},Le.use_prefix=!1;var Wt="undefined"!=typeof PouchDB?PouchDB:e("pouchdb");Wt?Te(Wt):R("error",'memory adapter plugin error: Cannot find global "PouchDB" object! Did you remember to include pouchdb.js?')}).call(this,e(53),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e(5).Buffer)},{1:1,17:17,21:21,25:25,28:28,29:29,35:35,41:41,42:42,43:43,5:5,53:53,61:61,62:62,7:7,82:82,87:87,pouchdb:"pouchdb"}]},{},[88]); diff --git a/lib/pouchdb/dist/pouchdb.min.js b/lib/pouchdb/dist/pouchdb.min.js index 9a530877..856a3dcf 100644 --- a/lib/pouchdb/dist/pouchdb.min.js +++ b/lib/pouchdb/dist/pouchdb.min.js @@ -1,4 +1,4 @@ -// PouchDB 6.0.4 +// PouchDB 6.0.6 // // (c) 2012-2016 Dale Harvey and the PouchDB team // PouchDB may be freely distributed under the Apache license, version 2.0. @@ -6,6 +6,6 @@ // http://pouchdb.com !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.PouchDB=e()}}(function(){var e;return function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var f=n[s]={exports:{}};t[s][0].call(f.exports,function(e){var n=t[s][1][e];return o(n?n:e)},f,f.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s=31}function o(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(e){}}function a(){var e;try{e=n.storage.debug}catch(e){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(3),n.log=i,n.formatArgs=o,n.save=s,n.load=a,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(a())},{3:3}],3:[function(e,t,n){function r(){return n.colors[f++%n.colors.length]}function o(e){function t(){}function o(){var e=o,t=+new Date,i=t-(c||t);e.diff=i,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var s=Array.prototype.slice.call(arguments);s[0]=n.coerce(s[0]),"string"!=typeof s[0]&&(s=["%o"].concat(s));var a=0;s[0]=s[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;a++;var o=n.formatters[r];if("function"==typeof o){var i=s[a];t=o.call(e,i),s.splice(a,1),a--}return t}),"function"==typeof n.formatArgs&&(s=n.formatArgs.apply(e,s));var u=o.log||n.log||console.log.bind(console);u.apply(e,s)}t.enabled=!1,o.enabled=!0;var i=n.enabled(e)?o:t;return i.namespace=e,i}function i(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,o=0;o=0&&this._listeners[e].splice(n,1)}},e.prototype.dispatchEvent=function(e){if(this._listeners[e.type]&&this._listeners[e.type].length)for(var t=this._listeners[e.type].slice(),n=0,r=t.length;n0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!o(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,i,a;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],i=n.length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(a=i;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],o(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],6:[function(e,t,n){(function(e){"use strict";function n(){f=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*f;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function o(e){return e>=f?Math.round(e/f)+"d":e>=c?Math.round(e/c)+"h":e>=u?Math.round(e/u)+"m":e>=a?Math.round(e/a)+"s":e+"ms"}function i(e){return s(e,f,"day")||s(e,c,"hour")||s(e,u,"minute")||s(e,a,"second")||e+" ms"}function s(e,t,n){if(!(e1)for(var n=1;n>>32-o,n)}function n(e,n,r,o,i,s,a){return t(n&r|~n&o,e,n,i,s,a)}function r(e,n,r,o,i,s,a){return t(n&o|r&~o,e,n,i,s,a)}function o(e,n,r,o,i,s,a){return t(n^r^o,e,n,i,s,a)}function i(e,n,r,o,i,s,a){return t(r^(n|~o),e,n,i,s,a)}function s(e,t){var s=e[0],a=e[1],u=e[2],c=e[3];s=n(s,a,u,c,t[0],7,-680876936),c=n(c,s,a,u,t[1],12,-389564586),u=n(u,c,s,a,t[2],17,606105819),a=n(a,u,c,s,t[3],22,-1044525330),s=n(s,a,u,c,t[4],7,-176418897),c=n(c,s,a,u,t[5],12,1200080426),u=n(u,c,s,a,t[6],17,-1473231341),a=n(a,u,c,s,t[7],22,-45705983),s=n(s,a,u,c,t[8],7,1770035416),c=n(c,s,a,u,t[9],12,-1958414417),u=n(u,c,s,a,t[10],17,-42063),a=n(a,u,c,s,t[11],22,-1990404162),s=n(s,a,u,c,t[12],7,1804603682),c=n(c,s,a,u,t[13],12,-40341101),u=n(u,c,s,a,t[14],17,-1502002290),a=n(a,u,c,s,t[15],22,1236535329),s=r(s,a,u,c,t[1],5,-165796510),c=r(c,s,a,u,t[6],9,-1069501632),u=r(u,c,s,a,t[11],14,643717713),a=r(a,u,c,s,t[0],20,-373897302),s=r(s,a,u,c,t[5],5,-701558691),c=r(c,s,a,u,t[10],9,38016083),u=r(u,c,s,a,t[15],14,-660478335),a=r(a,u,c,s,t[4],20,-405537848),s=r(s,a,u,c,t[9],5,568446438),c=r(c,s,a,u,t[14],9,-1019803690),u=r(u,c,s,a,t[3],14,-187363961),a=r(a,u,c,s,t[8],20,1163531501),s=r(s,a,u,c,t[13],5,-1444681467),c=r(c,s,a,u,t[2],9,-51403784),u=r(u,c,s,a,t[7],14,1735328473),a=r(a,u,c,s,t[12],20,-1926607734),s=o(s,a,u,c,t[5],4,-378558),c=o(c,s,a,u,t[8],11,-2022574463),u=o(u,c,s,a,t[11],16,1839030562),a=o(a,u,c,s,t[14],23,-35309556),s=o(s,a,u,c,t[1],4,-1530992060),c=o(c,s,a,u,t[4],11,1272893353),u=o(u,c,s,a,t[7],16,-155497632),a=o(a,u,c,s,t[10],23,-1094730640),s=o(s,a,u,c,t[13],4,681279174),c=o(c,s,a,u,t[0],11,-358537222),u=o(u,c,s,a,t[3],16,-722521979),a=o(a,u,c,s,t[6],23,76029189),s=o(s,a,u,c,t[9],4,-640364487),c=o(c,s,a,u,t[12],11,-421815835),u=o(u,c,s,a,t[15],16,530742520),a=o(a,u,c,s,t[2],23,-995338651),s=i(s,a,u,c,t[0],6,-198630844),c=i(c,s,a,u,t[7],10,1126891415),u=i(u,c,s,a,t[14],15,-1416354905),a=i(a,u,c,s,t[5],21,-57434055),s=i(s,a,u,c,t[12],6,1700485571),c=i(c,s,a,u,t[3],10,-1894986606),u=i(u,c,s,a,t[10],15,-1051523),a=i(a,u,c,s,t[1],21,-2054922799),s=i(s,a,u,c,t[8],6,1873313359),c=i(c,s,a,u,t[15],10,-30611744),u=i(u,c,s,a,t[6],15,-1560198380),a=i(a,u,c,s,t[13],21,1309151649),s=i(s,a,u,c,t[4],6,-145523070),c=i(c,s,a,u,t[11],10,-1120210379),u=i(u,c,s,a,t[2],15,718787259),a=i(a,u,c,s,t[9],21,-343485551),e[0]=g(s,e[0]),e[1]=g(a,e[1]),e[2]=g(u,e[2]),e[3]=g(c,e[3])}function a(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function c(e){var t,n,r,o,i,u,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)s(f,a(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(s(f,r),t=0;t<16;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),u=parseInt(o[1],16)||0,r[14]=i,r[15]=u,s(f,r),f}function f(e){var t,n,r,o,i,a,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)s(f,u(e.subarray(t-64,t)));for(e=t-64>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(s(f,r),t=0;t<16;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),a=parseInt(o[1],16)||0,r[14]=i,r[15]=a,s(f,r),f}function l(e){var t,n="";for(t=0;t<4;t+=1)n+=b[e>>8*t+4&15]+b[e>>8*t&15];return n}function d(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,e<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var o,i,s,a,u=this.byteLength,c=t(n,u),f=u;return r!==e&&(f=t(r,u)),c>f?new ArrayBuffer(0):(o=f-c,i=new ArrayBuffer(o),s=new Uint8Array(i),a=new Uint8Array(this,c,o),s.set(a),i)}}(),m.prototype.append=function(e){return this.appendBinary(h(e)),this},m.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;t<=n;t+=64)s(this._hash,a(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},m.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),n=d(this._hash),e&&(n=_(n)),this.reset(),n},m.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},m.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},m.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},m.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},m.prototype._finish=function(e,t){var n,r,o,i=t;if(e[i>>2]|=128<<(i%4<<3),i>55)for(s(this._hash,e),i=0;i<16;i+=1)e[i]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),o=parseInt(n[1],16)||0,e[14]=r,e[15]=o,s(this._hash,e)},m.hash=function(e,t){return m.hashBinary(h(e),t)},m.hashBinary=function(e,t){var n=c(e),r=d(n);return t?_(r):r},m.ArrayBuffer=function(){this.reset()},m.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;t<=r;t+=64)s(this._hash,u(n.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(i,o),n=d(this._hash),e&&(n=_(n)),this.reset(),n},m.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},m.ArrayBuffer.prototype.getState=function(){var e=m.prototype.getState.call(this);return e.buff=v(e.buff),e},m.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),m.prototype.setState.call(this,e)},m.ArrayBuffer.prototype.destroy=m.prototype.destroy,m.ArrayBuffer.prototype._finish=m.prototype._finish,m.ArrayBuffer.hash=function(e,t){var n=f(new Uint8Array(e)),r=d(n);return t?_(r):r},m})},{}],14:[function(e,t,n){"use strict";function r(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var o=r.element,i=r.index;if(Array.isArray(o))o.push(e);else if(i===t.length-2){var s=t.pop();o[s]=e}else t.push(e)}n.stringify=function(e){var t=[];t.push({obj:e});for(var n,r,o,i,s,a,u,c,f,l,d,h="";n=t.pop();)if(r=n.obj,o=n.prefix||"",i=n.val||"",h+=o,i)h+=i;else if("object"!=typeof r)h+="undefined"==typeof r?null:JSON.stringify(r);else if(null===r)h+="null";else if(Array.isArray(r)){for(t.push({val:"]"}),s=r.length-1;s>=0;s--)a=0===s?"":",",t.push({obj:r[s],prefix:a});t.push({val:"["})}else{u=[];for(c in r)r.hasOwnProperty(c)&&u.push(c);for(t.push({val:"}"}),s=u.length-1;s>=0;s--)f=u[s],l=r[f],d=s>0?",":"",d+=JSON.stringify(f)+":",t.push({obj:l,prefix:d});t.push({val:"{"})}return h},n.parse=function(e){for(var t,n,o,i,s,a,u,c,f,l=[],d=[],h=0;;)if(t=e[h++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":h+=3,r(null,l,d);break;case"t":h+=3,r(!0,l,d);break;case"f":h+=4,r(!1,l,d);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",h--;;){if(o=e[h++],!/[\d\.\-e\+]/.test(o)){h--;break}n+=o}r(parseFloat(n),l,d);break;case'"':for(i="",s=void 0,a=0;;){if(u=e[h++],'"'===u&&("\\"!==s||a%2!==1))break;i+=u,s=u,"\\"===s?a++:a=0}r(JSON.parse('"'+i+'"'),l,d);break;case"[":c={element:[],index:l.length},l.push(c.element),d.push(c);break;case"{":f={element:{},index:l.length},l.push(f.element),d.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,d)}}},{}],15:[function(e,t,n){(function(n,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function i(e){return"$"+e}function s(e){return e.substring(1)}function a(){this.store={}}function u(e){if(this.store=new a,e&&Array.isArray(e))for(var t=0,n=e.length;t=h.length)){var e=Math.min(p+Yr,h.length),t=h.slice(p,e);a(t,p),p+=t.length}}function a(n,r){n.forEach(function(n,o){var a=r+o,u=c[n],f=_(u[0],["atts_since","attachments"]);f.open_revs=u.map(function(e){return e.rev}),f.open_revs=f.open_revs.filter(m);var l=m;0===f.open_revs.length&&(delete f.open_revs,l=g),["revs","attachments","binary","ajax"].forEach(function(e){e in t&&(f[e]=t[e])}),e.get(n,f,function(e,t){var r;r=e?[{error:e}]:l(t),i(a,n,r),s()})})}var u=t.docs,c={};u.forEach(function(e){e.id in c?c[e.id].push(e):c[e.id]=[e]});var f=Object.keys(c).length,l=0,d=new Array(f),h=Object.keys(c),p=0;s()}function w(){return"undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage&&"undefined"!=typeof chrome.storage.local}function E(){return Gr}function k(e){w()?chrome.storage.onChanged.addListener(function(t){null!=t.db_name&&e.emit(t.dbName.newValue)}):E()&&("undefined"!=typeof addEventListener?addEventListener("storage",function(t){e.emit(t.key)}):window.attachEvent("storage",function(t){e.emit(t.key)}))}function S(){Mr.EventEmitter.call(this),this._listeners={},k(this)}function q(e){if("undefined"!==console&&e in console){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}function x(e,t){var n=6e5;e=parseInt(e,10)||0,t=parseInt(t,10),t!==t||t<=e?t=(e||1)<<1:t+=1,t>n&&(e=n>>1,t=n);var r=Math.random(),o=t-e;return~~(o*r+e)}function A(e){var t=0;return e||(t=2e3),x(e,t)}function T(e,t){q("info","The above "+e+" is totally normal. "+t)}function O(e){Error.call(this,e.reason),this.status=e.status,this.name=e.error,this.message=e.reason,this.error=!0}function j(e,t){function n(t){for(var n in e)"function"!=typeof e[n]&&(this[n]=e[n]);void 0!==t&&(this.reason=t)}return n.prototype=O.prototype,new n(t)}function C(e){if("object"!=typeof e){var t=e;e=so,e.data=t}return"error"in e&&"conflict"===e.error&&(e.name="conflict",e.status=409),"name"in e||(e.name=e.error||"unknown"),"status"in e||(e.status=500),"message"in e||(e.message=e.message||e.reason),e}function L(e,t,n){try{return!e(t,n)}catch(e){var r="Filter function threw: "+e.toString();return j(fo,r)}}function I(e){var t={},n=e.filter&&"function"==typeof e.filter;return t.query=e.query_params,function(r){r.doc||(r.doc={});var o=n&&L(e.filter,r.doc,t);if("object"==typeof o)return o;if(o)return!1;if(e.include_docs){if(!e.attachments)for(var i in r.doc._attachments)r.doc._attachments.hasOwnProperty(i)&&(r.doc._attachments[i].stub=!0)}else delete r.doc;return!0}}function R(e){for(var t=[],n=0,r=e.length;n>>1,n(e[r],t)<0?o=r+1:i=r;return o}function Z(e,t,n){var r=Y(e,t,n);e.splice(r,0,t)}function ee(e,t){for(var n,r,o=t,i=e.length;o0;){var o=n.pop(),i=o.tree1,s=o.tree2;(i[1].status||s[1].status)&&(i[1].status="available"===i[1].status||"available"===s[1].status?"available":"missing");for(var a=0;a0;){var v=p.pop();if(0!==v.diff)for(var y=v.ids[2],_=0,m=y.length;_0&&o.emit("error",t):o.emit("complete",n),o.removeAllListeners(),e.removeListener("destroyed",r)});n&&(o.on("complete",function(e){n(null,e)}),o.on("error",n)),e.once("destroyed",r),t.onChange=function(e){t.isCancelled||de(o,e)};var s=new Xr(function(e,n){t.complete=function(t,r){t?n(t):e(r)}});o.once("cancel",function(){e.removeListener("destroyed",r),t.complete(null,{status:"cancelled"})}),this.then=s.then.bind(s),this.catch=s.catch.bind(s),this.then(function(e){i(null,e)},i),e.taskqueue.isReady?o.doChanges(t):e.taskqueue.addTask(function(e){e?t.complete(e):o.isCancelled?o.emit("cancel"):o.doChanges(t)})}function pe(e,t,n){var r=[{rev:e._rev}];"all_docs"===n.style&&(r=X(t.rev_tree).map(function(e){return{rev:e.rev}}));var o={id:t.id,changes:r,doc:e};return ue(t,e._rev)&&(o.deleted=!0),n.conflicts&&(o.doc._conflicts=G(t),o.doc._conflicts.length||delete o.doc._conflicts),o}function ve(e,t){return et?1:0}function ye(e,t){for(var n=0;n0?t.keys.slice(t.skip):t.keys;if(t.descending&&r.reverse(),!r.length)return e._allDocs({limit:0},n);var o={offset:t.skip};return Xr.all(r.map(function(n){var r=Br.extend({key:n,deleted:"ok"},t);return["limit","skip","keys"].forEach(function(e){delete r[e]}),new Xr(function(t,i){e._allDocs(r,function(e,r){return e?i(e):(o.total_rows=r.total_rows,void t(r.rows[0]||{key:n,error:"not_found"}))})})})).then(function(e){return o.rows=e,o})}function Ee(e){var t=e._compactionQueue[0],r=t.opts,o=t.callback;e.get("_local/compaction").catch(function(){return!1}).then(function(t){t&&t.last_seq&&(r.last_seq=t.last_seq),e._compact(r,function(t,r){t?o(t):o(null,r),n.nextTick(function(){e._compactionQueue.shift(),e._compactionQueue.length&&Ee(e)})})})}function ke(e){return"_"===e.charAt(0)&&e+"is not a valid attachment name, attachment names cannot start with '_'"}function Se(){Mr.EventEmitter.call(this)}function qe(){this.isReady=!1,this.failed=!1,this.queue=[]}function xe(e,t){var n=e.match(/([a-z\-]*):\/\/(.*)/);if(n)return e=/http(s?)/.test(n[1])?n[1]+"://"+n[2]:n[2],{name:e,adapter:n[1]};var r,o="idb"in Te.adapters&&"websql"in Te.adapters&&E()&&localStorage["_pouch__websqldb_"+Te.prefix+e];if(t.adapter)r=t.adapter;else if("undefined"!=typeof t&&t.db)r="leveldb";else for(var i=0;i0||r0||r=43)}}).catch(function(){return!1})}function Et(e,t){var n=this;Po.queue.push({action:function(t){kt(n,e,t)},callback:t}),at(n.constructor)}function kt(e,t,r){function o(e){var t=e.createObjectStore(Lo,{keyPath:"id"});e.createObjectStore(Io,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0}),e.createObjectStore(Ro,{keyPath:"digest"}),e.createObjectStore(No,{keyPath:"id",autoIncrement:!1}),e.createObjectStore(Fo),t.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),e.createObjectStore(Bo,{keyPath:"_id"});var n=e.createObjectStore(Do,{autoIncrement:!0});n.createIndex("seq","seq"),n.createIndex("digestSeq","digestSeq",{unique:!0})}function i(e,t){var n=e.objectStore(Lo);n.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var o=r.value,i=ue(o);o.deletedOrLocal=i?"1":"0",n.put(o),r.continue()}else t()}}function s(e){e.createObjectStore(Bo,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function c(e,t){var n=e.objectStore(Bo),r=e.objectStore(Lo),o=e.objectStore(Io),i=r.openCursor();i.onsuccess=function(e){var i=e.target.result;if(i){var s=i.value,a=s.id,u=ce(a),c=J(s);if(u){var f=a+"::"+c,l=a+"::",d=a+"::~",h=o.index("_doc_id_rev"),p=IDBKeyRange.bound(l,d,!1,!1),v=h.openCursor(p);v.onsuccess=function(e){if(v=e.target.result){var t=v.value;t._doc_id_rev===f&&n.put(t),o.delete(v.primaryKey),v.continue()}else r.delete(i.primaryKey),i.continue()}}else i.continue()}else t&&t()}}function f(e){var t=e.createObjectStore(Do,{autoIncrement:!0});t.createIndex("seq","seq"),t.createIndex("digestSeq","digestSeq",{unique:!0})}function l(e,t){var n=e.objectStore(Io),r=e.objectStore(Ro),o=e.objectStore(Do),i=r.count();i.onsuccess=function(e){var r=e.target.result;return r?void(n.openCursor().onsuccess=function(e){var n=e.target.result;if(!n)return t();for(var r=n.value,i=n.primaryKey,s=Object.keys(r._attachments||{}),a={},u=0;uo&&(o=n),t.continue()}}function i(){var e=ct(a,a.winningRev,a.deleted),t=r.put(e);t.onsuccess=function(){s.continue()}}var s=e.target.result;if(s){var a=t(s.value);return a.winningRev=a.winningRev||J(a),a.seq?i():void o()}}}var p=t.name,y=null;e._meta=null,e.type=function(){return"idb"},e._id=v(function(t){t(null,e._meta.instanceId)}),e._bulkDocs=function(n,r,o){_t(t,n,r,e,y,Mo,o)},e._get=function(e,t,n){function r(){n(s,{doc:o,metadata:i,ctx:a})}var o,i,s,a=t.ctx;if(!a){var u=yt(y,[Lo,Io,Ro],"readonly");if(u.error)return n(u.error);a=u.txn}a.objectStore(Lo).get(e).onsuccess=function(e){if(i=ft(e.target.result),!i)return s=j(eo,"missing"),r();if(ue(i)&&!t.rev)return s=j(eo,"deleted"),r();var n=a.objectStore(Io),u=t.rev||i.winningRev,c=i.id+"::"+u;n.index("_doc_id_rev").get(c).onsuccess=function(e){return o=e.target.result,o&&(o=lt(o)),o?void r():(s=j(eo,"missing"),r())}}},e._getAttachment=function(e,t,n,r,o){var i;if(r.ctx)i=r.ctx;else{var s=yt(y,[Lo,Io,Ro],"readonly");if(s.error)return o(s.error);i=s.txn}var a=n.digest,u=n.content_type;i.objectStore(Ro).get(a).onsuccess=function(e){var t=e.target.result.body;dt(t,u,r.binary,function(e){o(null,e)})}},e._info=function(t){if(null===y||!Uo.has(p)){var n=new Error("db isn't open");return n.id="idbNull",t(n)}var r,o,i=yt(y,[Io],"readonly");if(i.error)return t(i.error);var s=i.txn,a=s.objectStore(Io).openCursor(null,"prev");a.onsuccess=function(t){var n=t.target.result;r=n?n.key:0,o=e._meta.docCount},s.oncomplete=function(){t(null,{doc_count:o,update_seq:r,idb_attachment_format:e._meta.blobSupport?"binary":"base64"})}},e._allDocs=function(t,n){bt(t,e,y,n)},e._changes=function(t){function n(e){function n(){return a.seq!==s?e.continue():(f=s,a.winningRev===i._rev?o(i):void r())}function r(){var e=i._id+"::"+a.winningRev,t=g.get(e);t.onsuccess=function(e){o(lt(e.target.result))}}function o(n){var r=t.processChange(n,a,t);r.seq=a.seq;var o=E(r);return"object"==typeof o?t.complete(o):(o&&(w++,d&&b.push(r),t.attachments&&t.include_docs?ht(n,t,v,function(){pt([r],t.binary).then(function(){t.onChange(r)})}):t.onChange(r)),void(w!==l&&e.continue()))}var i=lt(e.value),s=e.key;if(c&&!c.has(i._id))return e.continue();var a;return(a=k.get(i._id))?n():void(m.get(i._id).onsuccess=function(e){a=ft(e.target.result),k.set(i._id,a),n()})}function r(e){var t=e.target.result;t&&n(t)}function o(){var e=[Lo,Io];t.attachments&&e.push(Ro);var n=yt(y,e,"readonly");if(n.error)return t.complete(n.error);v=n.txn,v.onabort=ut(t.complete),v.oncomplete=i,_=v.objectStore(Io),m=v.objectStore(Lo),g=_.index("_doc_id_rev");var o;o=t.descending?_.openCursor(null,"prev"):_.openCursor(IDBKeyRange.lowerBound(t.since,!0)),o.onsuccess=r}function i(){function e(){t.complete(null,{results:b,last_seq:f})}!t.continuous&&t.attachments?pt(b).then(e):e()}if(t=h(t),t.continuous){var s=p+":"+W();return Mo.addListener(p,s,e,t),Mo.notify(p),{cancel:function(){Mo.removeListener(p,s)}}}var c=t.doc_ids&&new u(t.doc_ids);t.since=t.since||0;var f=t.since,l="limit"in t?t.limit:-1;0===l&&(l=1);var d;d="return_docs"in t?t.return_docs:!("returnDocs"in t)||t.returnDocs;var v,_,m,g,b=[],w=0,E=I(t),k=new a;o()},e._close=function(e){return null===y?e(j(io)):(y.close(),Uo.delete(p),y=null,void e())},e._getRevisionTree=function(e,t){var n=yt(y,[Lo],"readonly");if(n.error)return t(n.error);var r=n.txn,o=r.objectStore(Lo).get(e);o.onsuccess=function(e){var n=ft(e.target.result);n?t(null,n.rev_tree):t(j(eo))}},e._doCompaction=function(e,t,n){var r=[Lo,Io,Ro,Do],o=yt(y,r,"readwrite");if(o.error)return n(o.error);var i=o.txn,s=i.objectStore(Lo);s.get(e).onsuccess=function(n){var r=ft(n.target.result);K(r.rev_tree,function(e,n,r,o,i){var s=n+"-"+r;t.indexOf(s)!==-1&&(i.status="missing")}),vt(t,e,i);var o=r.winningRev,s=r.deleted;i.objectStore(Lo).put(ct(r,o,s))},i.onabort=ut(n),i.oncomplete=function(){n()}},e._getLocal=function(e,t){var n=yt(y,[Bo],"readonly");if(n.error)return t(n.error);var r=n.txn,o=r.objectStore(Bo).get(e);o.onerror=ut(t),o.onsuccess=function(e){var n=e.target.result;n?(delete n._doc_id_rev,t(null,n)):t(j(eo))}},e._putLocal=function(e,t,n){"function"==typeof t&&(n=t,t={}),delete e._revisions;var r=e._rev,o=e._id;r?e._rev="0-"+(parseInt(r.split("-")[1],10)+1):e._rev="0-1";var i,s=t.ctx;if(!s){var a=yt(y,[Bo],"readwrite");if(a.error)return n(a.error);s=a.txn,s.onerror=ut(n),s.oncomplete=function(){i&&n(null,i)}}var u,c=s.objectStore(Bo);r?(u=c.get(o),u.onsuccess=function(o){var s=o.target.result;if(s&&s._rev===r){var a=c.put(e);a.onsuccess=function(){i={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,i)}}else n(j(to))}):(u=c.add(e),u.onerror=function(e){n(j(to)),e.preventDefault(),e.stopPropagation()},u.onsuccess=function(){i={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,i)})},e._removeLocal=function(e,t,n){"function"==typeof t&&(n=t,t={});var r=t.ctx;if(!r){var o=yt(y,[Bo],"readwrite");if(o.error)return n(o.error);r=o.txn,r.oncomplete=function(){i&&n(null,i)}}var i,s=e._id,a=r.objectStore(Bo),u=a.get(s);u.onerror=ut(n),u.onsuccess=function(r){var o=r.target.result;o&&o._rev===e._rev?(a.delete(s),i={ok:!0,id:s,rev:"0-0"},t.ctx&&n(null,i)):n(j(eo))}},e._destroy=function(e,t){Mo.removeAllListeners(p);var n=Ho.get(p);n&&n.result&&(n.result.close(),Uo.delete(p));var r=indexedDB.deleteDatabase(p);r.onsuccess=function(){Ho.delete(p),E()&&p in localStorage&&delete localStorage[p],t(null,{ok:!0})},r.onerror=ut(t)};var _=Uo.get(p);if(_)return y=_.idb,e._meta=_.global,void n.nextTick(function(){r(null,e)});var m;m=t.storage?St(p,t.storage):indexedDB.open(p,Co),Ho.set(p,m),m.onupgradeneeded=function(e){function t(){var e=a[u-1];u++,e&&e(r,t)}var n=e.target.result;if(e.oldVersion<1)return o(n);var r=e.currentTarget.transaction;e.oldVersion<3&&s(n),e.oldVersion<4&&f(n);var a=[i,c,l,d],u=e.oldVersion;t()},m.onsuccess=function(t){y=t.target.result,y.onversionchange=function(){y.close(),Uo.delete(p)},y.onabort=function(e){q("error","Database has a global failure",e.target.error),y.close(),Uo.delete(p)};var n=y.transaction([No,Fo,Lo],"readwrite"),o=n.objectStore(No).get(No),i=null,s=null,a=null;o.onsuccess=function(t){var o=function(){null!==i&&null!==s&&null!==a&&(e._meta={name:p,instanceId:a,blobSupport:i,docCount:s},Uo.set(p,{idb:y,global:e._meta}),r(null,e))},u=t.target.result||{id:No};p+"_id"in u?(a=u[p+"_id"],o()):(a=W(),u[p+"_id"]=a,n.objectStore(No).put(u).onsuccess=function(){o()}),So||(So=wt(n)),So.then(function(e){i=e,o()});var c=n.objectStore(Lo).index("deletedOrLocal");c.count(IDBKeyRange.only("0")).onsuccess=function(e){s=e.target.result,o()}}},m.onerror=function(){ -var e="Failed to open indexedDB, are you in private browsing mode?";q("error",e),r(j(ho,e))}}function St(e,t){try{return indexedDB.open(e,{version:Co,storage:t})}catch(t){return indexedDB.open(e,Co)}}function qt(e){e.adapter("idb",Et,!0)}function xt(e){return decodeURIComponent(escape(e))}function At(e){return e<65?e-48:e-55}function Tt(e,t,n){for(var r="";t0;){var e=w.pop();e(null,g)}}function l(e,t){if(0===t){var n="CREATE TABLE IF NOT EXISTS "+Go+" (dbid, db_version INTEGER)",c="CREATE TABLE IF NOT EXISTS "+zo+" (digest UNIQUE, escaped TINYINT(1), body BLOB)",l="CREATE TABLE IF NOT EXISTS "+Vo+" (digest, seq INTEGER)",d="CREATE TABLE IF NOT EXISTS "+Jo+" (id unique, json, winningseq, max_seq INTEGER UNIQUE)",h="CREATE TABLE IF NOT EXISTS "+Ko+" (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, json, deleted TINYINT(1), doc_id, rev)",p="CREATE TABLE IF NOT EXISTS "+Xo+" (id UNIQUE, rev, json)";e.executeSql(c),e.executeSql(p),e.executeSql(l,[],function(){e.executeSql(ni),e.executeSql(ri)}),e.executeSql(d,[],function(){e.executeSql(ti),e.executeSql(h,[],function(){e.executeSql(Zo),e.executeSql(ei),e.executeSql(n,[],function(){var t="INSERT INTO "+Go+" (db_version, dbid) VALUES (?,?)";g=W();var n=[Wo,g];e.executeSql(t,n,function(){f()})})})})}else{var v=function(){var n=t=")+" ?"),l.push(o)),i!==!1){var h=a?">":"<";f&&(h+="="),d.push(Jo+".id "+h+" ?"),l.push(i)}s!==!1&&(d.push(Jo+".id = ?"),l.push(s))}"ok"!==e.deleted&&d.push(Ko+".deleted = 0"),q.readTransaction(function(t){y(t,function(o){if(n=o,0!==u){var i=Bt(ii,[Jo,Ko],oi,d,Jo+".id "+(a?"DESC":"ASC"));i+=" LIMIT "+u+" OFFSET "+c,t.executeSql(i,l,function(t,n){for(var o=0,i=n.rows.length;o ?"],f=[e.since];e.doc_ids&&(c.push(Jo+".id IN "+Nt(e.doc_ids.length)),f=f.concat(e.doc_ids));var l="maxSeq "+(r?"DESC":"ASC"),d=Bt(t,n,u,c,l),h=I(e);e.view||e.filter||(d+=" LIMIT "+o);var p=e.since||0;q.readTransaction(function(t){t.executeSql(d,f,function(t,n){function r(t){return function(){e.onChange(t)}}for(var u=0,c=n.rows.length;u0&&(r=setTimeout(function(){n.reject(new Error("Load timeout for resource: "+e.url))},e.timeout)),n.promise.then(function(t){return o={statusCode:t.status},e.timeout>0&&clearTimeout(r),o.statusCode>=200&&o.statusCode<300?e.binary?t.blob():t.text():t.json()}).then(function(e){o.statusCode>=200&&o.statusCode<300?t(null,o,e):t(e,o)}).catch(function(e){t(e,o)}),{abort:n.reject}}function tn(e,t){var n,r,o=!1,i=function(){n.abort(),u()},s=function(){o=!0,n.abort(),u()},a={abort:i},u=function(){clearTimeout(r),a.abort=function(){},n&&(n.onprogress=void 0,n.upload&&(n.upload.onprogress=void 0),n.onreadystatechange=void 0,n=void 0)};n=e.xhr?new e.xhr:new XMLHttpRequest;try{n.open(e.method,e.url)}catch(e){return t(new Error(e.name||"Url is invalid"))}n.withCredentials=!("withCredentials"in e)||e.withCredentials,"GET"===e.method?delete e.headers["Content-Type"]:e.json&&(e.headers.Accept="application/json",e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json",e.body&&e.processData&&"string"!=typeof e.body&&(e.body=JSON.stringify(e.body))),e.binary&&(n.responseType="arraybuffer"),"body"in e||(e.body=null);for(var c in e.headers)e.headers.hasOwnProperty(c)&&n.setRequestHeader(c,e.headers[c]);return e.timeout>0&&(r=setTimeout(s,e.timeout),n.onprogress=function(){clearTimeout(r),4!==n.readyState&&(r=setTimeout(s,e.timeout))},"undefined"!=typeof n.upload&&(n.upload.onprogress=n.onprogress)),n.onreadystatechange=function(){if(4===n.readyState){var r={statusCode:n.status};if(n.status>=200&&n.status<300){var i;i=e.binary?Re([n.response||""],{type:n.getResponseHeader("Content-Type")}):n.responseText,t(null,r,i)}else{var s={};if(o)s=new Error("ETIMEDOUT"),s.code="ETIMEDOUT";else if("string"==typeof n.response)try{s=JSON.parse(n.response)}catch(e){}s.status=n.status,t(s)}u()}},e.body&&e.body instanceof Blob?He(e.body,function(e){n.send(e)}):n.send(e.body),a}function nn(){try{return new XMLHttpRequest,!0}catch(e){return!1}}function rn(e,t){return si||e.xhr?tn(e,t):en(e,t)}function on(){return""}function sn(e,t){function n(t,n,r){if(!e.binary&&e.json&&"string"==typeof t)try{t=JSON.parse(t)}catch(e){return r(e)}Array.isArray(t)&&(t=t.map(function(e){return e.error||e.missing?C(e):e})),e.binary&&ai(t,n),r(null,t,n)}e=h(e);var r={method:"GET",headers:{},json:!0,processData:!0,timeout:1e4,cache:!1};return e=Br.extend(r,e),e.json&&(e.binary||(e.headers.Accept="application/json"),e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json"),e.binary&&(e.encoding=null,e.json=!1),e.processData||(e.json=!1),rn(e,function(r,o,i){if(r)return t(C(r));var s,a=o.headers&&o.headers["content-type"],u=i||on();if(!e.binary&&(e.json||!e.processData)&&"object"!=typeof u&&(/json/.test(a)||/^[\s]*\{/.test(u)&&/\}[\s]*$/.test(u)))try{u=JSON.parse(u.toString())}catch(e){}o.statusCode>=200&&o.statusCode<300?n(u,o,t):(s=C(u),s.status=o.statusCode,t(s))})}function an(e,t){var n=navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",r=n.indexOf("safari")!==-1&&n.indexOf("chrome")===-1,o=n.indexOf("msie")!==-1,i=n.indexOf("edge")!==-1,s=r||(o||i)&&"GET"===e.method,a=!("cache"in e)||e.cache,u=/^blob:/.test(e.url);if(!u&&(s||!a)){var c=e.url.indexOf("?")!==-1;e.url+=(c?"&":"?")+"_nonce="+Date.now()}return sn(e,t)}function un(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];n.data=Be(n.data,n.content_type)})}function cn(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):/^_local/.test(e)?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function fn(e){return e._attachments&&Object.keys(e._attachments)?Xr.all(Object.keys(e._attachments).map(function(t){var n=e._attachments[t];if(n.data&&"string"!=typeof n.data)return new Xr(function(e){Me(n.data,e)}).then(function(e){n.data=e})})):Xr.resolve()}function ln(e){if(!e.prefix)return!1;var t=P(e.prefix).protocol;return"http"===t||"https"===t}function dn(e,t){if(ln(t)){var n=t.name.substr(t.prefix.length);e=t.prefix+encodeURIComponent(n)}var r=P(e);(r.user||r.password)&&(r.auth={username:r.user,password:r.password});var o=r.path.replace(/(^\/|\/$)/g,"").split("/");return r.db=o.pop(),r.db.indexOf("%")===-1&&(r.db=encodeURIComponent(r.db)),r.path=o.join("/"),r}function hn(e,t){return pn(e,e.db+"/"+t)}function pn(e,t){var n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function vn(e){return"?"+Object.keys(e).map(function(t){return t+"="+encodeURIComponent(e[t])}).join("&")}function yn(e,t){function n(e,t,n){var r=e.ajax||{},o=Br.extend(h(f),r,t);return li(o.method+" "+o.url),a._ajax(o,n)}function r(e,t){return new Xr(function(r,o){n(e,t,function(e,t){return e?o(e):void r(t)})})}function o(e,t){return y(e,Hr(function(e){i().then(function(){return t.apply(this,e)}).catch(function(t){var n=e.pop();n(t)})}))}function i(){if(e.skipSetup||e.skip_setup)return Xr.resolve();if(v)return v;var t={method:"GET",url:c};return v=r({},t).catch(function(e){return e&&e.status&&404===e.status?(T(404,"PouchDB is just detecting if the remote exists."),r({},{method:"PUT",url:c})):Xr.reject(e)}).catch(function(e){return!(!e||!e.status||412!==e.status)||Xr.reject(e)}),v.catch(function(){v=null}),v}function s(e){return e.split("/").map(encodeURIComponent).join("/")}var a=this,u=dn(e.name,e),c=hn(u,"");e=h(e);var f=e.ajax||{};if(e.auth||u.auth){var l=e.auth||u.auth,d=l.username+":"+l.password,p=To(unescape(encodeURIComponent(d)));f.headers=f.headers||{},f.headers.Authorization="Basic "+p}a._ajax=an;var v;setTimeout(function(){t(null,a)}),a.type=function(){return"http"},a.id=o("id",function(e){n({},{method:"GET",url:pn(u,"")},function(t,n){var r=n&&n.uuid?n.uuid+u.db:hn(u,"");e(null,r)})}),a.request=o("request",function(e,t){e.url=hn(u,e.url),n({},e,t)}),a.compact=o("compact",function(e,t){"function"==typeof e&&(t=e,e={}),e=h(e),n(e,{url:hn(u,"_compact"),method:"POST"},function(){function n(){a.info(function(r,o){o&&!o.compact_running?t(null,{ok:!0}):setTimeout(n,e.interval||200)})}n()})}),a.bulkGet=y("bulkGet",function(e,t){function r(t){var r={};e.revs&&(r.revs=!0),e.attachments&&(r.attachments=!0),n({},{url:hn(u,"_bulk_get"+vn(r)),method:"POST",body:{docs:e.docs}},t)}function o(){function n(e){return function(n,r){a[e]=r.results,++s===o&&t(null,{results:R(a)})}}for(var r=ci,o=Math.ceil(e.docs.length/r),s=0,a=new Array(o),u=0;ut?t:a;var f={method:d,url:hn(u,"_changes"+vn(o)),timeout:e.timeout,body:l};v=r,e.aborted||i().then(function(){p=n(e,f,c)}).catch(c)}},_={results:[]},m=function(n,o){if(!e.aborted){var i=0;if(o&&o.results){i=o.results.length,_.last_seq=o.last_seq;var u={};u.query=e.query_params,o.results=o.results.filter(function(t){a--;var n=I(e)(t);return n&&(e.include_docs&&e.attachments&&e.binary&&un(t),r&&_.results.push(t),e.onChange(t)),n})}else if(n)return e.aborted=!0,void e.complete(n);o&&o.last_seq&&(v=o.last_seq);var c=s&&a<=0||o&&it.length?1:-1}function Tn(e,t){return e===t?0:e>t?1:-1}function On(e,t){for(var n=Object.keys(e),r=Object.keys(t),o=Math.min(n.length,r.length),i=0;ir.length?1:-1}function jn(e){var t=["boolean","number","string","object"],n=t.indexOf(typeof e);return~n?null===e?1:Array.isArray(e)?5:n<3?n+2:n+3:Array.isArray(e)?5:void 0}function Cn(e){if(0===e)return"1";var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=e<0,o=r?"0":"2",i=(r?-n:n)-di,s=gn(i.toString(),"0",hi);o+=pi+s;var a=Math.abs(parseFloat(t[0]));r&&(a=10-a);var u=a.toFixed(20);return u=u.replace(/\.?0+$/,""),o+=pi+u}function Ln(){this.promise=new Xr(function(e){e()})}function In(e){var t,n=e.db,r=e.viewName,o=e.map,i=e.reduce,s=e.temporary,a=o.toString()+(i&&i.toString())+"undefined";if(!s&&(t=n._cachedViews=n._cachedViews||{},t[a]))return t[a];var u=n.info().then(function(e){function u(e){e.views=e.views||{};var t=r;t.indexOf("/")===-1&&(t=r+"/"+r);var n=e.views[t]=e.views[t]||{};if(!n[c])return n[c]=!0,e}var c=e.db_name+"-mrview-"+(s?"temp":Ge(a));return U(n,"_local/mrviews",u).then(function(){return n.registerDependentDatabase(c).then(function(e){var r=e.db;r.auto_compaction=!0;var s={name:c,db:r,sourceDB:n,adapter:n.adapter,mapFun:o,reduceFun:i};return s.db.get("_local/lastSeq").catch(function(e){if(404!==e.status)throw e}).then(function(e){return s.seq=e?e.seq:0,t&&s.db.once("destroyed",function(){delete t[a]}),s})})})});return t&&(t[a]=u),u}function Rn(e,t,n,r,o,i){return Wr("return ("+e.replace(/;\s*$/,"")+");",{emit:t,sum:n,log:r,isArray:o,toJSON:i})}function Dn(e){return e.indexOf("/")===-1?[e,e]:e.split("/")}function Nn(e){return 1===e.length&&/^1-/.test(e[0].rev)}function Bn(e,t){try{e.emit("error",t)}catch(e){q("error","The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function."),q("error",t)}}function Fn(e,t,n){try{return{output:t.apply(null,n)}}catch(t){return Bn(e,t),{error:t}}}function Pn(e,t){var n=bn(e.key,t.key);return 0!==n?n:bn(e.value,t.value)}function Un(e,t,n){return n=n||0,"number"==typeof t?e.slice(n,t+n):n>0?e.slice(n):e}function Mn(e){var t=e.value,n=t&&"object"==typeof t&&t._id||e.id;return n}function Hn(e){e.rows.forEach(function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];t[e].data=Be(n.data,n.content_type)})})}function Wn(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&Hn(t),t}}function Jn(e){var t="builtin "+e+" function requires map values to be numbers or number arrays";return new pr(t)}function Kn(e){for(var t=0,n=0,r=e.length;n0)throw new dr("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new dr("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new dr("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach(function(t){var n=Vn(e[t]);if(n)throw n})}function $n(e,t,n){var r,o=[],i="GET";if(zn("reduce",n,o),zn("include_docs",n,o),zn("attachments",n,o),zn("limit",n,o),zn("descending",n,o),zn("group",n,o),zn("group_level",n,o),zn("skip",n,o),zn("stale",n,o),zn("conflicts",n,o),zn("startkey",n,o,!0),zn("start_key",n,o,!0),zn("endkey",n,o,!0),zn("end_key",n,o,!0),zn("inclusive_end",n,o),zn("key",n,o,!0),o=o.join("&"),o=""===o?"":"?"+o,"undefined"!=typeof n.keys){var s=2e3,a="keys="+encodeURIComponent(JSON.stringify(n.keys));a.length+o.length+1<=s?o+=("?"===o[0]?"&":"?")+a:(i="POST","string"==typeof t?r={keys:n.keys}:t.keys=n.keys)}if("string"==typeof t){var u=Dn(t);return e.request({method:i,url:"_design/"+u[0]+"/_view/"+u[1]+o,body:r}).then(Wn(n))}return r=r||{},Object.keys(t).forEach(function(e){Array.isArray(t[e])?r[e]=t[e]:r[e]=t[e].toString()}),e.request({method:"POST",url:"_temp_view"+o,body:r}).then(Wn(n))}function Yn(e,t,n){return new Xr(function(r,o){e._query(t,n,function(e,t){return e?o(e):void r(t)})})}function Zn(e){return new Xr(function(t,n){e._viewCleanup(function(e,r){return e?n(e):void t(r)})})}function er(e){return function(t){if(404===t.status)return e;throw t}}function tr(e,t,n){function r(){return Nn(f)?Xr.resolve(a):t.db.get(s).catch(er(a))}function o(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Xr.resolve({rows:[]})}function i(e,t){for(var n=[],r={},o=0,i=t.rows.length;on))return e.doc.value}var r=xn(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}})})}function r(n){var r;if(r=i?sr(e,n,t):{total_rows:o,offset:s,rows:n},t.include_docs){var a=gi(n.map(Mn));return e.sourceDB.allDocs({keys:a,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}).then(function(e){var t={};return e.rows.forEach(function(e){e.doc&&(t["$"+e.id]=e.doc)}),n.forEach(function(e){var n=Mn(e),r=t["$"+n];r&&(e.doc=r)}),r})}return r}var o,i=e.reduceFun&&t.reduce!==!1,s=t.skip||0;if("undefined"==typeof t.keys||t.keys.length||(t.limit=0,delete t.keys),"undefined"!=typeof t.keys){var a=t.keys,u=a.map(function(e){var t={startkey:kn([e]),endkey:kn([e,{}])};return n(t)});return Xr.all(u).then(R).then(r)}var c={descending:t.descending};if(t.start_key&&(t.startkey=t.start_key),t.end_key&&(t.endkey=t.end_key),"undefined"!=typeof t.startkey&&(c.startkey=kn(t.descending?[t.startkey,{}]:[t.startkey])),"undefined"!=typeof t.endkey){var f=t.inclusive_end!==!1;t.descending&&(f=!f),c.endkey=kn(f?[t.endkey,{}]:[t.endkey])}if("undefined"!=typeof t.key){var l=kn([t.key]),d=kn([t.key,{}]);c.descending?(c.endkey=l,c.startkey=d):(c.startkey=l,c.endkey=d)}return i||("number"==typeof t.limit&&(c.limit=t.limit),c.skip=s),n(c).then(r)}function cr(e){return e.request({method:"POST",url:"_view_cleanup"})}function fr(e){return e.get("_local/mrviews").then(function(t){var n={};Object.keys(t.views).forEach(function(e){var t=Dn(e),r="_design/"+t[0],o=t[1];n[r]=n[r]||{},n[r][o]=!0});var r={keys:Object.keys(n),include_docs:!0};return e.allDocs(r).then(function(r){var o={};r.rows.forEach(function(e){var r=e.key.substring(8);Object.keys(n[e.key]).forEach(function(n){var i=r+"/"+n;t.views[i]||(i=n);var s=Object.keys(t.views[i]),a=e.doc&&e.doc.views&&e.doc.views[n];s.forEach(function(e){o[e]=o[e]||a})})});var i=Object.keys(o).filter(function(e){return!o[e]}),s=i.map(function(t){return mi(rr(t),function(){return new e.constructor(t,e.__opts).destroy()})()});return Xr.all(s).then(function(){return{ok:!0}})})},er({ok:!0}))}function lr(e,t,r){if("http"===e.type())return $n(e,t,r);if("function"==typeof e._query)return Yn(e,t,r);if("string"!=typeof t){Qn(r,t);var o={db:e,viewName:"temp_view/temp_view",map:t.map,reduce:t.reduce,temporary:!0};return wi.add(function(){return In(o).then(function(e){function t(){return e.db.destroy()}return _i(or(e).then(function(){return ar(e,r)}),t)})}),wi.finish()}var i=t,s=Dn(i),a=s[0],u=s[1];return e.get("_design/"+a).then(function(t){var o=t.views&&t.views[u];if(!o||"string"!=typeof o.map)throw new hr("ddoc "+a+" has no view named "+u);Qn(r,o);var s={db:e,viewName:i,map:o.map,reduce:o.reduce};return In(s).then(function(e){return"ok"===r.stale||"update_after"===r.stale?("update_after"===r.stale&&n.nextTick(function(){or(e)}),ar(e,r)):or(e).then(function(){return ar(e,r)})})})}function dr(e){this.status=400,this.name="query_parse_error",this.message=e,this.error=!0;try{Error.captureStackTrace(this,dr)}catch(e){}}function hr(e){this.status=404,this.name="not_found",this.message=e,this.error=!0;try{Error.captureStackTrace(this,hr)}catch(e){}}function pr(e){this.status=500,this.name="invalid_value",this.message=e,this.error=!0;try{Error.captureStackTrace(this,pr)}catch(e){}}function vr(e){return/^1-/.test(e)}function yr(e,t,n){return!e._attachments||!e._attachments[n]||e._attachments[n].digest!==t._attachments[n].digest}function _r(e,t){var n=Object.keys(t._attachments);return Xr.all(n.map(function(n){return e.getAttachment(t._id,n,{rev:t._rev})}))}function mr(e,t,n){var r="http"===t.type()&&"http"!==e.type(),o=Object.keys(n._attachments);return r?e.get(n._id).then(function(r){return Xr.all(o.map(function(o){return yr(r,n,o)?t.getAttachment(n._id,o):e.getAttachment(r._id,o)}))}).catch(function(e){if(404!==e.status)throw e;return _r(t,n)}):_r(t,n)}function gr(e){var t=[];return Object.keys(e).forEach(function(n){var r=e[n].missing;r.forEach(function(e){t.push({id:n,rev:e})})}),{docs:t,revs:!0}}function br(e,t,n,r){function o(){var o=gr(n);if(o.docs.length)return e.bulkGet(o).then(function(n){if(r.cancelled)throw new Error("cancelled");return Xr.all(n.results.map(function(n){return Xr.all(n.docs.map(function(n){var r=n.ok;return n.error&&(f=!1),r&&r._attachments?mr(t,e,r).then(function(e){var t=Object.keys(r._attachments);return e.forEach(function(e,n){var o=r._attachments[t[n]];delete o.stub,delete o.length,o.data=e}),r}):r}))})).then(function(e){c=c.concat(R(e).filter(Boolean))})})}function i(e){return e._attachments&&Object.keys(e._attachments).length>0}function s(t){return e.allDocs({keys:t,include_docs:!0}).then(function(e){if(r.cancelled)throw new Error("cancelled");e.rows.forEach(function(e){!e.deleted&&e.doc&&vr(e.value.rev)&&!i(e.doc)&&(c.push(e.doc),delete n[e.id])})})}function a(){var e=Object.keys(n).filter(function(e){var t=n[e].missing;return 1===t.length&&vr(t[0])});if(e.length>0)return s(e)}function u(){return{ok:f,docs:c}}n=h(n);var c=[],f=!0;return Xr.resolve().then(a).then(o).then(u)}function wr(e,t,n,r,o){return e.get(t).catch(function(n){if(404===n.status)return"http"===e.type()&&T(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:Oi,version:Ti};throw n}).then(function(i){if(!o.cancelled&&i.last_seq!==n)return i.history=(i.history||[]).filter(function(e){return e.session_id!==r}),i.history.unshift({last_seq:n,session_id:r}),i.history=i.history.slice(0,ji),i.version=Ti,i.replicator=Oi,i.session_id=r,i.last_seq=n,e.put(i).catch(function(i){if(409===i.status)return wr(e,t,n,r,o);throw i})})}function Er(e,t,n,r){this.src=e,this.target=t,this.id=n,this.returnValue=r}function kr(e,t){return e.session_id===t.session_id?{last_seq:e.last_seq,history:e.history}:Sr(e.history,t.history)}function Sr(e,t){var n=e[0],r=e.slice(1),o=t[0],i=t.slice(1);if(!n||0===t.length)return{last_seq:Ci,history:[]};var s=n.session_id;if(qr(s,t))return{last_seq:n.last_seq,history:e};var a=o.session_id;return qr(a,r)?{last_seq:o.last_seq,history:i}:Sr(r,i)}function qr(e,t){var n=t[0],r=t.slice(1);return!(!e||0===t.length)&&(e===n.session_id||qr(e,r))}function xr(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function Ar(e,t,n,r){if(e.retry===!1)return t.emit("error",n),void t.removeAllListeners();if("function"!=typeof e.back_off_function&&(e.back_off_function=A),t.emit("requestError",n),"active"===t.state||"pending"===t.state){t.emit("paused",n),t.state="stopped";var o=function(){e.current_back_off=Ii},i=function(){t.removeListener("active",o)};t.once("paused",i),t.once("active",o)}e.current_back_off=e.current_back_off||Ii,e.current_back_off=e.back_off_function(e.current_back_off),setTimeout(r,e.current_back_off)}function Tr(e){return Object.keys(e).sort(bn).reduce(function(t,n){return t[n]=e[n],t},{})}function Or(e,t,n){var r=n.doc_ids?n.doc_ids.sort(bn):"",o=n.filter?n.filter.toString():"",i="",s="";return n.filter&&n.query_params&&(i=JSON.stringify(Tr(n.query_params))),n.filter&&"_view"===n.filter&&(s=n.view.toString()),Xr.all([e.id(),t.id()]).then(function(e){var t=e[0]+e[1]+o+s+i+r;return new Xr(function(e){Xe(t,e)})}).then(function(e){return e=e.replace(/\//g,".").replace(/\+/g,"_"),"_local/"+e})}function jr(e,t,n,r,o){function i(){return k?Xr.resolve():Or(e,t,n).then(function(n){E=n,k=new Er(e,t,E,r)})}function s(){if(N=[],0!==w.docs.length){var e=w.docs,i={timeout:n.timeout};return t.bulkDocs({docs:e,new_edits:!1},i).then(function(t){if(r.cancelled)throw p(),new Error("cancelled");var n=Object.create(null);t.forEach(function(e){e.error&&(n[e.id]=e)});var i=Object.keys(n).length;o.doc_write_failures+=i,o.docs_written+=e.length-i,e.forEach(function(e){var t=n[e._id];if(t){if(o.errors.push(t),"unauthorized"!==t.name&&"forbidden"!==t.name)throw t;r.emit("denied",h(t))}else N.push(e)})},function(t){throw o.doc_write_failures+=e.length,t})}}function a(){if(w.error)throw new Error("There was a problem getting docs.");o.last_seq=O=w.seq;var e=h(o);return N.length&&(e.docs=N,r.emit("change",e)),x=!0,k.writeCheckpoint(w.seq,B).then(function(){if(x=!1,r.cancelled)throw p(),new Error("cancelled");w=void 0,m()}).catch(function(e){throw b(e),e})}function u(){var e={};return w.changes.forEach(function(t){"_user/"!==t.id&&(e[t.id]=t.changes.map(function(e){return e.rev}))}),t.revsDiff(e).then(function(e){if(r.cancelled)throw p(),new Error("cancelled");w.diffs=e})}function c(){return br(e,t,w.diffs,r).then(function(e){w.error=!e.ok,e.docs.forEach(function(e){delete w.diffs[e._id],o.docs_read++,w.docs.push(e)})})}function f(){if(!r.cancelled&&!w){if(0===S.length)return void l(!0);w=S.shift(),u().then(c).then(s).then(a).then(f).catch(function(e){d("batch processing terminated with error",e)})}}function l(e){return 0===q.changes.length?void(0!==S.length||w||((j&&F.live||A)&&(r.state="pending",r.emit("paused")),A&&p())):void((e||A||q.changes.length>=C)&&(S.push(q),q={seq:0,changes:[],docs:[]},"pending"!==r.state&&"stopped"!==r.state||(r.state="active",r.emit("active")),f()))}function d(e,t){T||(t.message||(t.message=e),o.ok=!1,o.status="aborting",S=[],q={seq:0,changes:[],docs:[]},p(t))}function p(i){T||r.cancelled&&(o.status="cancelled",x)||(o.status=o.status||"complete",o.end_time=new Date,o.last_seq=O,T=!0,i?(i.result=o,"unauthorized"===i.name||"forbidden"===i.name?(r.emit("error",i),r.removeAllListeners()):Ar(n,r,i,function(){jr(e,t,n,r)})):(r.emit("complete",o),r.removeAllListeners()))}function v(e){if(r.cancelled)return p();var t=I(n)(e);t&&(q.seq=e.seq,q.changes.push(e),l(0===S.length&&F.live))}function y(e){if(R=!1,r.cancelled)return p();if(e.results.length>0)F.since=e.last_seq,m(),l(!0);else{var t=function(){j?(F.live=!0,m()):A=!0,l(!0)};w||0!==e.results.length?t():(x=!0,k.writeCheckpoint(e.last_seq,B).then(function(){x=!1,o.last_seq=O=e.last_seq,t()}).catch(b))}}function _(e){return R=!1,r.cancelled?p():void d("changes rejected",e)}function m(){function t(){i.cancel()}function o(){r.removeListener("cancel",t)}if(!R&&!A&&S.lengthr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===s&&setTimeout(function(){o()},0),s=!1}).on("error",e)}}if(!this._listeners[t]){var i=this,s=!1;this._listeners[t]=o,this.on(e,o)}},S.prototype.removeListener=function(e,t){t in this._listeners&&(Mr.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},S.prototype.notifyLocalWindows=function(e){w()?chrome.storage.local.set({dbName:e}):E()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},S.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Pr(O,Error),O.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var Zr=(new O({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new O({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"})),eo=new O({status:404,error:"not_found",reason:"missing"}),to=new O({status:409,error:"conflict",reason:"Document update conflict"}),no=new O({status:400,error:"bad_request",reason:"_id field must contain a string"}),ro=new O({status:412,error:"missing_id",reason:"_id is required for puts"}),oo=new O({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),io=new O({status:412,error:"precondition_failed",reason:"Database not open"}),so=new O({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),ao=new O({status:500,error:"badarg",reason:"Some query argument is invalid"}),uo=(new O({status:400,error:"invalid_request",reason:"Request was invalid"}),new O({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"})),co=new O({status:500,error:"doc_validation",reason:"Bad special document member"}),fo=new O({status:400,error:"bad_request",reason:"Something wrong with the request"}),lo=new O({status:400,error:"bad_request",reason:"Document must be a JSON object"}),ho=(new O({status:404,error:"not_found",reason:"Database not found"}),new O({status:500,error:"indexed_db_went_bad",reason:"unknown"})),po=new O({status:500,error:"web_sql_went_bad",reason:"unknown"}),vo=(new O({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new O({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new O({status:400,error:"bad_request",reason:"Invalid rev format"})),yo=(new O({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new O({status:412,error:"missing_stub"})),_o=(new O({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]),mo="queryKey",go=/(?:^|&)([^&=]*)=?([^&]*)/g,bo=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,wo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");Pr(he,Mr.EventEmitter),he.prototype.cancel=function(){this.isCancelled=!0,this.db.taskqueue.isReady&&this.emit("cancel")},he.prototype.doChanges=function(e){var t=this,n=e.complete;if(e=h(e),"live"in e&&!("continuous"in e)&&(e.continuous=e.live),e.processChange=pe,"latest"===e.since&&(e.since="now"),e.since||(e.since=0),"now"===e.since)return void this.db.info().then(function(r){return t.isCancelled?void n(null,{status:"cancelled"}):(e.since=r.update_seq,void t.doChanges(e))},n);if(e.view&&!e.filter&&(e.filter="_view"),e.filter&&"string"==typeof e.filter&&("_view"===e.filter?e.view=F(e.view):e.filter=F(e.filter),"http"!==this.db.type()&&!e.doc_ids))return this.filterChanges(e);"descending"in e||(e.descending=!1),e.limit=0===e.limit?1:e.limit,e.complete=n;var r=this.db._changes(e);if(r&&"function"==typeof r.cancel){var o=t.cancel;t.cancel=Hr(function(e){r.cancel(),o.apply(this,e)})}},he.prototype.filterChanges=function(e){var t=this,n=e.complete;if("_view"===e.filter){if(!e.view||"string"!=typeof e.view){var r=j(fo,"`view` filter parameter not found or invalid.");return n(r)}var o=B(e.view);this.db.get("_design/"+o[0],function(r,i){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(C(r));var s=i&&i.views&&i.views[o[1]]&&i.views[o[1]].map;return s?(e.filter=le(s),void t.doChanges(e)):n(j(eo,i.views?"missing json key: "+o[1]:"missing json key: views"))})}else{var i=B(e.filter);if(!i)return t.doChanges(e);this.db.get("_design/"+i[0],function(r,o){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(C(r));var s=o&&o.filters&&o.filters[i[1]];return s?(e.filter=fe(s),void t.doChanges(e)):n(j(eo,o&&o.filters?"missing json key: "+i[1]:"missing json key: filters"))})}},Pr(Se,Mr.EventEmitter),Se.prototype.post=y("post",function(e,t,n){return"function"==typeof t&&(n=t,t={}),"object"!=typeof e||Array.isArray(e)?n(j(lo)):void this.bulkDocs({docs:[e]},t,_e(n))}),Se.prototype.put=y("put",function(e,t,n){return"function"==typeof t&&(n=t,t={}),"object"!=typeof e||Array.isArray(e)?n(j(lo)):(D(e._id),ce(e._id)&&"function"==typeof this._putLocal?e._deleted?this._removeLocal(e,n):this._putLocal(e,n):void("function"==typeof this._put&&t.new_edits!==!1?this._put(e,t,n):this.bulkDocs({docs:[e]},t,_e(n))))}),Se.prototype.putAttachment=y("putAttachment",function(e,t,n,r,o){function i(e){var n="_rev"in e?parseInt(e._rev,10):0;return e._attachments=e._attachments||{},e._attachments[t]={content_type:o,data:r,revpos:++n},s.put(e)}var s=this;return"function"==typeof o&&(o=r,r=n,n=null),"undefined"==typeof o&&(o=r,r=n,n=null),s.get(e).then(function(e){if(e._rev!==n)throw j(to);return i(e)},function(t){if(t.reason===eo.message)return i({_id:e});throw t})}),Se.prototype.removeAttachment=y("removeAttachment",function(e,t,n,r){ -var o=this;o.get(e,function(e,i){return e?void r(e):i._rev!==n?void r(j(to)):i._attachments?(delete i._attachments[t],0===Object.keys(i._attachments).length&&delete i._attachments,void o.put(i,r)):r()})}),Se.prototype.remove=y("remove",function(e,t,n,r){var o;"string"==typeof t?(o={_id:e,_rev:t},"function"==typeof n&&(r=n,n={})):(o=e,"function"==typeof t?(r=t,n={}):(r=n,n=t)),n=n||{},n.was_delete=!0;var i={_id:o._id,_rev:o._rev||n.rev};return i._deleted=!0,ce(i._id)&&"function"==typeof this._removeLocal?this._removeLocal(o,r):void this.bulkDocs({docs:[i]},n,_e(r))}),Se.prototype.revsDiff=y("revsDiff",function(e,t,n){function r(e,t){u.has(e)||u.set(e,{missing:[]}),u.get(e).missing.push(t)}function o(t,n){var o=e[t].slice(0);K(n,function(e,n,i,s,a){var u=n+"-"+i,c=o.indexOf(u);c!==-1&&(o.splice(c,1),"available"!==a.status&&r(t,u))}),o.forEach(function(e){r(t,e)})}"function"==typeof t&&(n=t,t={});var i=Object.keys(e);if(!i.length)return n(null,{});var s=0,u=new a;i.map(function(t){this._getRevisionTree(t,function(r,a){if(r&&404===r.status&&"missing"===r.message)u.set(t,{missing:e[t]});else{if(r)return n(r);o(t,a)}if(++s===i.length){var c={};return u.forEach(function(e,t){c[t]=e}),n(null,c)}})},this)}),Se.prototype.bulkGet=y("bulkGet",function(e,t){b(this,e,t)}),Se.prototype.compactDocument=y("compactDocument",function(e,t,n){var r=this;this._getRevisionTree(e,function(o,i){if(o)return n(o);var s=be(i),a=[],u=[];Object.keys(s).forEach(function(e){s[e]>t&&a.push(e)}),K(i,function(e,t,n,r,o){var i=t+"-"+n;"available"===o.status&&a.indexOf(i)!==-1&&u.push(i)}),r._doCompaction(e,u,n)})}),Se.prototype.compact=y("compact",function(e,t){"function"==typeof e&&(t=e,e={});var n=this;e=e||{},n._compactionQueue=n._compactionQueue||[],n._compactionQueue.push({opts:e,callback:t}),1===n._compactionQueue.length&&Ee(n)}),Se.prototype._compact=function(e,t){function n(e){s.push(o.compactDocument(e.id,0))}function r(e){var n=e.last_seq;Xr.all(s).then(function(){return U(o,"_local/compaction",function(e){return(!e.last_seq||e.last_seq0;){var e=w.pop();e(null,g)}}function l(e,t){if(0===t){var n="CREATE TABLE IF NOT EXISTS "+Go+" (dbid, db_version INTEGER)",c="CREATE TABLE IF NOT EXISTS "+zo+" (digest UNIQUE, escaped TINYINT(1), body BLOB)",l="CREATE TABLE IF NOT EXISTS "+Vo+" (digest, seq INTEGER)",d="CREATE TABLE IF NOT EXISTS "+Jo+" (id unique, json, winningseq, max_seq INTEGER UNIQUE)",h="CREATE TABLE IF NOT EXISTS "+Ko+" (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, json, deleted TINYINT(1), doc_id, rev)",p="CREATE TABLE IF NOT EXISTS "+Xo+" (id UNIQUE, rev, json)";e.executeSql(c),e.executeSql(p),e.executeSql(l,[],function(){e.executeSql(ni),e.executeSql(ri)}),e.executeSql(d,[],function(){e.executeSql(ti),e.executeSql(h,[],function(){e.executeSql(Zo),e.executeSql(ei),e.executeSql(n,[],function(){var t="INSERT INTO "+Go+" (db_version, dbid) VALUES (?,?)";g=W();var n=[Wo,g];e.executeSql(t,n,function(){f()})})})})}else{var v=function(){var n=t=")+" ?"),l.push(o)),i!==!1){var h=a?">":"<";f&&(h+="="),d.push(Jo+".id "+h+" ?"),l.push(i)}s!==!1&&(d.push(Jo+".id = ?"),l.push(s))}"ok"!==e.deleted&&d.push(Ko+".deleted = 0"),q.readTransaction(function(t){y(t,function(o){if(n=o,0!==u){var i=Bt(ii,[Jo,Ko],oi,d,Jo+".id "+(a?"DESC":"ASC"));i+=" LIMIT "+u+" OFFSET "+c,t.executeSql(i,l,function(t,n){for(var o=0,i=n.rows.length;o ?"],f=[e.since];e.doc_ids&&(c.push(Jo+".id IN "+Nt(e.doc_ids.length)),f=f.concat(e.doc_ids));var l="maxSeq "+(r?"DESC":"ASC"),d=Bt(t,n,u,c,l),h=I(e);e.view||e.filter||(d+=" LIMIT "+o);var p=e.since||0;q.readTransaction(function(t){t.executeSql(d,f,function(t,n){function r(t){return function(){e.onChange(t)}}for(var u=0,c=n.rows.length;u0&&(r=setTimeout(function(){n.reject(new Error("Load timeout for resource: "+e.url))},e.timeout)),n.promise.then(function(t){return o={statusCode:t.status},e.timeout>0&&clearTimeout(r),o.statusCode>=200&&o.statusCode<300?e.binary?t.blob():t.text():t.json()}).then(function(e){o.statusCode>=200&&o.statusCode<300?t(null,o,e):t(e,o)}).catch(function(e){t(e,o)}),{abort:n.reject}}function tn(e,t){var n,r,o=!1,i=function(){n.abort(),u()},s=function(){o=!0,n.abort(),u()},a={abort:i},u=function(){clearTimeout(r),a.abort=function(){},n&&(n.onprogress=void 0,n.upload&&(n.upload.onprogress=void 0),n.onreadystatechange=void 0,n=void 0)};n=e.xhr?new e.xhr:new XMLHttpRequest;try{n.open(e.method,e.url)}catch(e){return t(new Error(e.name||"Url is invalid"))}n.withCredentials=!("withCredentials"in e)||e.withCredentials,"GET"===e.method?delete e.headers["Content-Type"]:e.json&&(e.headers.Accept="application/json",e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json",e.body&&e.processData&&"string"!=typeof e.body&&(e.body=JSON.stringify(e.body))),e.binary&&(n.responseType="arraybuffer"),"body"in e||(e.body=null);for(var c in e.headers)e.headers.hasOwnProperty(c)&&n.setRequestHeader(c,e.headers[c]);return e.timeout>0&&(r=setTimeout(s,e.timeout),n.onprogress=function(){clearTimeout(r),4!==n.readyState&&(r=setTimeout(s,e.timeout))},"undefined"!=typeof n.upload&&(n.upload.onprogress=n.onprogress)),n.onreadystatechange=function(){if(4===n.readyState){var r={statusCode:n.status};if(n.status>=200&&n.status<300){var i;i=e.binary?Re([n.response||""],{type:n.getResponseHeader("Content-Type")}):n.responseText,t(null,r,i)}else{var s={};if(o)s=new Error("ETIMEDOUT"),s.code="ETIMEDOUT";else if("string"==typeof n.response)try{s=JSON.parse(n.response)}catch(e){}s.status=n.status,t(s)}u()}},e.body&&e.body instanceof Blob?He(e.body,function(e){n.send(e)}):n.send(e.body),a}function nn(){try{return new XMLHttpRequest,!0}catch(e){return!1}}function rn(e,t){return si||e.xhr?tn(e,t):en(e,t)}function on(){return""}function sn(e,t){function n(t,n,r){if(!e.binary&&e.json&&"string"==typeof t)try{t=JSON.parse(t)}catch(e){return r(e)}Array.isArray(t)&&(t=t.map(function(e){return e.error||e.missing?C(e):e})),e.binary&&ai(t,n),r(null,t,n)}e=h(e);var r={method:"GET",headers:{},json:!0,processData:!0,timeout:1e4,cache:!1};return e=Br.extend(r,e),e.json&&(e.binary||(e.headers.Accept="application/json"),e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json"),e.binary&&(e.encoding=null,e.json=!1),e.processData||(e.json=!1),rn(e,function(r,o,i){if(r)return t(C(r));var s,a=o.headers&&o.headers["content-type"],u=i||on();if(!e.binary&&(e.json||!e.processData)&&"object"!=typeof u&&(/json/.test(a)||/^[\s]*\{/.test(u)&&/\}[\s]*$/.test(u)))try{u=JSON.parse(u.toString())}catch(e){}o.statusCode>=200&&o.statusCode<300?n(u,o,t):(s=C(u),s.status=o.statusCode,t(s))})}function an(e,t){var n=navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",r=n.indexOf("safari")!==-1&&n.indexOf("chrome")===-1,o=n.indexOf("msie")!==-1,i=n.indexOf("edge")!==-1,s=r||(o||i)&&"GET"===e.method,a=!("cache"in e)||e.cache,u=/^blob:/.test(e.url);if(!u&&(s||!a)){var c=e.url.indexOf("?")!==-1;e.url+=(c?"&":"?")+"_nonce="+Date.now()}return sn(e,t)}function un(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];n.data=Be(n.data,n.content_type)})}function cn(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):/^_local/.test(e)?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function fn(e){return e._attachments&&Object.keys(e._attachments)?Xr.all(Object.keys(e._attachments).map(function(t){var n=e._attachments[t];if(n.data&&"string"!=typeof n.data)return new Xr(function(e){Me(n.data,e)}).then(function(e){n.data=e})})):Xr.resolve()}function ln(e){if(!e.prefix)return!1;var t=P(e.prefix).protocol;return"http"===t||"https"===t}function dn(e,t){if(ln(t)){var n=t.name.substr(t.prefix.length);e=t.prefix+encodeURIComponent(n)}var r=P(e);(r.user||r.password)&&(r.auth={username:r.user,password:r.password});var o=r.path.replace(/(^\/|\/$)/g,"").split("/");return r.db=o.pop(),r.db.indexOf("%")===-1&&(r.db=encodeURIComponent(r.db)),r.path=o.join("/"),r}function hn(e,t){return pn(e,e.db+"/"+t)}function pn(e,t){var n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function vn(e){return"?"+Object.keys(e).map(function(t){return t+"="+encodeURIComponent(e[t])}).join("&")}function yn(e,t){function n(e,t,n){var r=e.ajax||{},o=Br.extend(h(f),r,t);return li(o.method+" "+o.url),a._ajax(o,n)}function r(e,t){return new Xr(function(r,o){n(e,t,function(e,t){return e?o(e):void r(t)})})}function o(e,t){return y(e,Hr(function(e){i().then(function(){return t.apply(this,e)}).catch(function(t){var n=e.pop();n(t)})}))}function i(){if(e.skipSetup||e.skip_setup)return Xr.resolve();if(v)return v;var t={method:"GET",url:c};return v=r({},t).catch(function(e){return e&&e.status&&404===e.status?(T(404,"PouchDB is just detecting if the remote exists."),r({},{method:"PUT",url:c})):Xr.reject(e)}).catch(function(e){return!(!e||!e.status||412!==e.status)||Xr.reject(e)}),v.catch(function(){v=null}),v}function s(e){return e.split("/").map(encodeURIComponent).join("/")}var a=this,u=dn(e.name,e),c=hn(u,"");e=h(e);var f=e.ajax||{};if(e.auth||u.auth){var l=e.auth||u.auth,d=l.username+":"+l.password,p=To(unescape(encodeURIComponent(d)));f.headers=f.headers||{},f.headers.Authorization="Basic "+p}a._ajax=an;var v;setTimeout(function(){t(null,a)}),a.type=function(){return"http"},a.id=o("id",function(e){n({},{method:"GET",url:pn(u,"")},function(t,n){var r=n&&n.uuid?n.uuid+u.db:hn(u,"");e(null,r)})}),a.request=o("request",function(e,t){e.url=hn(u,e.url),n({},e,t)}),a.compact=o("compact",function(e,t){"function"==typeof e&&(t=e,e={}),e=h(e),n(e,{url:hn(u,"_compact"),method:"POST"},function(){function n(){a.info(function(r,o){o&&!o.compact_running?t(null,{ok:!0}):setTimeout(n,e.interval||200)})}n()})}),a.bulkGet=y("bulkGet",function(e,t){function r(t){var r={};e.revs&&(r.revs=!0),e.attachments&&(r.attachments=!0),n({},{url:hn(u,"_bulk_get"+vn(r)),method:"POST",body:{docs:e.docs}},t)}function o(){function n(e){return function(n,r){a[e]=r.results,++s===o&&t(null,{results:R(a)})}}for(var r=ci,o=Math.ceil(e.docs.length/r),s=0,a=new Array(o),u=0;ut?t:a;var f={method:d,url:hn(u,"_changes"+vn(o)),timeout:e.timeout,body:l};v=r,e.aborted||i().then(function(){p=n(e,f,c)}).catch(c)}},_={results:[]},m=function(n,o){if(!e.aborted){var i=0;if(o&&o.results){i=o.results.length,_.last_seq=o.last_seq;var u={};u.query=e.query_params,o.results=o.results.filter(function(t){a--;var n=I(e)(t);return n&&(e.include_docs&&e.attachments&&e.binary&&un(t),r&&_.results.push(t),e.onChange(t)),n})}else if(n)return e.aborted=!0,void e.complete(n);o&&o.last_seq&&(v=o.last_seq);var c=s&&a<=0||o&&it.length?1:-1}function Tn(e,t){return e===t?0:e>t?1:-1}function On(e,t){for(var n=Object.keys(e),r=Object.keys(t),o=Math.min(n.length,r.length),i=0;ir.length?1:-1}function jn(e){var t=["boolean","number","string","object"],n=t.indexOf(typeof e);return~n?null===e?1:Array.isArray(e)?5:n<3?n+2:n+3:Array.isArray(e)?5:void 0}function Cn(e){if(0===e)return"1";var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=e<0,o=r?"0":"2",i=(r?-n:n)-di,s=gn(i.toString(),"0",hi);o+=pi+s;var a=Math.abs(parseFloat(t[0]));r&&(a=10-a);var u=a.toFixed(20);return u=u.replace(/\.?0+$/,""),o+=pi+u}function Ln(){this.promise=new Xr(function(e){e()})}function In(e){var t,n=e.db,r=e.viewName,o=e.map,i=e.reduce,s=e.temporary,a=o.toString()+(i&&i.toString())+"undefined";if(!s&&(t=n._cachedViews=n._cachedViews||{},t[a]))return t[a];var u=n.info().then(function(e){function u(e){e.views=e.views||{};var t=r;t.indexOf("/")===-1&&(t=r+"/"+r);var n=e.views[t]=e.views[t]||{};if(!n[c])return n[c]=!0,e}var c=e.db_name+"-mrview-"+(s?"temp":Ge(a));return U(n,"_local/mrviews",u).then(function(){return n.registerDependentDatabase(c).then(function(e){var r=e.db;r.auto_compaction=!0;var s={name:c,db:r,sourceDB:n,adapter:n.adapter,mapFun:o,reduceFun:i};return s.db.get("_local/lastSeq").catch(function(e){if(404!==e.status)throw e}).then(function(e){return s.seq=e?e.seq:0,t&&s.db.once("destroyed",function(){delete t[a]}),s})})})});return t&&(t[a]=u),u}function Rn(e){this.status=400,this.name="query_parse_error",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Rn)}catch(e){}}function Dn(e){this.status=404,this.name="not_found",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Dn)}catch(e){}}function Nn(e){this.status=500,this.name="invalid_value",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Nn)}catch(e){}}function Bn(e){var t="builtin "+e+" function requires map values to be numbers or number arrays";return new Nn(t)}function Fn(e){for(var t=0,n=0,r=e.length;n0?e.slice(n):e}function zn(e){var t=e.value,n=t&&"object"==typeof t&&t._id||e.id;return n}function Xn(e){e.rows.forEach(function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];t[e].data=Be(n.data,n.content_type)})})}function Gn(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&Xn(t),t}}function Vn(e,t,n,r){var o=t[e];"undefined"!=typeof o&&(r&&(o=encodeURIComponent(JSON.stringify(o))),n.push(e+"="+o))}function Qn(e){if("undefined"!=typeof e){var t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function $n(e){return e.group_level=Qn(e.group_level),e.limit=Qn(e.limit),e.skip=Qn(e.skip),e}function Yn(e){if(e){if("number"!=typeof e)return new Rn('Invalid value for integer: "'+e+'"');if(e<0)return new Rn('Invalid value for positive integer: "'+e+'"')}}function Zn(e,t){var n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if("undefined"!=typeof e[n]&&"undefined"!=typeof e[r]&&bn(e[n],e[r])>0)throw new Rn("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new Rn("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new Rn("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach(function(t){var n=Yn(e[t]);if(n)throw n})}function er(e,t,n){var r,o=[],i="GET";if(Vn("reduce",n,o),Vn("include_docs",n,o),Vn("attachments",n,o),Vn("limit",n,o),Vn("descending",n,o),Vn("group",n,o),Vn("group_level",n,o),Vn("skip",n,o),Vn("stale",n,o),Vn("conflicts",n,o),Vn("startkey",n,o,!0),Vn("start_key",n,o,!0),Vn("endkey",n,o,!0),Vn("end_key",n,o,!0),Vn("inclusive_end",n,o),Vn("key",n,o,!0),o=o.join("&"),o=""===o?"":"?"+o,"undefined"!=typeof n.keys){var s=2e3,a="keys="+encodeURIComponent(JSON.stringify(n.keys));a.length+o.length+1<=s?o+=("?"===o[0]?"&":"?")+a:(i="POST","string"==typeof t?r={keys:n.keys}:t.keys=n.keys)}if("string"==typeof t){var u=Un(t);return e.request({method:i,url:"_design/"+u[0]+"/_view/"+u[1]+o,body:r}).then(Gn(n))}return r=r||{},Object.keys(t).forEach(function(e){Array.isArray(t[e])?r[e]=t[e]:r[e]=t[e].toString()}),e.request({method:"POST",url:"_temp_view"+o,body:r}).then(Gn(n))}function tr(e,t,n){return new Xr(function(r,o){e._query(t,n,function(e,t){return e?o(e):void r(t)})})}function nr(e){return new Xr(function(t,n){e._viewCleanup(function(e,r){return e?n(e):void t(r)})})}function rr(e){return function(t){if(404===t.status)return e;throw t}}function or(e,t,n){function r(){return Mn(f)?Xr.resolve(a):t.db.get(s).catch(rr(a))}function o(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Xr.resolve({rows:[]})}function i(e,t){for(var n=[],r={},o=0,i=t.rows.length;on))return e.doc.value}var r=xn(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}})})}function r(n){var r;if(r=i?cr(e,n,t):{total_rows:o,offset:s,rows:n},t.include_docs){var a=Ei(n.map(zn));return e.sourceDB.allDocs({keys:a,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}).then(function(e){var t={};return e.rows.forEach(function(e){e.doc&&(t["$"+e.id]=e.doc)}),n.forEach(function(e){var n=zn(e),r=t["$"+n];r&&(e.doc=r)}),r})}return r}var o,i=e.reduceFun&&t.reduce!==!1,s=t.skip||0;if("undefined"==typeof t.keys||t.keys.length||(t.limit=0,delete t.keys),"undefined"!=typeof t.keys){var a=t.keys,u=a.map(function(e){var t={startkey:kn([e]),endkey:kn([e,{}])};return n(t)});return Xr.all(u).then(R).then(r)}var c={descending:t.descending};if(t.start_key&&(t.startkey=t.start_key),t.end_key&&(t.endkey=t.end_key),"undefined"!=typeof t.startkey&&(c.startkey=kn(t.descending?[t.startkey,{}]:[t.startkey])),"undefined"!=typeof t.endkey){var f=t.inclusive_end!==!1;t.descending&&(f=!f),c.endkey=kn(f?[t.endkey,{}]:[t.endkey])}if("undefined"!=typeof t.key){var l=kn([t.key]),d=kn([t.key,{}]);c.descending?(c.endkey=l,c.startkey=d):(c.startkey=l,c.endkey=d)}return i||("number"==typeof t.limit&&(c.limit=t.limit),c.skip=s),n(c).then(r)}function dr(e){return e.request({method:"POST",url:"_view_cleanup"})}function hr(e){return e.get("_local/mrviews").then(function(t){var n={};Object.keys(t.views).forEach(function(e){var t=Un(e),r="_design/"+t[0],o=t[1];n[r]=n[r]||{},n[r][o]=!0});var r={keys:Object.keys(n),include_docs:!0};return e.allDocs(r).then(function(r){var o={};r.rows.forEach(function(e){var r=e.key.substring(8);Object.keys(n[e.key]).forEach(function(n){var i=r+"/"+n;t.views[i]||(i=n);var s=Object.keys(t.views[i]),a=e.doc&&e.doc.views&&e.doc.views[n];s.forEach(function(e){o[e]=o[e]||a})})});var i=Object.keys(o).filter(function(e){return!o[e]}),s=i.map(function(t){return wi(sr(t),function(){return new e.constructor(t,e.__opts).destroy()})()});return Xr.all(s).then(function(){return{ok:!0}})})},rr({ok:!0}))}function pr(e,t,r){if("http"===e.type())return er(e,t,r);if("function"==typeof e._query)return tr(e,t,r);if("string"!=typeof t){Zn(r,t);var o={db:e,viewName:"temp_view/temp_view",map:t.map,reduce:t.reduce,temporary:!0};return Si.add(function(){return In(o).then(function(e){function t(){return e.db.destroy()}return bi(ar(e).then(function(){return fr(e,r)}),t)})}),Si.finish()}var i=t,s=Un(i),a=s[0],u=s[1];return e.get("_design/"+a).then(function(t){var o=t.views&&t.views[u];if(!o||"string"!=typeof o.map)throw new Dn("ddoc "+a+" has no view named "+u);Zn(r,o);var s={db:e,viewName:i,map:o.map,reduce:o.reduce};return In(s).then(function(e){return"ok"===r.stale||"update_after"===r.stale?("update_after"===r.stale&&n.nextTick(function(){ar(e)}),fr(e,r)):ar(e).then(function(){return fr(e,r)})})})}function vr(e){return/^1-/.test(e)}function yr(e,t,n){return!e._attachments||!e._attachments[n]||e._attachments[n].digest!==t._attachments[n].digest}function _r(e,t){var n=Object.keys(t._attachments);return Xr.all(n.map(function(n){return e.getAttachment(t._id,n,{rev:t._rev})}))}function mr(e,t,n){var r="http"===t.type()&&"http"!==e.type(),o=Object.keys(n._attachments);return r?e.get(n._id).then(function(r){return Xr.all(o.map(function(o){return yr(r,n,o)?t.getAttachment(n._id,o):e.getAttachment(r._id,o)}))}).catch(function(e){if(404!==e.status)throw e;return _r(t,n)}):_r(t,n)}function gr(e){var t=[];return Object.keys(e).forEach(function(n){var r=e[n].missing;r.forEach(function(e){t.push({id:n,rev:e})})}),{docs:t,revs:!0}}function br(e,t,n,r){function o(){var o=gr(n);if(o.docs.length)return e.bulkGet(o).then(function(n){if(r.cancelled)throw new Error("cancelled");return Xr.all(n.results.map(function(n){return Xr.all(n.docs.map(function(n){var r=n.ok;return n.error&&(f=!1),r&&r._attachments?mr(t,e,r).then(function(e){var t=Object.keys(r._attachments);return e.forEach(function(e,n){var o=r._attachments[t[n]];delete o.stub,delete o.length,o.data=e}),r}):r}))})).then(function(e){c=c.concat(R(e).filter(Boolean))})})}function i(e){return e._attachments&&Object.keys(e._attachments).length>0}function s(t){return e.allDocs({keys:t,include_docs:!0}).then(function(e){if(r.cancelled)throw new Error("cancelled");e.rows.forEach(function(e){!e.deleted&&e.doc&&vr(e.value.rev)&&!i(e.doc)&&(c.push(e.doc),delete n[e.id])})})}function a(){var e=Object.keys(n).filter(function(e){var t=n[e].missing;return 1===t.length&&vr(t[0])});if(e.length>0)return s(e)}function u(){return{ok:f,docs:c}}n=h(n);var c=[],f=!0;return Xr.resolve().then(a).then(o).then(u)}function wr(e,t,n,r,o){return e.get(t).catch(function(n){if(404===n.status)return"http"===e.type()&&T(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:Ci,version:ji};throw n}).then(function(i){if(!o.cancelled&&i.last_seq!==n)return i.history=(i.history||[]).filter(function(e){return e.session_id!==r}),i.history.unshift({last_seq:n,session_id:r}),i.history=i.history.slice(0,Li),i.version=ji,i.replicator=Ci,i.session_id=r,i.last_seq=n,e.put(i).catch(function(i){if(409===i.status)return wr(e,t,n,r,o);throw i})})}function Er(e,t,n,r){this.src=e,this.target=t,this.id=n,this.returnValue=r}function kr(e,t){return e.session_id===t.session_id?{last_seq:e.last_seq,history:e.history}:Sr(e.history,t.history)}function Sr(e,t){var n=e[0],r=e.slice(1),o=t[0],i=t.slice(1);if(!n||0===t.length)return{last_seq:Ii,history:[]};var s=n.session_id;if(qr(s,t))return{last_seq:n.last_seq,history:e};var a=o.session_id;return qr(a,r)?{last_seq:o.last_seq,history:i}:Sr(r,i)}function qr(e,t){var n=t[0],r=t.slice(1);return!(!e||0===t.length)&&(e===n.session_id||qr(e,r))}function xr(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function Ar(e,t,n,r){if(e.retry===!1)return t.emit("error",n),void t.removeAllListeners();if("function"!=typeof e.back_off_function&&(e.back_off_function=A),t.emit("requestError",n),"active"===t.state||"pending"===t.state){t.emit("paused",n),t.state="stopped";var o=function(){e.current_back_off=Di},i=function(){t.removeListener("active",o)};t.once("paused",i),t.once("active",o)}e.current_back_off=e.current_back_off||Di,e.current_back_off=e.back_off_function(e.current_back_off),setTimeout(r,e.current_back_off)}function Tr(e){return Object.keys(e).sort(bn).reduce(function(t,n){return t[n]=e[n],t},{})}function Or(e,t,n){var r=n.doc_ids?n.doc_ids.sort(bn):"",o=n.filter?n.filter.toString():"",i="",s="";return n.filter&&n.query_params&&(i=JSON.stringify(Tr(n.query_params))),n.filter&&"_view"===n.filter&&(s=n.view.toString()),Xr.all([e.id(),t.id()]).then(function(e){var t=e[0]+e[1]+o+s+i+r;return new Xr(function(e){Xe(t,e)})}).then(function(e){return e=e.replace(/\//g,".").replace(/\+/g,"_"),"_local/"+e})}function jr(e,t,n,r,o){function i(){return k?Xr.resolve():Or(e,t,n).then(function(n){E=n,k=new Er(e,t,E,r)})}function s(){if(N=[],0!==w.docs.length){var e=w.docs,i={timeout:n.timeout};return t.bulkDocs({docs:e,new_edits:!1},i).then(function(t){if(r.cancelled)throw p(),new Error("cancelled");var n=Object.create(null);t.forEach(function(e){e.error&&(n[e.id]=e)});var i=Object.keys(n).length;o.doc_write_failures+=i,o.docs_written+=e.length-i,e.forEach(function(e){var t=n[e._id];if(t){if(o.errors.push(t),"unauthorized"!==t.name&&"forbidden"!==t.name)throw t;r.emit("denied",h(t))}else N.push(e)})},function(t){throw o.doc_write_failures+=e.length,t})}}function a(){if(w.error)throw new Error("There was a problem getting docs.");o.last_seq=O=w.seq;var e=h(o);return N.length&&(e.docs=N,r.emit("change",e)),x=!0,k.writeCheckpoint(w.seq,B).then(function(){if(x=!1,r.cancelled)throw p(),new Error("cancelled");w=void 0,m()}).catch(function(e){throw b(e),e})}function u(){var e={};return w.changes.forEach(function(t){"_user/"!==t.id&&(e[t.id]=t.changes.map(function(e){return e.rev}))}),t.revsDiff(e).then(function(e){if(r.cancelled)throw p(),new Error("cancelled");w.diffs=e})}function c(){return br(e,t,w.diffs,r).then(function(e){w.error=!e.ok,e.docs.forEach(function(e){delete w.diffs[e._id],o.docs_read++,w.docs.push(e)})})}function f(){if(!r.cancelled&&!w){if(0===S.length)return void l(!0);w=S.shift(),u().then(c).then(s).then(a).then(f).catch(function(e){d("batch processing terminated with error",e)})}}function l(e){return 0===q.changes.length?void(0!==S.length||w||((j&&F.live||A)&&(r.state="pending",r.emit("paused")),A&&p())):void((e||A||q.changes.length>=C)&&(S.push(q),q={seq:0,changes:[],docs:[]},"pending"!==r.state&&"stopped"!==r.state||(r.state="active",r.emit("active")),f()))}function d(e,t){T||(t.message||(t.message=e),o.ok=!1,o.status="aborting",S=[],q={seq:0,changes:[],docs:[]},p(t))}function p(i){T||r.cancelled&&(o.status="cancelled",x)||(o.status=o.status||"complete",o.end_time=new Date,o.last_seq=O,T=!0,i?(i.result=o,"unauthorized"===i.name||"forbidden"===i.name?(r.emit("error",i),r.removeAllListeners()):Ar(n,r,i,function(){jr(e,t,n,r)})):(r.emit("complete",o),r.removeAllListeners()))}function v(e){if(r.cancelled)return p();var t=I(n)(e);t&&(q.seq=e.seq,q.changes.push(e),l(0===S.length&&F.live))}function y(e){if(R=!1,r.cancelled)return p();if(e.results.length>0)F.since=e.last_seq,m(),l(!0);else{var t=function(){j?(F.live=!0,m()):A=!0,l(!0)};w||0!==e.results.length?t():(x=!0,k.writeCheckpoint(e.last_seq,B).then(function(){x=!1,o.last_seq=O=e.last_seq,t()}).catch(b))}}function _(e){return R=!1,r.cancelled?p():void d("changes rejected",e)}function m(){function t(){i.cancel()}function o(){r.removeListener("cancel",t)}if(!R&&!A&&S.lengthr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===s&&setTimeout(function(){o()},0),s=!1}).on("error",e)}}if(!this._listeners[t]){var i=this,s=!1;this._listeners[t]=o,this.on(e,o)}},S.prototype.removeListener=function(e,t){t in this._listeners&&(Mr.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},S.prototype.notifyLocalWindows=function(e){w()?chrome.storage.local.set({dbName:e}):E()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},S.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)},Pr(O,Error),O.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var Zr=(new O({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),new O({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"})),eo=new O({status:404,error:"not_found",reason:"missing"}),to=new O({status:409,error:"conflict",reason:"Document update conflict"}),no=new O({status:400,error:"bad_request",reason:"_id field must contain a string"}),ro=new O({status:412,error:"missing_id",reason:"_id is required for puts"}),oo=new O({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),io=new O({status:412,error:"precondition_failed",reason:"Database not open"}),so=new O({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),ao=new O({status:500,error:"badarg",reason:"Some query argument is invalid"}),uo=(new O({status:400,error:"invalid_request",reason:"Request was invalid"}),new O({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"})),co=new O({status:500,error:"doc_validation",reason:"Bad special document member"}),fo=new O({status:400,error:"bad_request",reason:"Something wrong with the request"}),lo=new O({status:400,error:"bad_request",reason:"Document must be a JSON object"}),ho=(new O({status:404,error:"not_found",reason:"Database not found"}),new O({status:500,error:"indexed_db_went_bad",reason:"unknown"})),po=new O({status:500,error:"web_sql_went_bad",reason:"unknown"}),vo=(new O({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),new O({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),new O({status:400,error:"bad_request",reason:"Invalid rev format"})),yo=(new O({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),new O({status:412,error:"missing_stub"})),_o=(new O({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]),mo="queryKey",go=/(?:^|&)([^&=]*)=?([^&]*)/g,bo=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,wo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");Pr(he,Mr.EventEmitter),he.prototype.cancel=function(){this.isCancelled=!0,this.db.taskqueue.isReady&&this.emit("cancel")},he.prototype.doChanges=function(e){var t=this,n=e.complete;if(e=h(e),"live"in e&&!("continuous"in e)&&(e.continuous=e.live),e.processChange=pe,"latest"===e.since&&(e.since="now"),e.since||(e.since=0),"now"===e.since)return void this.db.info().then(function(r){return t.isCancelled?void n(null,{status:"cancelled"}):(e.since=r.update_seq,void t.doChanges(e))},n);if(e.view&&!e.filter&&(e.filter="_view"),e.filter&&"string"==typeof e.filter&&("_view"===e.filter?e.view=F(e.view):e.filter=F(e.filter),"http"!==this.db.type()&&!e.doc_ids))return this.filterChanges(e);"descending"in e||(e.descending=!1),e.limit=0===e.limit?1:e.limit,e.complete=n;var r=this.db._changes(e);if(r&&"function"==typeof r.cancel){var o=t.cancel;t.cancel=Hr(function(e){r.cancel(),o.apply(this,e)})}},he.prototype.filterChanges=function(e){var t=this,n=e.complete;if("_view"===e.filter){if(!e.view||"string"!=typeof e.view){var r=j(fo,"`view` filter parameter not found or invalid.");return n(r)}var o=B(e.view);this.db.get("_design/"+o[0],function(r,i){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(C(r));var s=i&&i.views&&i.views[o[1]]&&i.views[o[1]].map;return s?(e.filter=le(s),void t.doChanges(e)):n(j(eo,i.views?"missing json key: "+o[1]:"missing json key: views"))})}else{var i=B(e.filter);if(!i)return t.doChanges(e);this.db.get("_design/"+i[0],function(r,o){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(C(r));var s=o&&o.filters&&o.filters[i[1]];return s?(e.filter=fe(s),void t.doChanges(e)):n(j(eo,o&&o.filters?"missing json key: "+i[1]:"missing json key: filters"))})}},Pr(Se,Mr.EventEmitter),Se.prototype.post=y("post",function(e,t,n){return"function"==typeof t&&(n=t,t={}),"object"!=typeof e||Array.isArray(e)?n(j(lo)):void this.bulkDocs({docs:[e]},t,_e(n))}),Se.prototype.put=y("put",function(e,t,n){return"function"==typeof t&&(n=t,t={}),"object"!=typeof e||Array.isArray(e)?n(j(lo)):(D(e._id),ce(e._id)&&"function"==typeof this._putLocal?e._deleted?this._removeLocal(e,n):this._putLocal(e,n):void("function"==typeof this._put&&t.new_edits!==!1?this._put(e,t,n):this.bulkDocs({docs:[e]},t,_e(n))))}),Se.prototype.putAttachment=y("putAttachment",function(e,t,n,r,o){function i(e){var n="_rev"in e?parseInt(e._rev,10):0;return e._attachments=e._attachments||{},e._attachments[t]={content_type:o,data:r,revpos:++n},s.put(e)}var s=this;return"function"==typeof o&&(o=r,r=n,n=null),"undefined"==typeof o&&(o=r,r=n,n=null),s.get(e).then(function(e){if(e._rev!==n)throw j(to);return i(e)},function(t){if(t.reason===eo.message)return i({_id:e});throw t})}),Se.prototype.removeAttachment=y("removeAttachment",function(e,t,n,r){var o=this;o.get(e,function(e,i){return e?void r(e):i._rev!==n?void r(j(to)):i._attachments?(delete i._attachments[t], +0===Object.keys(i._attachments).length&&delete i._attachments,void o.put(i,r)):r()})}),Se.prototype.remove=y("remove",function(e,t,n,r){var o;"string"==typeof t?(o={_id:e,_rev:t},"function"==typeof n&&(r=n,n={})):(o=e,"function"==typeof t?(r=t,n={}):(r=n,n=t)),n=n||{},n.was_delete=!0;var i={_id:o._id,_rev:o._rev||n.rev};return i._deleted=!0,ce(i._id)&&"function"==typeof this._removeLocal?this._removeLocal(o,r):void this.bulkDocs({docs:[i]},n,_e(r))}),Se.prototype.revsDiff=y("revsDiff",function(e,t,n){function r(e,t){u.has(e)||u.set(e,{missing:[]}),u.get(e).missing.push(t)}function o(t,n){var o=e[t].slice(0);K(n,function(e,n,i,s,a){var u=n+"-"+i,c=o.indexOf(u);c!==-1&&(o.splice(c,1),"available"!==a.status&&r(t,u))}),o.forEach(function(e){r(t,e)})}"function"==typeof t&&(n=t,t={});var i=Object.keys(e);if(!i.length)return n(null,{});var s=0,u=new a;i.map(function(t){this._getRevisionTree(t,function(r,a){if(r&&404===r.status&&"missing"===r.message)u.set(t,{missing:e[t]});else{if(r)return n(r);o(t,a)}if(++s===i.length){var c={};return u.forEach(function(e,t){c[t]=e}),n(null,c)}})},this)}),Se.prototype.bulkGet=y("bulkGet",function(e,t){b(this,e,t)}),Se.prototype.compactDocument=y("compactDocument",function(e,t,n){var r=this;this._getRevisionTree(e,function(o,i){if(o)return n(o);var s=be(i),a=[],u=[];Object.keys(s).forEach(function(e){s[e]>t&&a.push(e)}),K(i,function(e,t,n,r,o){var i=t+"-"+n;"available"===o.status&&a.indexOf(i)!==-1&&u.push(i)}),r._doCompaction(e,u,n)})}),Se.prototype.compact=y("compact",function(e,t){"function"==typeof e&&(t=e,e={});var n=this;e=e||{},n._compactionQueue=n._compactionQueue||[],n._compactionQueue.push({opts:e,callback:t}),1===n._compactionQueue.length&&Ee(n)}),Se.prototype._compact=function(e,t){function n(e){s.push(o.compactDocument(e.id,0))}function r(e){var n=e.last_seq;Xr.all(s).then(function(){return U(o,"_local/compaction",function(e){return(!e.last_seq||e.last_seq= allRequests.length) { + return; + } + + var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length); + var batch = allRequests.slice(i, upTo); + processBatch(batch, i); + i += batch.length; + } + + function processBatch(batch, offset) { + batch.forEach(function (docId, j) { + var docIdx = offset + j; + var docRequests = requestsById[docId]; + + // just use the first request as the "template" + // TODO: The _bulk_get API allows for more subtle use cases than this, + // but for now it is unlikely that there will be a mix of different + // "atts_since" or "attachments" in the same request, since it's just + // replicate.js that is using this for the moment. + // Also, atts_since is aspirational, since we don't support it yet. + var docOpts = pick(docRequests[0], ['atts_since', 'attachments']); + docOpts.open_revs = docRequests.map(function (request) { + // rev is optional, open_revs disallowed + return request.rev; + }); + + // remove falsey / undefined revisions + docOpts.open_revs = docOpts.open_revs.filter(identityFunction); + + var formatResult = identityFunction; + + if (docOpts.open_revs.length === 0) { + delete docOpts.open_revs; + + // when fetching only the "winning" leaf, + // transform the result so it looks like an open_revs + // request + formatResult = formatResultForOpenRevsGet; + } + + // globally-supplied options + ['revs', 'attachments', 'binary', 'ajax'].forEach(function (param) { + if (param in opts) { + docOpts[param] = opts[param]; + } + }); + db.get(docId, docOpts, function (err, res) { + var result; + /* istanbul ignore if */ + if (err) { + result = [{error: err}]; + } else { + result = formatResult(res); + } + gotResult(docIdx, docId, result); + nextBatch(); + }); + }); + } + + nextBatch(); + +} + +function isChromeApp() { + return (typeof chrome !== "undefined" && + typeof chrome.storage !== "undefined" && + typeof chrome.storage.local !== "undefined"); +} + +var hasLocal; + +if (isChromeApp()) { + hasLocal = false; +} else { + try { + localStorage.setItem('_pouch_check_localstorage', 1); + hasLocal = !!localStorage.getItem('_pouch_check_localstorage'); + } catch (e) { + hasLocal = false; + } +} + +function hasLocalStorage() { + return hasLocal; +} + +inherits(Changes$1, EventEmitter); + +/* istanbul ignore next */ +function attachBrowserEvents(self) { + if (isChromeApp()) { + chrome.storage.onChanged.addListener(function (e) { + // make sure it's event addressed to us + if (e.db_name != null) { + //object only has oldValue, newValue members + self.emit(e.dbName.newValue); + } + }); + } else if (hasLocalStorage()) { + if (typeof addEventListener !== 'undefined') { + addEventListener("storage", function (e) { + self.emit(e.key); + }); + } else { // old IE + window.attachEvent("storage", function (e) { + self.emit(e.key); + }); + } + } +} + +function Changes$1() { + EventEmitter.call(this); + this._listeners = {}; + + attachBrowserEvents(this); +} +Changes$1.prototype.addListener = function (dbName, id, db, opts) { + /* istanbul ignore if */ + if (this._listeners[id]) { + return; + } + var self = this; + var inprogress = false; + function eventFunction() { + /* istanbul ignore if */ + if (!self._listeners[id]) { + return; + } + if (inprogress) { + inprogress = 'waiting'; + return; + } + inprogress = true; + var changesOpts = pick(opts, [ + 'style', 'include_docs', 'attachments', 'conflicts', 'filter', + 'doc_ids', 'view', 'since', 'query_params', 'binary' + ]); + + /* istanbul ignore next */ + function onError() { + inprogress = false; + } + + db.changes(changesOpts).on('change', function (c) { + if (c.seq > opts.since && !opts.cancelled) { + opts.since = c.seq; + opts.onChange(c); + } + }).on('complete', function () { + if (inprogress === 'waiting') { + setTimeout(function (){ + eventFunction(); + },0); + } + inprogress = false; + }).on('error', onError); + } + this._listeners[id] = eventFunction; + this.on(dbName, eventFunction); +}; + +Changes$1.prototype.removeListener = function (dbName, id) { + /* istanbul ignore if */ + if (!(id in this._listeners)) { + return; + } + EventEmitter.prototype.removeListener.call(this, dbName, + this._listeners[id]); + delete this._listeners[id]; +}; + + +/* istanbul ignore next */ +Changes$1.prototype.notifyLocalWindows = function (dbName) { + //do a useless change on a storage thing + //in order to get other windows's listeners to activate + if (isChromeApp()) { + chrome.storage.local.set({dbName: dbName}); + } else if (hasLocalStorage()) { + localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; + } +}; + +Changes$1.prototype.notify = function (dbName) { + this.emit(dbName); + this.notifyLocalWindows(dbName); +}; + +function guardedConsole(method) { + /* istanbul ignore else */ + if (console !== 'undefined' && method in console) { + var args = Array.prototype.slice.call(arguments, 1); + console[method].apply(console, args); + } +} + +function randomNumber(min, max) { + var maxTimeout = 600000; // Hard-coded default of 10 minutes + min = parseInt(min, 10) || 0; + max = parseInt(max, 10); + if (max !== max || max <= min) { + max = (min || 1) << 1; //doubling + } else { + max = max + 1; + } + // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout + if(max > maxTimeout) { + min = maxTimeout >> 1; // divide by two + max = maxTimeout; + } + var ratio = Math.random(); + var range = max - min; + + return ~~(range * ratio + min); // ~~ coerces to an int, but fast. +} + +function defaultBackOff(min) { + var max = 0; + if (!min) { + max = 2000; + } + return randomNumber(min, max); +} + +// designed to give info to browser users, who are disturbed +// when they see http errors in the console +function explainError(status, str) { + guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str); +} + +inherits(PouchError, Error); + +function PouchError(opts) { + Error.call(this, opts.reason); + this.status = opts.status; + this.name = opts.error; + this.message = opts.reason; + this.error = true; +} + +PouchError.prototype.toString = function () { + return JSON.stringify({ + status: this.status, + name: this.name, + message: this.message, + reason: this.reason + }); +}; + +var UNAUTHORIZED = new PouchError({ + status: 401, + error: 'unauthorized', + reason: "Name or password is incorrect." +}); + +var MISSING_BULK_DOCS = new PouchError({ + status: 400, + error: 'bad_request', + reason: "Missing JSON list of 'docs'" +}); + +var MISSING_DOC = new PouchError({ + status: 404, + error: 'not_found', + reason: 'missing' +}); + +var REV_CONFLICT = new PouchError({ + status: 409, + error: 'conflict', + reason: 'Document update conflict' +}); + +var INVALID_ID = new PouchError({ + status: 400, + error: 'bad_request', + reason: '_id field must contain a string' +}); + +var MISSING_ID = new PouchError({ + status: 412, + error: 'missing_id', + reason: '_id is required for puts' +}); + +var RESERVED_ID = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Only reserved document ids may start with underscore.' +}); + +var NOT_OPEN = new PouchError({ + status: 412, + error: 'precondition_failed', + reason: 'Database not open' +}); + +var UNKNOWN_ERROR = new PouchError({ + status: 500, + error: 'unknown_error', + reason: 'Database encountered an unknown error' +}); + +var BAD_ARG = new PouchError({ + status: 500, + error: 'badarg', + reason: 'Some query argument is invalid' +}); + +var INVALID_REQUEST = new PouchError({ + status: 400, + error: 'invalid_request', + reason: 'Request was invalid' +}); + +var QUERY_PARSE_ERROR = new PouchError({ + status: 400, + error: 'query_parse_error', + reason: 'Some query parameter is invalid' +}); + +var DOC_VALIDATION = new PouchError({ + status: 500, + error: 'doc_validation', + reason: 'Bad special document member' +}); + +var BAD_REQUEST = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Something wrong with the request' +}); + +var NOT_AN_OBJECT = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Document must be a JSON object' +}); + +var DB_MISSING = new PouchError({ + status: 404, + error: 'not_found', + reason: 'Database not found' +}); + +var IDB_ERROR = new PouchError({ + status: 500, + error: 'indexed_db_went_bad', + reason: 'unknown' +}); + +var WSQ_ERROR = new PouchError({ + status: 500, + error: 'web_sql_went_bad', + reason: 'unknown' +}); + +var LDB_ERROR = new PouchError({ + status: 500, + error: 'levelDB_went_went_bad', + reason: 'unknown' +}); + +var FORBIDDEN = new PouchError({ + status: 403, + error: 'forbidden', + reason: 'Forbidden by design doc validate_doc_update function' +}); + +var INVALID_REV = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Invalid rev format' +}); + +var FILE_EXISTS = new PouchError({ + status: 412, + error: 'file_exists', + reason: 'The database could not be created, the file already exists.' +}); + +var MISSING_STUB = new PouchError({ + status: 412, + error: 'missing_stub' +}); + +var INVALID_URL = new PouchError({ + status: 413, + error: 'invalid_url', + reason: 'Provided URL is invalid' +}); + +function createError(error, reason) { + function CustomPouchError(reason) { + // inherit error properties from our parent error manually + // so as to allow proper JSON parsing. + /* jshint ignore:start */ + for (var p in error) { + if (typeof error[p] !== 'function') { + this[p] = error[p]; + } + } + /* jshint ignore:end */ + if (reason !== undefined) { + this.reason = reason; + } + } + CustomPouchError.prototype = PouchError.prototype; + return new CustomPouchError(reason); +} + +function generateErrorFromResponse(err) { + + if (typeof err !== 'object') { + var data = err; + err = UNKNOWN_ERROR; + err.data = data; + } + + if ('error' in err && err.error === 'conflict') { + err.name = 'conflict'; + err.status = 409; + } + + if (!('name' in err)) { + err.name = err.error || 'unknown'; + } + + if (!('status' in err)) { + err.status = 500; + } + + if (!('message' in err)) { + err.message = err.message || err.reason; + } + + return err; +} + +function tryFilter(filter, doc, req) { + try { + return !filter(doc, req); + } catch (err) { + var msg = 'Filter function threw: ' + err.toString(); + return createError(BAD_REQUEST, msg); + } +} + +function filterChange(opts) { + var req = {}; + var hasFilter = opts.filter && typeof opts.filter === 'function'; + req.query = opts.query_params; + + return function filter(change) { + if (!change.doc) { + // CSG sends events on the changes feed that don't have documents, + // this hack makes a whole lot of existing code robust. + change.doc = {}; + } + + var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); + + if (typeof filterReturn === 'object') { + return filterReturn; + } + + if (filterReturn) { + return false; + } + + if (!opts.include_docs) { + delete change.doc; + } else if (!opts.attachments) { + for (var att in change.doc._attachments) { + /* istanbul ignore else */ + if (change.doc._attachments.hasOwnProperty(att)) { + change.doc._attachments[att].stub = true; + } + } + } + return true; + }; +} + +function flatten(arrs) { + var res = []; + for (var i = 0, len = arrs.length; i < len; i++) { + res = res.concat(arrs[i]); + } + return res; +} + +// Determine id an ID is valid +// - invalid IDs begin with an underescore that does not begin '_design' or +// '_local' +// - any other string value is a valid id +// Returns the specific error object for each case +function invalidIdError(id) { + var err; + if (!id) { + err = createError(MISSING_ID); + } else if (typeof id !== 'string') { + err = createError(INVALID_ID); + } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { + err = createError(RESERVED_ID); + } + if (err) { + throw err; + } +} + +function listenerCount(ee, type) { + return 'listenerCount' in ee ? ee.listenerCount(type) : + EventEmitter.listenerCount(ee, type); +} + +function parseDesignDocFunctionName(s) { + if (!s) { + return null; + } + var parts = s.split('/'); + if (parts.length === 2) { + return parts; + } + if (parts.length === 1) { + return [s, s]; + } + return null; +} + +function normalizeDesignDocFunctionName(s) { + var normalized = parseDesignDocFunctionName(s); + return normalized ? normalized.join('/') : null; +} + +// originally parseUri 1.2.2, now patched by us +// (c) Steven Levithan +// MIT License +var keys = ["source", "protocol", "authority", "userInfo", "user", "password", + "host", "port", "relative", "path", "directory", "file", "query", "anchor"]; +var qName ="queryKey"; +var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g; + +// use the "loose" parser +/* jshint maxlen: false */ +var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + +function parseUri(str) { + var m = parser.exec(str); + var uri = {}; + var i = 14; + + while (i--) { + var key = keys[i]; + var value = m[i] || ""; + var encoded = ['user', 'password'].indexOf(key) !== -1; + uri[key] = encoded ? decodeURIComponent(value) : value; + } + + uri[qName] = {}; + uri[keys[12]].replace(qParser, function ($0, $1, $2) { + if ($1) { + uri[qName][$1] = $2; + } + }); + + return uri; +} + +// this is essentially the "update sugar" function from daleharvey/pouchdb#1388 +// the diffFun tells us what delta to apply to the doc. it either returns +// the doc, or false if it doesn't need to do an update after all +function upsert(db, docId, diffFun) { + return new PouchPromise(function (fulfill, reject) { + db.get(docId, function (err, doc) { + if (err) { + /* istanbul ignore next */ + if (err.status !== 404) { + return reject(err); + } + doc = {}; + } + + // the user might change the _rev, so save it for posterity + var docRev = doc._rev; + var newDoc = diffFun(doc); + + if (!newDoc) { + // if the diffFun returns falsy, we short-circuit as + // an optimization + return fulfill({updated: false, rev: docRev}); + } + + // users aren't allowed to modify these values, + // so reset them here + newDoc._id = docId; + newDoc._rev = docRev; + fulfill(tryAndPut(db, newDoc, diffFun)); + }); + }); +} + +function tryAndPut(db, doc, diffFun) { + return db.put(doc).then(function (res) { + return { + updated: true, + rev: res.rev + }; + }, function (err) { + /* istanbul ignore next */ + if (err.status !== 409) { + throw err; + } + return upsert(db, doc._id, diffFun); + }); +} + +// BEGIN Math.uuid.js + +/*! +Math.uuid.js (v1.4) +http://www.broofa.com +mailto:robert@broofa.com + +Copyright (c) 2010 Robert Kieffer +Dual licensed under the MIT and GPL licenses. +*/ + +/* + * Generate a random uuid. + * + * USAGE: Math.uuid(length, radix) + * length - the desired number of characters + * radix - the number of allowable values for each character. + * + * EXAMPLES: + * // No arguments - returns RFC4122, version 4 ID + * >>> Math.uuid() + * "92329D39-6F5C-4520-ABFC-AAB64544E172" + * + * // One argument - returns ID of the specified length + * >>> Math.uuid(15) // 15 character ID (default base=62) + * "VcydxgltxrVZSTV" + * + * // Two arguments - returns ID of the specified length, and radix. + * // (Radix must be <= 62) + * >>> Math.uuid(8, 2) // 8 character ID (base=2) + * "01001010" + * >>> Math.uuid(8, 10) // 8 character ID (base=10) + * "47473046" + * >>> Math.uuid(8, 16) // 8 character ID (base=16) + * "098F4D35" + */ +var chars = ( + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + + 'abcdefghijklmnopqrstuvwxyz' +).split(''); +function getValue(radix) { + return 0 | Math.random() * radix; +} +function uuid(len, radix) { + radix = radix || chars.length; + var out = ''; + var i = -1; + + if (len) { + // Compact form + while (++i < len) { + out += chars[getValue(radix)]; + } + return out; + } + // rfc4122, version 4 form + // Fill in random data. At i==19 set the high bits of clock sequence as + // per rfc4122, sec. 4.1.5 + while (++i < 36) { + switch (i) { + case 8: + case 13: + case 18: + case 23: + out += '-'; + break; + case 19: + out += chars[(getValue(16) & 0x3) | 0x8]; + break; + default: + out += chars[getValue(16)]; + } + } + + return out; +} + +// We fetch all leafs of the revision tree, and sort them based on tree length +// and whether they were deleted, undeleted documents with the longest revision +// tree (most edits) win +// The final sort algorithm is slightly documented in a sidebar here: +// http://guide.couchdb.org/draft/conflicts.html +function winningRev(metadata) { + var winningId; + var winningPos; + var winningDeleted; + var toVisit = metadata.rev_tree.slice(); + var node; + while ((node = toVisit.pop())) { + var tree = node.ids; + var branches = tree[2]; + var pos = node.pos; + if (branches.length) { // non-leaf + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i]}); + } + continue; + } + var deleted = !!tree[1].deleted; + var id = tree[0]; + // sort by deleted, then pos, then id + if (!winningId || (winningDeleted !== deleted ? winningDeleted : + winningPos !== pos ? winningPos < pos : winningId < id)) { + winningId = id; + winningPos = pos; + winningDeleted = deleted; + } + } + + return winningPos + '-' + winningId; +} + +// Pretty much all below can be combined into a higher order function to +// traverse revisions +// The return value from the callback will be passed as context to all +// children of that node +function traverseRevTree(revs, callback) { + var toVisit = revs.slice(); + + var node; + while ((node = toVisit.pop())) { + var pos = node.pos; + var tree = node.ids; + var branches = tree[2]; + var newCtx = + callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx}); + } + } +} + +function sortByPos(a, b) { + return a.pos - b.pos; +} + +function collectLeaves(revs) { + var leaves = []; + traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) { + if (isLeaf) { + leaves.push({rev: pos + "-" + id, pos: pos, opts: opts}); + } + }); + leaves.sort(sortByPos).reverse(); + for (var i = 0, len = leaves.length; i < len; i++) { + delete leaves[i].pos; + } + return leaves; +} + +// returns revs of all conflicts that is leaves such that +// 1. are not deleted and +// 2. are different than winning revision +function collectConflicts(metadata) { + var win = winningRev(metadata); + var leaves = collectLeaves(metadata.rev_tree); + var conflicts = []; + for (var i = 0, len = leaves.length; i < len; i++) { + var leaf = leaves[i]; + if (leaf.rev !== win && !leaf.opts.deleted) { + conflicts.push(leaf.rev); + } + } + return conflicts; +} + +// compact a tree by marking its non-leafs as missing, +// and return a list of revs to delete +function compactTree(metadata) { + var revs = []; + traverseRevTree(metadata.rev_tree, function (isLeaf, pos, + revHash, ctx, opts) { + if (opts.status === 'available' && !isLeaf) { + revs.push(pos + '-' + revHash); + opts.status = 'missing'; + } + }); + return revs; +} + +// build up a list of all the paths to the leafs in this revision tree +function rootToLeaf(revs) { + var paths = []; + var toVisit = revs.slice(); + var node; + while ((node = toVisit.pop())) { + var pos = node.pos; + var tree = node.ids; + var id = tree[0]; + var opts = tree[1]; + var branches = tree[2]; + var isLeaf = branches.length === 0; + + var history = node.history ? node.history.slice() : []; + history.push({id: id, opts: opts}); + if (isLeaf) { + paths.push({pos: (pos + 1 - history.length), ids: history}); + } + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i], history: history}); + } + } + return paths.reverse(); +} + +// for a better overview of what this is doing, read: +// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl +// +// But for a quick intro, CouchDB uses a revision tree to store a documents +// history, A -> B -> C, when a document has conflicts, that is a branch in the +// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format +// +// KeyTree = [Path ... ] +// Path = {pos: position_from_root, ids: Tree} +// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []] + +function sortByPos$1(a, b) { + return a.pos - b.pos; +} + +// classic binary search +function binarySearch(arr, item, comparator) { + var low = 0; + var high = arr.length; + var mid; + while (low < high) { + mid = (low + high) >>> 1; + if (comparator(arr[mid], item) < 0) { + low = mid + 1; + } else { + high = mid; + } + } + return low; +} + +// assuming the arr is sorted, insert the item in the proper place +function insertSorted(arr, item, comparator) { + var idx = binarySearch(arr, item, comparator); + arr.splice(idx, 0, item); +} + +// Turn a path as a flat array into a tree with a single branch. +// If any should be stemmed from the beginning of the array, that's passed +// in as the second argument +function pathToTree(path, numStemmed) { + var root; + var leaf; + for (var i = numStemmed, len = path.length; i < len; i++) { + var node = path[i]; + var currentLeaf = [node.id, node.opts, []]; + if (leaf) { + leaf[2].push(currentLeaf); + leaf = currentLeaf; + } else { + root = leaf = currentLeaf; + } + } + return root; +} + +// compare the IDs of two trees +function compareTree(a, b) { + return a[0] < b[0] ? -1 : 1; +} + +// Merge two trees together +// The roots of tree1 and tree2 must be the same revision +function mergeTree(in_tree1, in_tree2) { + var queue = [{tree1: in_tree1, tree2: in_tree2}]; + var conflicts = false; + while (queue.length > 0) { + var item = queue.pop(); + var tree1 = item.tree1; + var tree2 = item.tree2; + + if (tree1[1].status || tree2[1].status) { + tree1[1].status = + (tree1[1].status === 'available' || + tree2[1].status === 'available') ? 'available' : 'missing'; + } + + for (var i = 0; i < tree2[2].length; i++) { + if (!tree1[2][0]) { + conflicts = 'new_leaf'; + tree1[2][0] = tree2[2][i]; + continue; + } + + var merged = false; + for (var j = 0; j < tree1[2].length; j++) { + if (tree1[2][j][0] === tree2[2][i][0]) { + queue.push({tree1: tree1[2][j], tree2: tree2[2][i]}); + merged = true; + } + } + if (!merged) { + conflicts = 'new_branch'; + insertSorted(tree1[2], tree2[2][i], compareTree); + } + } + } + return {conflicts: conflicts, tree: in_tree1}; +} + +function doMerge(tree, path, dontExpand) { + var restree = []; + var conflicts = false; + var merged = false; + var res; + + if (!tree.length) { + return {tree: [path], conflicts: 'new_leaf'}; + } + + for (var i = 0, len = tree.length; i < len; i++) { + var branch = tree[i]; + if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { + // Paths start at the same position and have the same root, so they need + // merged + res = mergeTree(branch.ids, path.ids); + restree.push({pos: branch.pos, ids: res.tree}); + conflicts = conflicts || res.conflicts; + merged = true; + } else if (dontExpand !== true) { + // The paths start at a different position, take the earliest path and + // traverse up until it as at the same point from root as the path we + // want to merge. If the keys match we return the longer path with the + // other merged After stemming we dont want to expand the trees + + var t1 = branch.pos < path.pos ? branch : path; + var t2 = branch.pos < path.pos ? path : branch; + var diff = t2.pos - t1.pos; + + var candidateParents = []; + + var trees = []; + trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null}); + while (trees.length > 0) { + var item = trees.pop(); + if (item.diff === 0) { + if (item.ids[0] === t2.ids[0]) { + candidateParents.push(item); + } + continue; + } + var elements = item.ids[2]; + for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { + trees.push({ + ids: elements[j], + diff: item.diff - 1, + parent: item.ids, + parentIdx: j + }); + } + } + + var el = candidateParents[0]; + + if (!el) { + restree.push(branch); + } else { + res = mergeTree(el.ids, t2.ids); + el.parent[2][el.parentIdx] = res.tree; + restree.push({pos: t1.pos, ids: t1.ids}); + conflicts = conflicts || res.conflicts; + merged = true; + } + } else { + restree.push(branch); + } + } + + // We didnt find + if (!merged) { + restree.push(path); + } + + restree.sort(sortByPos$1); + + return { + tree: restree, + conflicts: conflicts || 'internal_node' + }; +} + +// To ensure we dont grow the revision tree infinitely, we stem old revisions +function stem(tree, depth) { + // First we break out the tree into a complete list of root to leaf paths + var paths = rootToLeaf(tree); + var maybeStem = {}; + + var result; + for (var i = 0, len = paths.length; i < len; i++) { + // Then for each path, we cut off the start of the path based on the + // `depth` to stem to, and generate a new set of flat trees + var path = paths[i]; + var stemmed = path.ids; + var numStemmed = Math.max(0, stemmed.length - depth); + var stemmedNode = { + pos: path.pos + numStemmed, + ids: pathToTree(stemmed, numStemmed) + }; + + for (var s = 0; s < numStemmed; s++) { + var rev = (path.pos + s) + '-' + stemmed[s].id; + maybeStem[rev] = true; + } + + // Then we remerge all those flat trees together, ensuring that we dont + // connect trees that would go beyond the depth limit + if (result) { + result = doMerge(result, stemmedNode, true).tree; + } else { + result = [stemmedNode]; + } + } + + traverseRevTree(result, function (isLeaf, pos, revHash) { + // some revisions may have been removed in a branch but not in another + delete maybeStem[pos + '-' + revHash]; + }); + + return { + tree: result, + revs: Object.keys(maybeStem) + }; +} + +function merge(tree, path, depth) { + var newTree = doMerge(tree, path); + var stemmed = stem(newTree.tree, depth); + return { + tree: stemmed.tree, + stemmedRevs: stemmed.revs, + conflicts: newTree.conflicts + }; +} + +// return true if a rev exists in the rev tree, false otherwise +function revExists(revs, rev) { + var toVisit = revs.slice(); + var splitRev = rev.split('-'); + var targetPos = parseInt(splitRev[0], 10); + var targetId = splitRev[1]; + + var node; + while ((node = toVisit.pop())) { + if (node.pos === targetPos && node.ids[0] === targetId) { + return true; + } + var branches = node.ids[2]; + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: node.pos + 1, ids: branches[i]}); + } + } + return false; +} + +function getTrees(node) { + return node.ids; +} + +// check if a specific revision of a doc has been deleted +// - metadata: the metadata object from the doc store +// - rev: (optional) the revision to check. defaults to winning revision +function isDeleted(metadata, rev) { + if (!rev) { + rev = winningRev(metadata); + } + var id = rev.substring(rev.indexOf('-') + 1); + var toVisit = metadata.rev_tree.map(getTrees); + + var tree; + while ((tree = toVisit.pop())) { + if (tree[0] === id) { + return !!tree[1].deleted; + } + toVisit = toVisit.concat(tree[2]); + } +} + +function isLocalId(id) { + return (/^_local/).test(id); +} + +function evalFilter(input) { + return scopedEval('"use strict";\nreturn ' + input + ';', {}); +} + +function evalView(input) { + var code = [ + 'return function(doc) {', + ' "use strict";', + ' var emitted = false;', + ' var emit = function (a, b) {', + ' emitted = true;', + ' };', + ' var view = ' + input + ';', + ' view(doc);', + ' if (emitted) {', + ' return true;', + ' }', + '};' + ].join('\n'); + + return scopedEval(code, {}); +} + +inherits(Changes, EventEmitter); + +function tryCatchInChangeListener(self, change) { + // isolate try/catches to avoid V8 deoptimizations + try { + self.emit('change', change); + } catch (e) { + guardedConsole('error', 'Error in .on("change", function):', e); + } +} + +function Changes(db, opts, callback) { + EventEmitter.call(this); + var self = this; + this.db = db; + opts = opts ? clone(opts) : {}; + var complete = opts.complete = once(function (err, resp) { + if (err) { + if (listenerCount(self, 'error') > 0) { + self.emit('error', err); + } + } else { + self.emit('complete', resp); + } + self.removeAllListeners(); + db.removeListener('destroyed', onDestroy); + }); + if (callback) { + self.on('complete', function (resp) { + callback(null, resp); + }); + self.on('error', callback); + } + function onDestroy() { + self.cancel(); + } + db.once('destroyed', onDestroy); + + opts.onChange = function (change) { + /* istanbul ignore if */ + if (opts.isCancelled) { + return; + } + tryCatchInChangeListener(self, change); + }; + + var promise = new PouchPromise(function (fulfill, reject) { + opts.complete = function (err, res) { + if (err) { + reject(err); + } else { + fulfill(res); + } + }; + }); + self.once('cancel', function () { + db.removeListener('destroyed', onDestroy); + opts.complete(null, {status: 'cancelled'}); + }); + this.then = promise.then.bind(promise); + this['catch'] = promise['catch'].bind(promise); + this.then(function (result) { + complete(null, result); + }, complete); + + + + if (!db.taskqueue.isReady) { + db.taskqueue.addTask(function (failed) { + if (failed) { + opts.complete(failed); + } else if (self.isCancelled) { + self.emit('cancel'); + } else { + self.doChanges(opts); + } + }); + } else { + self.doChanges(opts); + } +} +Changes.prototype.cancel = function () { + this.isCancelled = true; + if (this.db.taskqueue.isReady) { + this.emit('cancel'); + } +}; +function processChange(doc, metadata, opts) { + var changeList = [{rev: doc._rev}]; + if (opts.style === 'all_docs') { + changeList = collectLeaves(metadata.rev_tree) + .map(function (x) { return {rev: x.rev}; }); + } + var change = { + id: metadata.id, + changes: changeList, + doc: doc + }; + + if (isDeleted(metadata, doc._rev)) { + change.deleted = true; + } + if (opts.conflicts) { + change.doc._conflicts = collectConflicts(metadata); + if (!change.doc._conflicts.length) { + delete change.doc._conflicts; + } + } + return change; +} + +Changes.prototype.doChanges = function (opts) { + var self = this; + var callback = opts.complete; + + opts = clone(opts); + if ('live' in opts && !('continuous' in opts)) { + opts.continuous = opts.live; + } + opts.processChange = processChange; + + if (opts.since === 'latest') { + opts.since = 'now'; + } + if (!opts.since) { + opts.since = 0; + } + if (opts.since === 'now') { + this.db.info().then(function (info) { + /* istanbul ignore if */ + if (self.isCancelled) { + callback(null, {status: 'cancelled'}); + return; + } + opts.since = info.update_seq; + self.doChanges(opts); + }, callback); + return; + } + + + if (opts.view && !opts.filter) { + opts.filter = '_view'; + } + + if (opts.filter && typeof opts.filter === 'string') { + if (opts.filter === '_view') { + opts.view = normalizeDesignDocFunctionName(opts.view); + } else { + opts.filter = normalizeDesignDocFunctionName(opts.filter); + } + + if (this.db.type() !== 'http' && !opts.doc_ids) { + return this.filterChanges(opts); + } + } + + if (!('descending' in opts)) { + opts.descending = false; + } + + // 0 and 1 should return 1 document + opts.limit = opts.limit === 0 ? 1 : opts.limit; + opts.complete = callback; + var newPromise = this.db._changes(opts); + /* istanbul ignore else */ + if (newPromise && typeof newPromise.cancel === 'function') { + var cancel = self.cancel; + self.cancel = getArguments(function (args) { + newPromise.cancel(); + cancel.apply(this, args); + }); + } +}; + +Changes.prototype.filterChanges = function (opts) { + var self = this; + var callback = opts.complete; + if (opts.filter === '_view') { + if (!opts.view || typeof opts.view !== 'string') { + var err = createError(BAD_REQUEST, + '`view` filter parameter not found or invalid.'); + return callback(err); + } + // fetch a view from a design doc, make it behave like a filter + var viewName = parseDesignDocFunctionName(opts.view); + this.db.get('_design/' + viewName[0], function (err, ddoc) { + /* istanbul ignore if */ + if (self.isCancelled) { + return callback(null, {status: 'cancelled'}); + } + /* istanbul ignore next */ + if (err) { + return callback(generateErrorFromResponse(err)); + } + var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] && + ddoc.views[viewName[1]].map; + if (!mapFun) { + return callback(createError(MISSING_DOC, + (ddoc.views ? 'missing json key: ' + viewName[1] : + 'missing json key: views'))); + } + opts.filter = evalView(mapFun); + self.doChanges(opts); + }); + } else { + // fetch a filter from a design doc + var filterName = parseDesignDocFunctionName(opts.filter); + if (!filterName) { + return self.doChanges(opts); + } + this.db.get('_design/' + filterName[0], function (err, ddoc) { + /* istanbul ignore if */ + if (self.isCancelled) { + return callback(null, {status: 'cancelled'}); + } + /* istanbul ignore next */ + if (err) { + return callback(generateErrorFromResponse(err)); + } + var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]]; + if (!filterFun) { + return callback(createError(MISSING_DOC, + ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1] + : 'missing json key: filters'))); + } + opts.filter = evalFilter(filterFun); + self.doChanges(opts); + }); + } +}; + +/* + * A generic pouch adapter + */ + +function compare(left, right) { + return left < right ? -1 : left > right ? 1 : 0; +} + +// returns first element of arr satisfying callback predicate +function arrayFirst(arr, callback) { + for (var i = 0; i < arr.length; i++) { + if (callback(arr[i], i) === true) { + return arr[i]; + } + } +} + +// Wrapper for functions that call the bulkdocs api with a single doc, +// if the first result is an error, return an error +function yankError(callback) { + return function (err, results) { + if (err || (results[0] && results[0].error)) { + callback(err || results[0]); + } else { + callback(null, results.length ? results[0] : results); + } + }; +} + +// clean docs given to us by the user +function cleanDocs(docs) { + for (var i = 0; i < docs.length; i++) { + var doc = docs[i]; + if (doc._deleted) { + delete doc._attachments; // ignore atts for deleted docs + } else if (doc._attachments) { + // filter out extraneous keys from _attachments + var atts = Object.keys(doc._attachments); + for (var j = 0; j < atts.length; j++) { + var att = atts[j]; + doc._attachments[att] = pick(doc._attachments[att], + ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']); + } + } + } +} + +// compare two docs, first by _id then by _rev +function compareByIdThenRev(a, b) { + var idCompare = compare(a._id, b._id); + if (idCompare !== 0) { + return idCompare; + } + var aStart = a._revisions ? a._revisions.start : 0; + var bStart = b._revisions ? b._revisions.start : 0; + return compare(aStart, bStart); +} + +// for every node in a revision tree computes its distance from the closest +// leaf +function computeHeight(revs) { + var height = {}; + var edges = []; + traverseRevTree(revs, function (isLeaf, pos, id, prnt) { + var rev = pos + "-" + id; + if (isLeaf) { + height[rev] = 0; + } + if (prnt !== undefined) { + edges.push({from: prnt, to: rev}); + } + return rev; + }); + + edges.reverse(); + edges.forEach(function (edge) { + if (height[edge.from] === undefined) { + height[edge.from] = 1 + height[edge.to]; + } else { + height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]); + } + }); + return height; +} + +function allDocsKeysQuery(api, opts, callback) { + var keys = ('limit' in opts) ? + opts.keys.slice(opts.skip, opts.limit + opts.skip) : + (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys; + if (opts.descending) { + keys.reverse(); + } + if (!keys.length) { + return api._allDocs({limit: 0}, callback); + } + var finalResults = { + offset: opts.skip + }; + return PouchPromise.all(keys.map(function (key) { + var subOpts = extend({key: key, deleted: 'ok'}, opts); + ['limit', 'skip', 'keys'].forEach(function (optKey) { + delete subOpts[optKey]; + }); + return new PouchPromise(function (resolve, reject) { + api._allDocs(subOpts, function (err, res) { + /* istanbul ignore if */ + if (err) { + return reject(err); + } + finalResults.total_rows = res.total_rows; + resolve(res.rows[0] || {key: key, error: 'not_found'}); + }); + }); + })).then(function (results) { + finalResults.rows = results; + return finalResults; + }); +} + +// all compaction is done in a queue, to avoid attaching +// too many listeners at once +function doNextCompaction(self) { + var task = self._compactionQueue[0]; + var opts = task.opts; + var callback = task.callback; + self.get('_local/compaction').catch(function () { + return false; + }).then(function (doc) { + if (doc && doc.last_seq) { + opts.last_seq = doc.last_seq; + } + self._compact(opts, function (err, res) { + /* istanbul ignore if */ + if (err) { + callback(err); + } else { + callback(null, res); + } + process.nextTick(function () { + self._compactionQueue.shift(); + if (self._compactionQueue.length) { + doNextCompaction(self); + } + }); + }); + }); +} + +function attachmentNameError(name) { + if (name.charAt(0) === '_') { + return name + 'is not a valid attachment name, attachment ' + + 'names cannot start with \'_\''; + } + return false; +} + +inherits(AbstractPouchDB, EventEmitter); + +function AbstractPouchDB() { + EventEmitter.call(this); +} + +AbstractPouchDB.prototype.post = + adapterFun('post', function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof doc !== 'object' || Array.isArray(doc)) { + return callback(createError(NOT_AN_OBJECT)); + } + this.bulkDocs({docs: [doc]}, opts, yankError(callback)); +}); + +AbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof doc !== 'object' || Array.isArray(doc)) { + return cb(createError(NOT_AN_OBJECT)); + } + invalidIdError(doc._id); + if (isLocalId(doc._id) && typeof this._putLocal === 'function') { + if (doc._deleted) { + return this._removeLocal(doc, cb); + } else { + return this._putLocal(doc, cb); + } + } + if (typeof this._put === 'function' && opts.new_edits !== false) { + this._put(doc, opts, cb); + } else { + this.bulkDocs({docs: [doc]}, opts, yankError(cb)); + } +}); + +AbstractPouchDB.prototype.putAttachment = + adapterFun('putAttachment', function (docId, attachmentId, rev, + blob, type) { + var api = this; + if (typeof type === 'function') { + type = blob; + blob = rev; + rev = null; + } + // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267 + /* istanbul ignore if */ + if (typeof type === 'undefined') { + type = blob; + blob = rev; + rev = null; + } + + function createAttachment(doc) { + var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0; + doc._attachments = doc._attachments || {}; + doc._attachments[attachmentId] = { + content_type: type, + data: blob, + revpos: ++prevrevpos + }; + return api.put(doc); + } + + return api.get(docId).then(function (doc) { + if (doc._rev !== rev) { + throw createError(REV_CONFLICT); + } + + return createAttachment(doc); + }, function (err) { + // create new doc + /* istanbul ignore else */ + if (err.reason === MISSING_DOC.message) { + return createAttachment({_id: docId}); + } else { + throw err; + } + }); +}); + +AbstractPouchDB.prototype.removeAttachment = + adapterFun('removeAttachment', function (docId, attachmentId, rev, + callback) { + var self = this; + self.get(docId, function (err, obj) { + /* istanbul ignore if */ + if (err) { + callback(err); + return; + } + if (obj._rev !== rev) { + callback(createError(REV_CONFLICT)); + return; + } + /* istanbul ignore if */ + if (!obj._attachments) { + return callback(); + } + delete obj._attachments[attachmentId]; + if (Object.keys(obj._attachments).length === 0) { + delete obj._attachments; + } + self.put(obj, callback); + }); +}); + +AbstractPouchDB.prototype.remove = + adapterFun('remove', function (docOrId, optsOrRev, opts, callback) { + var doc; + if (typeof optsOrRev === 'string') { + // id, rev, opts, callback style + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + } else { + // doc, opts, callback style + doc = docOrId; + if (typeof optsOrRev === 'function') { + callback = optsOrRev; + opts = {}; + } else { + callback = opts; + opts = optsOrRev; + } + } + opts = opts || {}; + opts.was_delete = true; + var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)}; + newDoc._deleted = true; + if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') { + return this._removeLocal(doc, callback); + } + this.bulkDocs({docs: [newDoc]}, opts, yankError(callback)); +}); + +AbstractPouchDB.prototype.revsDiff = + adapterFun('revsDiff', function (req, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var ids = Object.keys(req); + + if (!ids.length) { + return callback(null, {}); + } + + var count = 0; + var missing = new _Map(); + + function addToMissing(id, revId) { + if (!missing.has(id)) { + missing.set(id, {missing: []}); + } + missing.get(id).missing.push(revId); + } + + function processDoc(id, rev_tree) { + // Is this fast enough? Maybe we should switch to a set simulated by a map + var missingForId = req[id].slice(0); + traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx, + opts) { + var rev = pos + '-' + revHash; + var idx = missingForId.indexOf(rev); + if (idx === -1) { + return; + } + + missingForId.splice(idx, 1); + /* istanbul ignore if */ + if (opts.status !== 'available') { + addToMissing(id, rev); + } + }); + + // Traversing the tree is synchronous, so now `missingForId` contains + // revisions that were not found in the tree + missingForId.forEach(function (rev) { + addToMissing(id, rev); + }); + } + + ids.map(function (id) { + this._getRevisionTree(id, function (err, rev_tree) { + if (err && err.status === 404 && err.message === 'missing') { + missing.set(id, {missing: req[id]}); + } else if (err) { + /* istanbul ignore next */ + return callback(err); + } else { + processDoc(id, rev_tree); + } + + if (++count === ids.length) { + // convert LazyMap to object + var missingObj = {}; + missing.forEach(function (value, key) { + missingObj[key] = value; + }); + return callback(null, missingObj); + } + }); + }, this); +}); + +// _bulk_get API for faster replication, as described in +// https://github.com/apache/couchdb-chttpd/pull/33 +// At the "abstract" level, it will just run multiple get()s in +// parallel, because this isn't much of a performance cost +// for local databases (except the cost of multiple transactions, which is +// small). The http adapter overrides this in order +// to do a more efficient single HTTP request. +AbstractPouchDB.prototype.bulkGet = + adapterFun('bulkGet', function (opts, callback) { + bulkGet(this, opts, callback); +}); + +// compact one document and fire callback +// by compacting we mean removing all revisions which +// are further from the leaf in revision tree than max_height +AbstractPouchDB.prototype.compactDocument = + adapterFun('compactDocument', function (docId, maxHeight, callback) { + var self = this; + this._getRevisionTree(docId, function (err, revTree) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + var height = computeHeight(revTree); + var candidates = []; + var revs = []; + Object.keys(height).forEach(function (rev) { + if (height[rev] > maxHeight) { + candidates.push(rev); + } + }); + + traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) { + var rev = pos + '-' + revHash; + if (opts.status === 'available' && candidates.indexOf(rev) !== -1) { + revs.push(rev); + } + }); + self._doCompaction(docId, revs, callback); + }); +}); + +// compact the whole database using single document +// compaction +AbstractPouchDB.prototype.compact = + adapterFun('compact', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + var self = this; + opts = opts || {}; + + self._compactionQueue = self._compactionQueue || []; + self._compactionQueue.push({opts: opts, callback: callback}); + if (self._compactionQueue.length === 1) { + doNextCompaction(self); + } +}); +AbstractPouchDB.prototype._compact = function (opts, callback) { + var self = this; + var changesOpts = { + return_docs: false, + last_seq: opts.last_seq || 0 + }; + var promises = []; + + function onChange(row) { + promises.push(self.compactDocument(row.id, 0)); + } + function onComplete(resp) { + var lastSeq = resp.last_seq; + PouchPromise.all(promises).then(function () { + return upsert(self, '_local/compaction', function deltaFunc(doc) { + if (!doc.last_seq || doc.last_seq < lastSeq) { + doc.last_seq = lastSeq; + return doc; + } + return false; // somebody else got here first, don't update + }); + }).then(function () { + callback(null, {ok: true}); + }).catch(callback); + } + self.changes(changesOpts) + .on('change', onChange) + .on('complete', onComplete) + .on('error', callback); +}; + +/* Begin api wrappers. Specific functionality to storage belongs in the + _[method] */ +AbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof id !== 'string') { + return cb(createError(INVALID_ID)); + } + if (isLocalId(id) && typeof this._getLocal === 'function') { + return this._getLocal(id, cb); + } + var leaves = [], self = this; + + function finishOpenRevs() { + var result = []; + var count = leaves.length; + /* istanbul ignore if */ + if (!count) { + return cb(null, result); + } + // order with open_revs is unspecified + leaves.forEach(function (leaf) { + self.get(id, { + rev: leaf, + revs: opts.revs, + attachments: opts.attachments + }, function (err, doc) { + if (!err) { + result.push({ok: doc}); + } else { + result.push({missing: leaf}); + } + count--; + if (!count) { + cb(null, result); + } + }); + }); + } + + if (opts.open_revs) { + if (opts.open_revs === "all") { + this._getRevisionTree(id, function (err, rev_tree) { + if (err) { + return cb(err); + } + leaves = collectLeaves(rev_tree).map(function (leaf) { + return leaf.rev; + }); + finishOpenRevs(); + }); + } else { + if (Array.isArray(opts.open_revs)) { + leaves = opts.open_revs; + for (var i = 0; i < leaves.length; i++) { + var l = leaves[i]; + // looks like it's the only thing couchdb checks + if (!(typeof (l) === "string" && /^\d+-/.test(l))) { + return cb(createError(INVALID_REV)); + } + } + finishOpenRevs(); + } else { + return cb(createError(UNKNOWN_ERROR, 'function_clause')); + } + } + return; // open_revs does not like other options + } + + return this._get(id, opts, function (err, result) { + if (err) { + return cb(err); + } + + var doc = result.doc; + var metadata = result.metadata; + var ctx = result.ctx; + + if (opts.conflicts) { + var conflicts = collectConflicts(metadata); + if (conflicts.length) { + doc._conflicts = conflicts; + } + } + + if (isDeleted(metadata, doc._rev)) { + doc._deleted = true; + } + + if (opts.revs || opts.revs_info) { + var paths = rootToLeaf(metadata.rev_tree); + var path = arrayFirst(paths, function (arr) { + return arr.ids.map(function (x) { return x.id; }) + .indexOf(doc._rev.split('-')[1]) !== -1; + }); + + var indexOfRev = path.ids.map(function (x) {return x.id; }) + .indexOf(doc._rev.split('-')[1]) + 1; + var howMany = path.ids.length - indexOfRev; + path.ids.splice(indexOfRev, howMany); + path.ids.reverse(); + + if (opts.revs) { + doc._revisions = { + start: (path.pos + path.ids.length) - 1, + ids: path.ids.map(function (rev) { + return rev.id; + }) + }; + } + if (opts.revs_info) { + var pos = path.pos + path.ids.length; + doc._revs_info = path.ids.map(function (rev) { + pos--; + return { + rev: pos + '-' + rev.id, + status: rev.opts.status + }; + }); + } + } + + if (opts.attachments && doc._attachments) { + var attachments = doc._attachments; + var count = Object.keys(attachments).length; + if (count === 0) { + return cb(null, doc); + } + Object.keys(attachments).forEach(function (key) { + this._getAttachment(doc._id, key, attachments[key], { + // Previously the revision handling was done in adapter.js + // getAttachment, however since idb-next doesnt we need to + // pass the rev through + rev: doc._rev, + binary: opts.binary, + ctx: ctx + }, function (err, data) { + var att = doc._attachments[key]; + att.data = data; + delete att.stub; + delete att.length; + if (!--count) { + cb(null, doc); + } + }); + }, self); + } else { + if (doc._attachments) { + for (var key in doc._attachments) { + /* istanbul ignore else */ + if (doc._attachments.hasOwnProperty(key)) { + doc._attachments[key].stub = true; + } + } + } + cb(null, doc); + } + }); +}); + +// TODO: I dont like this, it forces an extra read for every +// attachment read and enforces a confusing api between +// adapter.js and the adapter implementation +AbstractPouchDB.prototype.getAttachment = + adapterFun('getAttachment', function (docId, attachmentId, opts, callback) { + var self = this; + if (opts instanceof Function) { + callback = opts; + opts = {}; + } + this._get(docId, opts, function (err, res) { + if (err) { + return callback(err); + } + if (res.doc._attachments && res.doc._attachments[attachmentId]) { + opts.ctx = res.ctx; + opts.binary = true; + self._getAttachment(docId, attachmentId, + res.doc._attachments[attachmentId], opts, callback); + } else { + return callback(createError(MISSING_DOC)); + } + }); +}); + +AbstractPouchDB.prototype.allDocs = + adapterFun('allDocs', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if ('keys' in opts) { + if (!Array.isArray(opts.keys)) { + return callback(new TypeError('options.keys must be an array')); + } + var incompatibleOpt = + ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) { + return incompatibleOpt in opts; + })[0]; + if (incompatibleOpt) { + callback(createError(QUERY_PARSE_ERROR, + 'Query parameter `' + incompatibleOpt + + '` is not compatible with multi-get' + )); + return; + } + if (this.type() !== 'http') { + return allDocsKeysQuery(this, opts, callback); + } + } + + return this._allDocs(opts, callback); +}); + +AbstractPouchDB.prototype.changes = function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return new Changes(this, opts, callback); +}; + +AbstractPouchDB.prototype.close = adapterFun('close', function (callback) { + this._closed = true; + return this._close(callback); +}); + +AbstractPouchDB.prototype.info = adapterFun('info', function (callback) { + var self = this; + this._info(function (err, info) { + if (err) { + return callback(err); + } + // assume we know better than the adapter, unless it informs us + info.db_name = info.db_name || self.name; + info.auto_compaction = !!(self.auto_compaction && self.type() !== 'http'); + info.adapter = self.type(); + callback(null, info); + }); +}); + +AbstractPouchDB.prototype.id = adapterFun('id', function (callback) { + return this._id(callback); +}); + +/* istanbul ignore next */ +AbstractPouchDB.prototype.type = function () { + return (typeof this._type === 'function') ? this._type() : this.adapter; +}; + +AbstractPouchDB.prototype.bulkDocs = + adapterFun('bulkDocs', function (req, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + opts = opts || {}; + + if (Array.isArray(req)) { + req = { + docs: req + }; + } + + if (!req || !req.docs || !Array.isArray(req.docs)) { + return callback(createError(MISSING_BULK_DOCS)); + } + + for (var i = 0; i < req.docs.length; ++i) { + if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) { + return callback(createError(NOT_AN_OBJECT)); + } + } + + var attachmentError; + req.docs.forEach(function (doc) { + if (doc._attachments) { + Object.keys(doc._attachments).forEach(function (name) { + attachmentError = attachmentError || attachmentNameError(name); + }); + } + }); + + if (attachmentError) { + return callback(createError(BAD_REQUEST, attachmentError)); + } + + if (!('new_edits' in opts)) { + if ('new_edits' in req) { + opts.new_edits = req.new_edits; + } else { + opts.new_edits = true; + } + } + + if (!opts.new_edits && this.type() !== 'http') { + // ensure revisions of the same doc are sorted, so that + // the local adapter processes them correctly (#2935) + req.docs.sort(compareByIdThenRev); + } + + cleanDocs(req.docs); + + return this._bulkDocs(req, opts, function (err, res) { + if (err) { + return callback(err); + } + if (!opts.new_edits) { + // this is what couch does when new_edits is false + res = res.filter(function (x) { + return x.error; + }); + } + callback(null, res); + }); +}); + +AbstractPouchDB.prototype.registerDependentDatabase = + adapterFun('registerDependentDatabase', function (dependentDb, + callback) { + var depDB = new this.constructor(dependentDb, this.__opts); + + function diffFun(doc) { + doc.dependentDbs = doc.dependentDbs || {}; + if (doc.dependentDbs[dependentDb]) { + return false; // no update required + } + doc.dependentDbs[dependentDb] = true; + return doc; + } + upsert(this, '_local/_pouch_dependentDbs', diffFun) + .then(function () { + callback(null, {db: depDB}); + }).catch(callback); +}); + +AbstractPouchDB.prototype.destroy = + adapterFun('destroy', function (opts, callback) { + + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + var self = this; + var usePrefix = 'use_prefix' in self ? self.use_prefix : true; + + function destroyDb() { + // call destroy method of the particular adaptor + self._destroy(opts, function (err, resp) { + if (err) { + return callback(err); + } + self._destroyed = true; + self.emit('destroyed'); + callback(null, resp || { 'ok': true }); + }); + } + + if (self.type() === 'http') { + // no need to check for dependent DBs if it's a remote DB + return destroyDb(); + } + + self.get('_local/_pouch_dependentDbs', function (err, localDoc) { + if (err) { + /* istanbul ignore if */ + if (err.status !== 404) { + return callback(err); + } else { // no dependencies + return destroyDb(); + } + } + var dependentDbs = localDoc.dependentDbs; + var PouchDB = self.constructor; + var deletedMap = Object.keys(dependentDbs).map(function (name) { + // use_prefix is only false in the browser + /* istanbul ignore next */ + var trueName = usePrefix ? + name.replace(new RegExp('^' + PouchDB.prefix), '') : name; + return new PouchDB(trueName, self.__opts).destroy(); + }); + PouchPromise.all(deletedMap).then(destroyDb, callback); + }); +}); + +function TaskQueue() { + this.isReady = false; + this.failed = false; + this.queue = []; +} + +TaskQueue.prototype.execute = function () { + var fun; + if (this.failed) { + while ((fun = this.queue.shift())) { + fun(this.failed); + } + } else { + while ((fun = this.queue.shift())) { + fun(); + } + } +}; + +TaskQueue.prototype.fail = function (err) { + this.failed = err; + this.execute(); +}; + +TaskQueue.prototype.ready = function (db) { + this.isReady = true; + this.db = db; + this.execute(); +}; + +TaskQueue.prototype.addTask = function (fun) { + this.queue.push(fun); + if (this.failed) { + this.execute(); + } +}; + +function parseAdapter(name, opts) { + var match = name.match(/([a-z\-]*):\/\/(.*)/); + if (match) { + // the http adapter expects the fully qualified name + name = /http(s?)/.test(match[1]) ? match[1] + '://' + match[2] : match[2]; + return {name: name, adapter: match[1]}; + } + + // check for browsers that have been upgraded from websql-only to websql+idb + var skipIdb = 'idb' in PouchDB.adapters && 'websql' in PouchDB.adapters && + hasLocalStorage() && + localStorage['_pouch__websqldb_' + PouchDB.prefix + name]; + + var adapterName; + + if (opts.adapter) { + adapterName = opts.adapter; + } else if (typeof opts !== 'undefined' && opts.db) { + adapterName = 'leveldb'; + } else { // automatically determine adapter + for (var i = 0; i < PouchDB.preferredAdapters.length; ++i) { + adapterName = PouchDB.preferredAdapters[i]; + /* istanbul ignore if */ + if (skipIdb && adapterName === 'idb') { + // log it, because this can be confusing during development + guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' + + ' avoid data loss, because it was already opened with WebSQL.'); + continue; // keep using websql to avoid user data loss + } + break; + } + } + + var adapter = PouchDB.adapters[adapterName]; + + // if adapter is invalid, then an error will be thrown later + var usePrefix = (adapter && 'use_prefix' in adapter) ? + adapter.use_prefix : true; + + return { + name: usePrefix ? (PouchDB.prefix + name) : name, + adapter: adapterName + }; +} + +// OK, so here's the deal. Consider this code: +// var db1 = new PouchDB('foo'); +// var db2 = new PouchDB('foo'); +// db1.destroy(); +// ^ these two both need to emit 'destroyed' events, +// as well as the PouchDB constructor itself. +// So we have one db object (whichever one got destroy() called on it) +// responsible for emitting the initial event, which then gets emitted +// by the constructor, which then broadcasts it to any other dbs +// that may have been created with the same name. +function prepareForDestruction(self) { + + var destructionListeners = self.constructor._destructionListeners; + + function onDestroyed() { + self.constructor.emit('destroyed', self.name); + } + + function onConstructorDestroyed() { + self.removeListener('destroyed', onDestroyed); + self.emit('destroyed', self); + } + + self.once('destroyed', onDestroyed); + + // in setup.js, the constructor is primed to listen for destroy events + if (!destructionListeners.has(self.name)) { + destructionListeners.set(self.name, []); + } + destructionListeners.get(self.name).push(onConstructorDestroyed); +} + +inherits(PouchDB, AbstractPouchDB); +function PouchDB(name, opts) { + // In Node our test suite only tests this for PouchAlt unfortunately + /* istanbul ignore if */ + if (!(this instanceof PouchDB)) { + return new PouchDB(name, opts); + } + + var self = this; + opts = opts || {}; + + if (name && typeof name === 'object') { + opts = name; + name = opts.name; + delete opts.name; + } + + this.__opts = opts = clone(opts); + + self.auto_compaction = opts.auto_compaction; + self.prefix = PouchDB.prefix; + + if (typeof name !== 'string') { + throw new Error('Missing/invalid DB name'); + } + + var prefixedName = (opts.prefix || '') + name; + var backend = parseAdapter(prefixedName, opts); + + opts.name = backend.name; + opts.adapter = opts.adapter || backend.adapter; + + self.name = name; + self._adapter = opts.adapter; + debug('pouchdb:adapter')('Picked adapter: ' + opts.adapter); + + if (!PouchDB.adapters[opts.adapter] || + !PouchDB.adapters[opts.adapter].valid()) { + throw new Error('Invalid Adapter: ' + opts.adapter); + } + + AbstractPouchDB.call(self); + self.taskqueue = new TaskQueue(); + + self.adapter = opts.adapter; + + PouchDB.adapters[opts.adapter].call(self, opts, function (err) { + if (err) { + return self.taskqueue.fail(err); + } + prepareForDestruction(self); + + self.emit('created', self); + PouchDB.emit('created', self.name); + self.taskqueue.ready(self); + }); + +} + +PouchDB.debug = debug; + +PouchDB.adapters = {}; +PouchDB.preferredAdapters = []; + +PouchDB.prefix = '_pouch_'; + +var eventEmitter = new EventEmitter(); + +function setUpEventEmitter(Pouch) { + Object.keys(EventEmitter.prototype).forEach(function (key) { + if (typeof EventEmitter.prototype[key] === 'function') { + Pouch[key] = eventEmitter[key].bind(eventEmitter); + } + }); + + // these are created in constructor.js, and allow us to notify each DB with + // the same name that it was destroyed, via the constructor object + var destructListeners = Pouch._destructionListeners = new _Map(); + Pouch.on('destroyed', function onConstructorDestroyed(name) { + destructListeners.get(name).forEach(function (callback) { + callback(); + }); + destructListeners.delete(name); + }); +} + +setUpEventEmitter(PouchDB); + +PouchDB.adapter = function (id, obj, addToPreferredAdapters) { + /* istanbul ignore else */ + if (obj.valid()) { + PouchDB.adapters[id] = obj; + if (addToPreferredAdapters) { + PouchDB.preferredAdapters.push(id); + } + } +}; + +PouchDB.plugin = function (obj) { + if (typeof obj === 'function') { // function style for plugins + obj(PouchDB); + } else if (typeof obj !== 'object' || Object.keys(obj).length === 0){ + throw new Error('Invalid plugin: object passed in is empty or not an object'); + } else { + Object.keys(obj).forEach(function (id) { // object style for plugins + PouchDB.prototype[id] = obj[id]; + }); + } + return PouchDB; +}; + +PouchDB.defaults = function (defaultOpts) { + function PouchAlt(name, opts) { + if (!(this instanceof PouchAlt)) { + return new PouchAlt(name, opts); + } + + opts = opts || {}; + + if (name && typeof name === 'object') { + opts = name; + name = opts.name; + delete opts.name; + } + + opts = extend({}, defaultOpts, opts); + PouchDB.call(this, name, opts); + } + + inherits(PouchAlt, PouchDB); + + PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice(); + Object.keys(PouchDB).forEach(function (key) { + if (!(key in PouchAlt)) { + PouchAlt[key] = PouchDB[key]; + } + }); + + return PouchAlt; +}; + +// managed automatically by set-version.js +var version = "6.0.6"; + +PouchDB.version = version; + +function toObject(array) { + return array.reduce(function (obj, item) { + obj[item] = true; + return obj; + }, {}); +} +// List of top level reserved words for doc +var reservedWords = toObject([ + '_id', + '_rev', + '_attachments', + '_deleted', + '_revisions', + '_revs_info', + '_conflicts', + '_deleted_conflicts', + '_local_seq', + '_rev_tree', + //replication documents + '_replication_id', + '_replication_state', + '_replication_state_time', + '_replication_state_reason', + '_replication_stats', + // Specific to Couchbase Sync Gateway + '_removed' +]); + +// List of reserved words that should end up the document +var dataWords = toObject([ + '_attachments', + //replication documents + '_replication_id', + '_replication_state', + '_replication_state_time', + '_replication_state_reason', + '_replication_stats' +]); + +function parseRevisionInfo(rev) { + if (!/^\d+\-./.test(rev)) { + return createError(INVALID_REV); + } + var idx = rev.indexOf('-'); + var left = rev.substring(0, idx); + var right = rev.substring(idx + 1); + return { + prefix: parseInt(left, 10), + id: right + }; +} + +function makeRevTreeFromRevisions(revisions, opts) { + var pos = revisions.start - revisions.ids.length + 1; + + var revisionIds = revisions.ids; + var ids = [revisionIds[0], opts, []]; + + for (var i = 1, len = revisionIds.length; i < len; i++) { + ids = [revisionIds[i], {status: 'missing'}, [ids]]; + } + + return [{ + pos: pos, + ids: ids + }]; +} + +// Preprocess documents, parse their revisions, assign an id and a +// revision for new writes that are missing them, etc +function parseDoc(doc, newEdits) { + + var nRevNum; + var newRevId; + var revInfo; + var opts = {status: 'available'}; + if (doc._deleted) { + opts.deleted = true; + } + + if (newEdits) { + if (!doc._id) { + doc._id = uuid(); + } + newRevId = uuid(32, 16).toLowerCase(); + if (doc._rev) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + doc._rev_tree = [{ + pos: revInfo.prefix, + ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]] + }]; + nRevNum = revInfo.prefix + 1; + } else { + doc._rev_tree = [{ + pos: 1, + ids : [newRevId, opts, []] + }]; + nRevNum = 1; + } + } else { + if (doc._revisions) { + doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); + nRevNum = doc._revisions.start; + newRevId = doc._revisions.ids[0]; + } + if (!doc._rev_tree) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + nRevNum = revInfo.prefix; + newRevId = revInfo.id; + doc._rev_tree = [{ + pos: nRevNum, + ids: [newRevId, opts, []] + }]; + } + } + + invalidIdError(doc._id); + + doc._rev = nRevNum + '-' + newRevId; + + var result = {metadata : {}, data : {}}; + for (var key in doc) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(doc, key)) { + var specialKey = key[0] === '_'; + if (specialKey && !reservedWords[key]) { + var error = createError(DOC_VALIDATION, key); + error.message = DOC_VALIDATION.message + ': ' + key; + throw error; + } else if (specialKey && !dataWords[key]) { + result.metadata[key.slice(1)] = doc[key]; + } else { + result.data[key] = doc[key]; + } + } + } + return result; +} + +var atob$1 = function (str) { + return atob(str); +}; + +var btoa$1 = function (str) { + return btoa(str); +}; + +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor (e.g. +// old QtWebKit versions, Android < 4.4). +function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== "TypeError") { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : + typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : + typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : + WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} + +// From http://stackoverflow.com/questions/14967647/ (continues on next line) +// encode-decode-image-with-base64-breaks-image (2013-04-21) +function binaryStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} + +function binStringToBluffer(binString, type) { + return createBlob([binaryStringToArrayBuffer(binString)], {type: type}); +} + +function b64ToBluffer(b64, type) { + return binStringToBluffer(atob$1(b64), type); +} + +//Can't find original post, but this is close +//http://stackoverflow.com/questions/6965107/ (continues on next line) +//converting-between-strings-and-arraybuffers +function arrayBufferToBinaryString(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var length = bytes.byteLength; + for (var i = 0; i < length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return binary; +} + +// shim for browsers that don't support it +function readAsBinaryString(blob, callback) { + if (typeof FileReader === 'undefined') { + // fix for Firefox in a web worker + // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 + return callback(arrayBufferToBinaryString( + new FileReaderSync().readAsArrayBuffer(blob))); + } + + var reader = new FileReader(); + var hasBinaryString = typeof reader.readAsBinaryString === 'function'; + reader.onloadend = function (e) { + var result = e.target.result || ''; + if (hasBinaryString) { + return callback(result); + } + callback(arrayBufferToBinaryString(result)); + }; + if (hasBinaryString) { + reader.readAsBinaryString(blob); + } else { + reader.readAsArrayBuffer(blob); + } +} + +function blobToBinaryString(blobOrBuffer, callback) { + readAsBinaryString(blobOrBuffer, function (bin) { + callback(bin); + }); +} + +function blobToBase64(blobOrBuffer, callback) { + blobToBinaryString(blobOrBuffer, function (base64) { + callback(btoa$1(base64)); + }); +} + +// simplified API. universal browser support is assumed +function readAsArrayBuffer(blob, callback) { + if (typeof FileReader === 'undefined') { + // fix for Firefox in a web worker: + // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 + return callback(new FileReaderSync().readAsArrayBuffer(blob)); + } + + var reader = new FileReader(); + reader.onloadend = function (e) { + var result = e.target.result || new ArrayBuffer(0); + callback(result); + }; + reader.readAsArrayBuffer(blob); +} + +var setImmediateShim = global.setImmediate || global.setTimeout; +var MD5_CHUNK_SIZE = 32768; + +function rawToBase64(raw) { + return btoa$1(raw); +} + +function sliceBlob(blob, start, end) { + if (blob.webkitSlice) { + return blob.webkitSlice(start, end); + } + return blob.slice(start, end); +} + +function appendBlob(buffer, blob, start, end, callback) { + if (start > 0 || end < blob.size) { + // only slice blob if we really need to + blob = sliceBlob(blob, start, end); + } + readAsArrayBuffer(blob, function (arrayBuffer) { + buffer.append(arrayBuffer); + callback(); + }); +} + +function appendString(buffer, string, start, end, callback) { + if (start > 0 || end < string.length) { + // only create a substring if we really need to + string = string.substring(start, end); + } + buffer.appendBinary(string); + callback(); +} + +function binaryMd5(data, callback) { + var inputIsString = typeof data === 'string'; + var len = inputIsString ? data.length : data.size; + var chunkSize = Math.min(MD5_CHUNK_SIZE, len); + var chunks = Math.ceil(len / chunkSize); + var currentChunk = 0; + var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer(); + + var append = inputIsString ? appendString : appendBlob; + + function next() { + setImmediateShim(loadNextChunk); + } + + function done() { + var raw = buffer.end(true); + var base64 = rawToBase64(raw); + callback(base64); + buffer.destroy(); + } + + function loadNextChunk() { + var start = currentChunk * chunkSize; + var end = start + chunkSize; + currentChunk++; + if (currentChunk < chunks) { + append(buffer, data, start, end, next); + } else { + append(buffer, data, start, end, done); + } + } + loadNextChunk(); +} + +function stringMd5(string) { + return Md5.hash(string); +} + +function parseBase64(data) { + try { + return atob$1(data); + } catch (e) { + var err = createError(BAD_ARG, + 'Attachment is not a valid base64 string'); + return {error: err}; + } +} + +function preprocessString(att, blobType, callback) { + var asBinary = parseBase64(att.data); + if (asBinary.error) { + return callback(asBinary.error); + } + + att.length = asBinary.length; + if (blobType === 'blob') { + att.data = binStringToBluffer(asBinary, att.content_type); + } else if (blobType === 'base64') { + att.data = btoa$1(asBinary); + } else { // binary + att.data = asBinary; + } + binaryMd5(asBinary, function (result) { + att.digest = 'md5-' + result; + callback(); + }); +} + +function preprocessBlob(att, blobType, callback) { + binaryMd5(att.data, function (md5) { + att.digest = 'md5-' + md5; + // size is for blobs (browser), length is for buffers (node) + att.length = att.data.size || att.data.length || 0; + if (blobType === 'binary') { + blobToBinaryString(att.data, function (binString) { + att.data = binString; + callback(); + }); + } else if (blobType === 'base64') { + blobToBase64(att.data, function (b64) { + att.data = b64; + callback(); + }); + } else { + callback(); + } + }); +} + +function preprocessAttachment(att, blobType, callback) { + if (att.stub) { + return callback(); + } + if (typeof att.data === 'string') { // input is a base64 string + preprocessString(att, blobType, callback); + } else { // input is a blob + preprocessBlob(att, blobType, callback); + } +} + +function preprocessAttachments(docInfos, blobType, callback) { + + if (!docInfos.length) { + return callback(); + } + + var docv = 0; + var overallErr; + + docInfos.forEach(function (docInfo) { + var attachments = docInfo.data && docInfo.data._attachments ? + Object.keys(docInfo.data._attachments) : []; + var recv = 0; + + if (!attachments.length) { + return done(); + } + + function processedAttachment(err) { + overallErr = err; + recv++; + if (recv === attachments.length) { + done(); + } + } + + for (var key in docInfo.data._attachments) { + if (docInfo.data._attachments.hasOwnProperty(key)) { + preprocessAttachment(docInfo.data._attachments[key], + blobType, processedAttachment); + } + } + }); + + function done() { + docv++; + if (docInfos.length === docv) { + if (overallErr) { + callback(overallErr); + } else { + callback(); + } + } + } +} + +function updateDoc(revLimit, prev, docInfo, results, + i, cb, writeDoc, newEdits) { + + if (revExists(prev.rev_tree, docInfo.metadata.rev)) { + results[i] = docInfo; + return cb(); + } + + // sometimes this is pre-calculated. historically not always + var previousWinningRev = prev.winningRev || winningRev(prev); + var previouslyDeleted = 'deleted' in prev ? prev.deleted : + isDeleted(prev, previousWinningRev); + var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted : + isDeleted(docInfo.metadata); + var isRoot = /^1-/.test(docInfo.metadata.rev); + + if (previouslyDeleted && !deleted && newEdits && isRoot) { + var newDoc = docInfo.data; + newDoc._rev = previousWinningRev; + newDoc._id = docInfo.metadata.id; + docInfo = parseDoc(newDoc, newEdits); + } + + var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); + + var inConflict = newEdits && (((previouslyDeleted && deleted) || + (!previouslyDeleted && merged.conflicts !== 'new_leaf') || + (previouslyDeleted && !deleted && merged.conflicts === 'new_branch'))); + + if (inConflict) { + var err = createError(REV_CONFLICT); + results[i] = err; + return cb(); + } + + var newRev = docInfo.metadata.rev; + docInfo.metadata.rev_tree = merged.tree; + docInfo.stemmedRevs = merged.stemmedRevs || []; + /* istanbul ignore else */ + if (prev.rev_map) { + docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb + } + + // recalculate + var winningRev$$ = winningRev(docInfo.metadata); + var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$); + + // calculate the total number of documents that were added/removed, + // from the perspective of total_rows/doc_count + var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 : + previouslyDeleted < winningRevIsDeleted ? -1 : 1; + + var newRevIsDeleted; + if (newRev === winningRev$$) { + // if the new rev is the same as the winning rev, we can reuse that value + newRevIsDeleted = winningRevIsDeleted; + } else { + // if they're not the same, then we need to recalculate + newRevIsDeleted = isDeleted(docInfo.metadata, newRev); + } + + writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted, + true, delta, i, cb); +} + +function rootIsMissing(docInfo) { + return docInfo.metadata.rev_tree[0].ids[1].status === 'missing'; +} + +function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, + writeDoc, opts, overallCallback) { + + // Default to 1000 locally + revLimit = revLimit || 1000; + + function insertDoc(docInfo, resultsIdx, callback) { + // Cant insert new deleted documents + var winningRev$$ = winningRev(docInfo.metadata); + var deleted = isDeleted(docInfo.metadata, winningRev$$); + if ('was_delete' in opts && deleted) { + results[resultsIdx] = createError(MISSING_DOC, 'deleted'); + return callback(); + } + + // 4712 - detect whether a new document was inserted with a _rev + var inConflict = newEdits && rootIsMissing(docInfo); + + if (inConflict) { + var err = createError(REV_CONFLICT); + results[resultsIdx] = err; + return callback(); + } + + var delta = deleted ? 0 : 1; + + writeDoc(docInfo, winningRev$$, deleted, deleted, false, + delta, resultsIdx, callback); + } + + var newEdits = opts.new_edits; + var idsToDocs = new _Map(); + + var docsDone = 0; + var docsToDo = docInfos.length; + + function checkAllDocsDone() { + if (++docsDone === docsToDo && overallCallback) { + overallCallback(); + } + } + + docInfos.forEach(function (currentDoc, resultsIdx) { + + if (currentDoc._id && isLocalId(currentDoc._id)) { + var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal'; + api[fun](currentDoc, {ctx: tx}, function (err, res) { + results[resultsIdx] = err || res; + checkAllDocsDone(); + }); + return; + } + + var id = currentDoc.metadata.id; + if (idsToDocs.has(id)) { + docsToDo--; // duplicate + idsToDocs.get(id).push([currentDoc, resultsIdx]); + } else { + idsToDocs.set(id, [[currentDoc, resultsIdx]]); + } + }); + + // in the case of new_edits, the user can provide multiple docs + // with the same id. these need to be processed sequentially + idsToDocs.forEach(function (docs, id) { + var numDone = 0; + + function docWritten() { + if (++numDone < docs.length) { + nextDoc(); + } else { + checkAllDocsDone(); + } + } + function nextDoc() { + var value = docs[numDone]; + var currentDoc = value[0]; + var resultsIdx = value[1]; + + if (fetchedDocs.has(id)) { + updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results, + resultsIdx, docWritten, writeDoc, newEdits); + } else { + // Ensure stemming applies to new writes as well + var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); + currentDoc.metadata.rev_tree = merged.tree; + currentDoc.stemmedRevs = merged.stemmedRevs || []; + insertDoc(currentDoc, resultsIdx, docWritten); + } + } + nextDoc(); + }); +} + +// IndexedDB requires a versioned database structure, so we use the +// version here to manage migrations. +var ADAPTER_VERSION = 5; + +// The object stores created for each database +// DOC_STORE stores the document meta data, its revision history and state +// Keyed by document id +var DOC_STORE = 'document-store'; +// BY_SEQ_STORE stores a particular version of a document, keyed by its +// sequence id +var BY_SEQ_STORE = 'by-sequence'; +// Where we store attachments +var ATTACH_STORE = 'attach-store'; +// Where we store many-to-many relations +// between attachment digests and seqs +var ATTACH_AND_SEQ_STORE = 'attach-seq-store'; + +// Where we store database-wide meta data in a single record +// keyed by id: META_STORE +var META_STORE = 'meta-store'; +// Where we store local documents +var LOCAL_STORE = 'local-store'; +// Where we detect blob support +var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support'; + +function slowJsonParse(str) { + try { + return JSON.parse(str); + } catch (e) { + /* istanbul ignore next */ + return vuvuzela.parse(str); + } +} + +function safeJsonParse(str) { + // try/catch is deoptimized in V8, leading to slower + // times than we'd like to have. Most documents are _not_ + // huge, and do not require a slower code path just to parse them. + // We can be pretty sure that a document under 50000 characters + // will not be so deeply nested as to throw a stack overflow error + // (depends on the engine and available memory, though, so this is + // just a hunch). 50000 was chosen based on the average length + // of this string in our test suite, to try to find a number that covers + // most of our test cases (26 over this size, 26378 under it). + if (str.length < 50000) { + return JSON.parse(str); + } + return slowJsonParse(str); +} + +function safeJsonStringify(json) { + try { + return JSON.stringify(json); + } catch (e) { + /* istanbul ignore next */ + return vuvuzela.stringify(json); + } +} + +function tryCode(fun, that, args, PouchDB) { + try { + fun.apply(that, args); + } catch (err) { + // Shouldn't happen, but in some odd cases + // IndexedDB implementations might throw a sync + // error, in which case this will at least log it. + PouchDB.emit('error', err); + } +} + +var taskQueue = { + running: false, + queue: [] +}; + +function applyNext(PouchDB) { + if (taskQueue.running || !taskQueue.queue.length) { + return; + } + taskQueue.running = true; + var item = taskQueue.queue.shift(); + item.action(function (err, res) { + tryCode(item.callback, this, [err, res], PouchDB); + taskQueue.running = false; + process.nextTick(function () { + applyNext(PouchDB); + }); + }); +} + +function idbError(callback) { + return function (evt) { + var message = 'unknown_error'; + if (evt.target && evt.target.error) { + message = evt.target.error.name || evt.target.error.message; + } + callback(createError(IDB_ERROR, message, evt.type)); + }; +} + +// Unfortunately, the metadata has to be stringified +// when it is put into the database, because otherwise +// IndexedDB can throw errors for deeply-nested objects. +// Originally we just used JSON.parse/JSON.stringify; now +// we use this custom vuvuzela library that avoids recursion. +// If we could do it all over again, we'd probably use a +// format for the revision trees other than JSON. +function encodeMetadata(metadata, winningRev, deleted) { + return { + data: safeJsonStringify(metadata), + winningRev: winningRev, + deletedOrLocal: deleted ? '1' : '0', + seq: metadata.seq, // highest seq for this doc + id: metadata.id + }; +} + +function decodeMetadata(storedObject) { + if (!storedObject) { + return null; + } + var metadata = safeJsonParse(storedObject.data); + metadata.winningRev = storedObject.winningRev; + metadata.deleted = storedObject.deletedOrLocal === '1'; + metadata.seq = storedObject.seq; + return metadata; +} + +// read the doc back out from the database. we don't store the +// _id or _rev because we already have _doc_id_rev. +function decodeDoc(doc) { + if (!doc) { + return doc; + } + var idx = doc._doc_id_rev.lastIndexOf(':'); + doc._id = doc._doc_id_rev.substring(0, idx - 1); + doc._rev = doc._doc_id_rev.substring(idx + 1); + delete doc._doc_id_rev; + return doc; +} + +// Read a blob from the database, encoding as necessary +// and translating from base64 if the IDB doesn't support +// native Blobs +function readBlobData(body, type, asBlob, callback) { + if (asBlob) { + if (!body) { + callback(createBlob([''], {type: type})); + } else if (typeof body !== 'string') { // we have blob support + callback(body); + } else { // no blob support + callback(b64ToBluffer(body, type)); + } + } else { // as base64 string + if (!body) { + callback(''); + } else if (typeof body !== 'string') { // we have blob support + readAsBinaryString(body, function (binary) { + callback(btoa$1(binary)); + }); + } else { // no blob support + callback(body); + } + } +} + +function fetchAttachmentsIfNecessary(doc, opts, txn, cb) { + var attachments = Object.keys(doc._attachments || {}); + if (!attachments.length) { + return cb && cb(); + } + var numDone = 0; + + function checkDone() { + if (++numDone === attachments.length && cb) { + cb(); + } + } + + function fetchAttachment(doc, att) { + var attObj = doc._attachments[att]; + var digest = attObj.digest; + var req = txn.objectStore(ATTACH_STORE).get(digest); + req.onsuccess = function (e) { + attObj.body = e.target.result.body; + checkDone(); + }; + } + + attachments.forEach(function (att) { + if (opts.attachments && opts.include_docs) { + fetchAttachment(doc, att); + } else { + doc._attachments[att].stub = true; + checkDone(); + } + }); +} + +// IDB-specific postprocessing necessary because +// we don't know whether we stored a true Blob or +// a base64-encoded string, and if it's a Blob it +// needs to be read outside of the transaction context +function postProcessAttachments(results, asBlob) { + return PouchPromise.all(results.map(function (row) { + if (row.doc && row.doc._attachments) { + var attNames = Object.keys(row.doc._attachments); + return PouchPromise.all(attNames.map(function (att) { + var attObj = row.doc._attachments[att]; + if (!('body' in attObj)) { // already processed + return; + } + var body = attObj.body; + var type = attObj.content_type; + return new PouchPromise(function (resolve) { + readBlobData(body, type, asBlob, function (data) { + row.doc._attachments[att] = extend( + pick(attObj, ['digest', 'content_type']), + {data: data} + ); + resolve(); + }); + }); + })); + } + })); +} + +function compactRevs(revs, docId, txn) { + + var possiblyOrphanedDigests = []; + var seqStore = txn.objectStore(BY_SEQ_STORE); + var attStore = txn.objectStore(ATTACH_STORE); + var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + var count = revs.length; + + function checkDone() { + count--; + if (!count) { // done processing all revs + deleteOrphanedAttachments(); + } + } + + function deleteOrphanedAttachments() { + if (!possiblyOrphanedDigests.length) { + return; + } + possiblyOrphanedDigests.forEach(function (digest) { + var countReq = attAndSeqStore.index('digestSeq').count( + IDBKeyRange.bound( + digest + '::', digest + '::\uffff', false, false)); + countReq.onsuccess = function (e) { + var count = e.target.result; + if (!count) { + // orphaned + attStore.delete(digest); + } + }; + }); + } + + revs.forEach(function (rev) { + var index = seqStore.index('_doc_id_rev'); + var key = docId + "::" + rev; + index.getKey(key).onsuccess = function (e) { + var seq = e.target.result; + if (typeof seq !== 'number') { + return checkDone(); + } + seqStore.delete(seq); + + var cursor = attAndSeqStore.index('seq') + .openCursor(IDBKeyRange.only(seq)); + + cursor.onsuccess = function (event) { + var cursor = event.target.result; + if (cursor) { + var digest = cursor.value.digestSeq.split('::')[0]; + possiblyOrphanedDigests.push(digest); + attAndSeqStore.delete(cursor.primaryKey); + cursor.continue(); + } else { // done + checkDone(); + } + }; + }; + }); +} + +function openTransactionSafely(idb, stores, mode) { + try { + return { + txn: idb.transaction(stores, mode) + }; + } catch (err) { + return { + error: err + }; + } +} + +function idbBulkDocs(dbOpts, req, opts, api, idb, idbChanges, callback) { + var docInfos = req.docs; + var txn; + var docStore; + var bySeqStore; + var attachStore; + var attachAndSeqStore; + var docInfoError; + var docCountDelta = 0; + + for (var i = 0, len = docInfos.length; i < len; i++) { + var doc = docInfos[i]; + if (doc._id && isLocalId(doc._id)) { + continue; + } + doc = docInfos[i] = parseDoc(doc, opts.new_edits); + if (doc.error && !docInfoError) { + docInfoError = doc; + } + } + + if (docInfoError) { + return callback(docInfoError); + } + + var results = new Array(docInfos.length); + var fetchedDocs = new _Map(); + var preconditionErrored = false; + var blobType = api._meta.blobSupport ? 'blob' : 'base64'; + + preprocessAttachments(docInfos, blobType, function (err) { + if (err) { + return callback(err); + } + startTransaction(); + }); + + function startTransaction() { + + var stores = [ + DOC_STORE, BY_SEQ_STORE, + ATTACH_STORE, + LOCAL_STORE, ATTACH_AND_SEQ_STORE + ]; + var txnResult = openTransactionSafely(idb, stores, 'readwrite'); + if (txnResult.error) { + return callback(txnResult.error); + } + txn = txnResult.txn; + txn.onabort = idbError(callback); + txn.ontimeout = idbError(callback); + txn.oncomplete = complete; + docStore = txn.objectStore(DOC_STORE); + bySeqStore = txn.objectStore(BY_SEQ_STORE); + attachStore = txn.objectStore(ATTACH_STORE); + attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + + verifyAttachments(function (err) { + if (err) { + preconditionErrored = true; + return callback(err); + } + fetchExistingDocs(); + }); + } + + function idbProcessDocs() { + processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs, + txn, results, writeDoc, opts); + } + + function fetchExistingDocs() { + + if (!docInfos.length) { + return; + } + + var numFetched = 0; + + function checkDone() { + if (++numFetched === docInfos.length) { + idbProcessDocs(); + } + } + + function readMetadata(event) { + var metadata = decodeMetadata(event.target.result); + + if (metadata) { + fetchedDocs.set(metadata.id, metadata); + } + checkDone(); + } + + for (var i = 0, len = docInfos.length; i < len; i++) { + var docInfo = docInfos[i]; + if (docInfo._id && isLocalId(docInfo._id)) { + checkDone(); // skip local docs + continue; + } + var req = docStore.get(docInfo.metadata.id); + req.onsuccess = readMetadata; + } + } + + function complete() { + if (preconditionErrored) { + return; + } + + idbChanges.notify(api._meta.name); + api._meta.docCount += docCountDelta; + callback(null, results); + } + + function verifyAttachment(digest, callback) { + + var req = attachStore.get(digest); + req.onsuccess = function (e) { + if (!e.target.result) { + var err = createError(MISSING_STUB, + 'unknown stub attachment with digest ' + + digest); + err.status = 412; + callback(err); + } else { + callback(); + } + }; + } + + function verifyAttachments(finish) { + + + var digests = []; + docInfos.forEach(function (docInfo) { + if (docInfo.data && docInfo.data._attachments) { + Object.keys(docInfo.data._attachments).forEach(function (filename) { + var att = docInfo.data._attachments[filename]; + if (att.stub) { + digests.push(att.digest); + } + }); + } + }); + if (!digests.length) { + return finish(); + } + var numDone = 0; + var err; + + function checkDone() { + if (++numDone === digests.length) { + finish(err); + } + } + digests.forEach(function (digest) { + verifyAttachment(digest, function (attErr) { + if (attErr && !err) { + err = attErr; + } + checkDone(); + }); + }); + } + + function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, + isUpdate, delta, resultsIdx, callback) { + + docCountDelta += delta; + + docInfo.metadata.winningRev = winningRev; + docInfo.metadata.deleted = winningRevIsDeleted; + + var doc = docInfo.data; + doc._id = docInfo.metadata.id; + doc._rev = docInfo.metadata.rev; + + if (newRevIsDeleted) { + doc._deleted = true; + } + + var hasAttachments = doc._attachments && + Object.keys(doc._attachments).length; + if (hasAttachments) { + return writeAttachments(docInfo, winningRev, winningRevIsDeleted, + isUpdate, resultsIdx, callback); + } + + finishDoc(docInfo, winningRev, winningRevIsDeleted, + isUpdate, resultsIdx, callback); + } + + function finishDoc(docInfo, winningRev, winningRevIsDeleted, + isUpdate, resultsIdx, callback) { + + var doc = docInfo.data; + var metadata = docInfo.metadata; + + doc._doc_id_rev = metadata.id + '::' + metadata.rev; + delete doc._id; + delete doc._rev; + + function afterPutDoc(e) { + var revsToDelete = docInfo.stemmedRevs || []; + + if (isUpdate && api.auto_compaction) { + revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata)); + } + + if (revsToDelete && revsToDelete.length) { + compactRevs(revsToDelete, docInfo.metadata.id, txn); + } + + metadata.seq = e.target.result; + // Current _rev is calculated from _rev_tree on read + delete metadata.rev; + var metadataToStore = encodeMetadata(metadata, winningRev, + winningRevIsDeleted); + var metaDataReq = docStore.put(metadataToStore); + metaDataReq.onsuccess = afterPutMetadata; + } + + function afterPutDocError(e) { + // ConstraintError, need to update, not put (see #1638 for details) + e.preventDefault(); // avoid transaction abort + e.stopPropagation(); // avoid transaction onerror + var index = bySeqStore.index('_doc_id_rev'); + var getKeyReq = index.getKey(doc._doc_id_rev); + getKeyReq.onsuccess = function (e) { + var putReq = bySeqStore.put(doc, e.target.result); + putReq.onsuccess = afterPutDoc; + }; + } + + function afterPutMetadata() { + results[resultsIdx] = { + ok: true, + id: metadata.id, + rev: winningRev + }; + fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); + insertAttachmentMappings(docInfo, metadata.seq, callback); + } + + var putReq = bySeqStore.put(doc); + + putReq.onsuccess = afterPutDoc; + putReq.onerror = afterPutDocError; + } + + function writeAttachments(docInfo, winningRev, winningRevIsDeleted, + isUpdate, resultsIdx, callback) { + + + var doc = docInfo.data; + + var numDone = 0; + var attachments = Object.keys(doc._attachments); + + function collectResults() { + if (numDone === attachments.length) { + finishDoc(docInfo, winningRev, winningRevIsDeleted, + isUpdate, resultsIdx, callback); + } + } + + function attachmentSaved() { + numDone++; + collectResults(); + } + + attachments.forEach(function (key) { + var att = docInfo.data._attachments[key]; + if (!att.stub) { + var data = att.data; + delete att.data; + att.revpos = parseInt(winningRev, 10); + var digest = att.digest; + saveAttachment(digest, data, attachmentSaved); + } else { + numDone++; + collectResults(); + } + }); + } + + // map seqs to attachment digests, which + // we will need later during compaction + function insertAttachmentMappings(docInfo, seq, callback) { + + var attsAdded = 0; + var attsToAdd = Object.keys(docInfo.data._attachments || {}); + + if (!attsToAdd.length) { + return callback(); + } + + function checkDone() { + if (++attsAdded === attsToAdd.length) { + callback(); + } + } + + function add(att) { + var digest = docInfo.data._attachments[att].digest; + var req = attachAndSeqStore.put({ + seq: seq, + digestSeq: digest + '::' + seq + }); + + req.onsuccess = checkDone; + req.onerror = function (e) { + // this callback is for a constaint error, which we ignore + // because this docid/rev has already been associated with + // the digest (e.g. when new_edits == false) + e.preventDefault(); // avoid transaction abort + e.stopPropagation(); // avoid transaction onerror + checkDone(); + }; + } + for (var i = 0; i < attsToAdd.length; i++) { + add(attsToAdd[i]); // do in parallel + } + } + + function saveAttachment(digest, data, callback) { + + + var getKeyReq = attachStore.count(digest); + getKeyReq.onsuccess = function (e) { + var count = e.target.result; + if (count) { + return callback(); // already exists + } + var newAtt = { + digest: digest, + body: data + }; + var putReq = attachStore.put(newAtt); + putReq.onsuccess = callback; + }; + } +} + +function createKeyRange(start, end, inclusiveEnd, key, descending) { + try { + if (start && end) { + if (descending) { + return IDBKeyRange.bound(end, start, !inclusiveEnd, false); + } else { + return IDBKeyRange.bound(start, end, false, !inclusiveEnd); + } + } else if (start) { + if (descending) { + return IDBKeyRange.upperBound(start); + } else { + return IDBKeyRange.lowerBound(start); + } + } else if (end) { + if (descending) { + return IDBKeyRange.lowerBound(end, !inclusiveEnd); + } else { + return IDBKeyRange.upperBound(end, !inclusiveEnd); + } + } else if (key) { + return IDBKeyRange.only(key); + } + } catch (e) { + return {error: e}; + } + return null; +} + +function handleKeyRangeError(api, opts, err, callback) { + if (err.name === "DataError" && err.code === 0) { + // data error, start is less than end + return callback(null, { + total_rows: api._meta.docCount, + offset: opts.skip, + rows: [] + }); + } + callback(createError(IDB_ERROR, err.name, err.message)); +} + +function idbAllDocs(opts, api, idb, callback) { + + function allDocsQuery(opts, callback) { + var start = 'startkey' in opts ? opts.startkey : false; + var end = 'endkey' in opts ? opts.endkey : false; + var key = 'key' in opts ? opts.key : false; + var skip = opts.skip || 0; + var limit = typeof opts.limit === 'number' ? opts.limit : -1; + var inclusiveEnd = opts.inclusive_end !== false; + var descending = 'descending' in opts && opts.descending ? 'prev' : null; + + var keyRange = createKeyRange(start, end, inclusiveEnd, key, descending); + if (keyRange && keyRange.error) { + return handleKeyRangeError(api, opts, keyRange.error, callback); + } + + var stores = [DOC_STORE, BY_SEQ_STORE]; + + if (opts.attachments) { + stores.push(ATTACH_STORE); + } + var txnResult = openTransactionSafely(idb, stores, 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + var txn = txnResult.txn; + var docStore = txn.objectStore(DOC_STORE); + var seqStore = txn.objectStore(BY_SEQ_STORE); + var cursor = descending ? + docStore.openCursor(keyRange, descending) : + docStore.openCursor(keyRange); + var docIdRevIndex = seqStore.index('_doc_id_rev'); + var results = []; + var docCount = 0; + + // if the user specifies include_docs=true, then we don't + // want to block the main cursor while we're fetching the doc + function fetchDocAsynchronously(metadata, row, winningRev) { + var key = metadata.id + "::" + winningRev; + docIdRevIndex.get(key).onsuccess = function onGetDoc(e) { + row.doc = decodeDoc(e.target.result); + if (opts.conflicts) { + row.doc._conflicts = collectConflicts(metadata); + } + fetchAttachmentsIfNecessary(row.doc, opts, txn); + }; + } + + function allDocsInner(cursor, winningRev, metadata) { + var row = { + id: metadata.id, + key: metadata.id, + value: { + rev: winningRev + } + }; + var deleted = metadata.deleted; + if (opts.deleted === 'ok') { + results.push(row); + // deleted docs are okay with "keys" requests + if (deleted) { + row.value.deleted = true; + row.doc = null; + } else if (opts.include_docs) { + fetchDocAsynchronously(metadata, row, winningRev); + } + } else if (!deleted && skip-- <= 0) { + results.push(row); + if (opts.include_docs) { + fetchDocAsynchronously(metadata, row, winningRev); + } + if (--limit === 0) { + return; + } + } + cursor.continue(); + } + + function onGetCursor(e) { + docCount = api._meta.docCount; // do this within the txn for consistency + var cursor = e.target.result; + if (!cursor) { + return; + } + var metadata = decodeMetadata(cursor.value); + var winningRev = metadata.winningRev; + + allDocsInner(cursor, winningRev, metadata); + } + + function onResultsReady() { + callback(null, { + total_rows: docCount, + offset: opts.skip, + rows: results + }); + } + + function onTxnComplete() { + if (opts.attachments) { + postProcessAttachments(results, opts.binary).then(onResultsReady); + } else { + onResultsReady(); + } + } + + txn.oncomplete = onTxnComplete; + cursor.onsuccess = onGetCursor; + } + + function allDocs(opts, callback) { + + if (opts.limit === 0) { + return callback(null, { + total_rows: api._meta.docCount, + offset: opts.skip, + rows: [] + }); + } + allDocsQuery(opts, callback); + } + + allDocs(opts, callback); +} + +// +// Blobs are not supported in all versions of IndexedDB, notably +// Chrome <37 and Android <5. In those versions, storing a blob will throw. +// +// Various other blob bugs exist in Chrome v37-42 (inclusive). +// Detecting them is expensive and confusing to users, and Chrome 37-42 +// is at very low usage worldwide, so we do a hacky userAgent check instead. +// +// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 +// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 +// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 +// +function checkBlobSupport(txn) { + return new PouchPromise(function (resolve) { + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function (e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function () { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || + parseInt(matchedChrome[1], 10) >= 43); + }; + }).catch(function () { + return false; // error, so assume unsupported + }); +} + +var cachedDBs = new _Map(); +var blobSupportPromise; +var idbChanges = new Changes$1(); +var openReqList = new _Map(); + +function IdbPouch(opts, callback) { + var api = this; + + taskQueue.queue.push({ + action: function (thisCallback) { + init(api, opts, thisCallback); + }, + callback: callback + }); + applyNext(api.constructor); +} + +function init(api, opts, callback) { + + var dbName = opts.name; + + var idb = null; + api._meta = null; + + // called when creating a fresh new database + function createSchema(db) { + var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'}); + db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true}) + .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true}); + db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'}); + db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false}); + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + + // added in v2 + docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); + + // added in v3 + db.createObjectStore(LOCAL_STORE, {keyPath: '_id'}); + + // added in v4 + var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE, + {autoIncrement: true}); + attAndSeqStore.createIndex('seq', 'seq'); + attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true}); + } + + // migration to version 2 + // unfortunately "deletedOrLocal" is a misnomer now that we no longer + // store local docs in the main doc-store, but whaddyagonnado + function addDeletedOrLocalIndex(txn, callback) { + var docStore = txn.objectStore(DOC_STORE); + docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); + + docStore.openCursor().onsuccess = function (event) { + var cursor = event.target.result; + if (cursor) { + var metadata = cursor.value; + var deleted = isDeleted(metadata); + metadata.deletedOrLocal = deleted ? "1" : "0"; + docStore.put(metadata); + cursor.continue(); + } else { + callback(); + } + }; + } + + // migration to version 3 (part 1) + function createLocalStoreSchema(db) { + db.createObjectStore(LOCAL_STORE, {keyPath: '_id'}) + .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true}); + } + + // migration to version 3 (part 2) + function migrateLocalStore(txn, cb) { + var localStore = txn.objectStore(LOCAL_STORE); + var docStore = txn.objectStore(DOC_STORE); + var seqStore = txn.objectStore(BY_SEQ_STORE); + + var cursor = docStore.openCursor(); + cursor.onsuccess = function (event) { + var cursor = event.target.result; + if (cursor) { + var metadata = cursor.value; + var docId = metadata.id; + var local = isLocalId(docId); + var rev = winningRev(metadata); + if (local) { + var docIdRev = docId + "::" + rev; + // remove all seq entries + // associated with this docId + var start = docId + "::"; + var end = docId + "::~"; + var index = seqStore.index('_doc_id_rev'); + var range = IDBKeyRange.bound(start, end, false, false); + var seqCursor = index.openCursor(range); + seqCursor.onsuccess = function (e) { + seqCursor = e.target.result; + if (!seqCursor) { + // done + docStore.delete(cursor.primaryKey); + cursor.continue(); + } else { + var data = seqCursor.value; + if (data._doc_id_rev === docIdRev) { + localStore.put(data); + } + seqStore.delete(seqCursor.primaryKey); + seqCursor.continue(); + } + }; + } else { + cursor.continue(); + } + } else if (cb) { + cb(); + } + }; + } + + // migration to version 4 (part 1) + function addAttachAndSeqStore(db) { + var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE, + {autoIncrement: true}); + attAndSeqStore.createIndex('seq', 'seq'); + attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true}); + } + + // migration to version 4 (part 2) + function migrateAttsAndSeqs(txn, callback) { + var seqStore = txn.objectStore(BY_SEQ_STORE); + var attStore = txn.objectStore(ATTACH_STORE); + var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE); + + // need to actually populate the table. this is the expensive part, + // so as an optimization, check first that this database even + // contains attachments + var req = attStore.count(); + req.onsuccess = function (e) { + var count = e.target.result; + if (!count) { + return callback(); // done + } + + seqStore.openCursor().onsuccess = function (e) { + var cursor = e.target.result; + if (!cursor) { + return callback(); // done + } + var doc = cursor.value; + var seq = cursor.primaryKey; + var atts = Object.keys(doc._attachments || {}); + var digestMap = {}; + for (var j = 0; j < atts.length; j++) { + var att = doc._attachments[atts[j]]; + digestMap[att.digest] = true; // uniq digests, just in case + } + var digests = Object.keys(digestMap); + for (j = 0; j < digests.length; j++) { + var digest = digests[j]; + attAndSeqStore.put({ + seq: seq, + digestSeq: digest + '::' + seq + }); + } + cursor.continue(); + }; + }; + } + + // migration to version 5 + // Instead of relying on on-the-fly migration of metadata, + // this brings the doc-store to its modern form: + // - metadata.winningrev + // - metadata.seq + // - stringify the metadata when storing it + function migrateMetadata(txn) { + + function decodeMetadataCompat(storedObject) { + if (!storedObject.data) { + // old format, when we didn't store it stringified + storedObject.deleted = storedObject.deletedOrLocal === '1'; + return storedObject; + } + return decodeMetadata(storedObject); + } + + // ensure that every metadata has a winningRev and seq, + // which was previously created on-the-fly but better to migrate + var bySeqStore = txn.objectStore(BY_SEQ_STORE); + var docStore = txn.objectStore(DOC_STORE); + var cursor = docStore.openCursor(); + cursor.onsuccess = function (e) { + var cursor = e.target.result; + if (!cursor) { + return; // done + } + var metadata = decodeMetadataCompat(cursor.value); + + metadata.winningRev = metadata.winningRev || + winningRev(metadata); + + function fetchMetadataSeq() { + // metadata.seq was added post-3.2.0, so if it's missing, + // we need to fetch it manually + var start = metadata.id + '::'; + var end = metadata.id + '::\uffff'; + var req = bySeqStore.index('_doc_id_rev').openCursor( + IDBKeyRange.bound(start, end)); + + var metadataSeq = 0; + req.onsuccess = function (e) { + var cursor = e.target.result; + if (!cursor) { + metadata.seq = metadataSeq; + return onGetMetadataSeq(); + } + var seq = cursor.primaryKey; + if (seq > metadataSeq) { + metadataSeq = seq; + } + cursor.continue(); + }; + } + + function onGetMetadataSeq() { + var metadataToStore = encodeMetadata(metadata, + metadata.winningRev, metadata.deleted); + + var req = docStore.put(metadataToStore); + req.onsuccess = function () { + cursor.continue(); + }; + } + + if (metadata.seq) { + return onGetMetadataSeq(); + } + + fetchMetadataSeq(); + }; + + } + + api.type = function () { + return 'idb'; + }; + + api._id = toPromise(function (callback) { + callback(null, api._meta.instanceId); + }); + + api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) { + idbBulkDocs(opts, req, reqOpts, api, idb, idbChanges, callback); + }; + + // First we look up the metadata in the ids database, then we fetch the + // current revision(s) from the by sequence store + api._get = function idb_get(id, opts, callback) { + var doc; + var metadata; + var err; + var txn = opts.ctx; + if (!txn) { + var txnResult = openTransactionSafely(idb, + [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + txn = txnResult.txn; + } + + function finish() { + callback(err, {doc: doc, metadata: metadata, ctx: txn}); + } + + txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) { + metadata = decodeMetadata(e.target.result); + // we can determine the result here if: + // 1. there is no such document + // 2. the document is deleted and we don't ask about specific rev + // When we ask with opts.rev we expect the answer to be either + // doc (possibly with _deleted=true) or missing error + if (!metadata) { + err = createError(MISSING_DOC, 'missing'); + return finish(); + } + if (isDeleted(metadata) && !opts.rev) { + err = createError(MISSING_DOC, "deleted"); + return finish(); + } + var objectStore = txn.objectStore(BY_SEQ_STORE); + + var rev = opts.rev || metadata.winningRev; + var key = metadata.id + '::' + rev; + + objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) { + doc = e.target.result; + if (doc) { + doc = decodeDoc(doc); + } + if (!doc) { + err = createError(MISSING_DOC, 'missing'); + return finish(); + } + finish(); + }; + }; + }; + + api._getAttachment = function (docId, attachId, attachment, opts, callback) { + var txn; + if (opts.ctx) { + txn = opts.ctx; + } else { + var txnResult = openTransactionSafely(idb, + [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + txn = txnResult.txn; + } + var digest = attachment.digest; + var type = attachment.content_type; + + txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) { + var body = e.target.result.body; + readBlobData(body, type, opts.binary, function (blobData) { + callback(null, blobData); + }); + }; + }; + + api._info = function idb_info(callback) { + + if (idb === null || !cachedDBs.has(dbName)) { + var error = new Error('db isn\'t open'); + error.id = 'idbNull'; + return callback(error); + } + var updateSeq; + var docCount; + + var txnResult = openTransactionSafely(idb, [BY_SEQ_STORE], 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + var txn = txnResult.txn; + var cursor = txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev'); + cursor.onsuccess = function (event) { + var cursor = event.target.result; + updateSeq = cursor ? cursor.key : 0; + // count within the same txn for consistency + docCount = api._meta.docCount; + }; + + txn.oncomplete = function () { + callback(null, { + doc_count: docCount, + update_seq: updateSeq, + // for debugging + idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64') + }); + }; + }; + + api._allDocs = function idb_allDocs(opts, callback) { + idbAllDocs(opts, api, idb, callback); + }; + + api._changes = function (opts) { + opts = clone(opts); + + if (opts.continuous) { + var id = dbName + ':' + uuid(); + idbChanges.addListener(dbName, id, api, opts); + idbChanges.notify(dbName); + return { + cancel: function () { + idbChanges.removeListener(dbName, id); + } + }; + } + + var docIds = opts.doc_ids && new _Set(opts.doc_ids); + + opts.since = opts.since || 0; + var lastSeq = opts.since; + + var limit = 'limit' in opts ? opts.limit : -1; + if (limit === 0) { + limit = 1; // per CouchDB _changes spec + } + var returnDocs; + if ('return_docs' in opts) { + returnDocs = opts.return_docs; + } else if ('returnDocs' in opts) { + // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release + returnDocs = opts.returnDocs; + } else { + returnDocs = true; + } + + var results = []; + var numResults = 0; + var filter = filterChange(opts); + var docIdsToMetadata = new _Map(); + + var txn; + var bySeqStore; + var docStore; + var docIdRevIndex; + + function onGetCursor(cursor) { + + var doc = decodeDoc(cursor.value); + var seq = cursor.key; + + if (docIds && !docIds.has(doc._id)) { + return cursor.continue(); + } + + var metadata; + + function onGetMetadata() { + if (metadata.seq !== seq) { + // some other seq is later + return cursor.continue(); + } + + lastSeq = seq; + + if (metadata.winningRev === doc._rev) { + return onGetWinningDoc(doc); + } + + fetchWinningDoc(); + } + + function fetchWinningDoc() { + var docIdRev = doc._id + '::' + metadata.winningRev; + var req = docIdRevIndex.get(docIdRev); + req.onsuccess = function (e) { + onGetWinningDoc(decodeDoc(e.target.result)); + }; + } + + function onGetWinningDoc(winningDoc) { + + var change = opts.processChange(winningDoc, metadata, opts); + change.seq = metadata.seq; + + var filtered = filter(change); + if (typeof filtered === 'object') { + return opts.complete(filtered); + } + + if (filtered) { + numResults++; + if (returnDocs) { + results.push(change); + } + // process the attachment immediately + // for the benefit of live listeners + if (opts.attachments && opts.include_docs) { + fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () { + postProcessAttachments([change], opts.binary).then(function () { + opts.onChange(change); + }); + }); + } else { + opts.onChange(change); + } + } + if (numResults !== limit) { + cursor.continue(); + } + } + + metadata = docIdsToMetadata.get(doc._id); + if (metadata) { // cached + return onGetMetadata(); + } + // metadata not cached, have to go fetch it + docStore.get(doc._id).onsuccess = function (event) { + metadata = decodeMetadata(event.target.result); + docIdsToMetadata.set(doc._id, metadata); + onGetMetadata(); + }; + } + + function onsuccess(event) { + var cursor = event.target.result; + + if (!cursor) { + return; + } + onGetCursor(cursor); + } + + function fetchChanges() { + var objectStores = [DOC_STORE, BY_SEQ_STORE]; + if (opts.attachments) { + objectStores.push(ATTACH_STORE); + } + var txnResult = openTransactionSafely(idb, objectStores, 'readonly'); + if (txnResult.error) { + return opts.complete(txnResult.error); + } + txn = txnResult.txn; + txn.onabort = idbError(opts.complete); + txn.oncomplete = onTxnComplete; + + bySeqStore = txn.objectStore(BY_SEQ_STORE); + docStore = txn.objectStore(DOC_STORE); + docIdRevIndex = bySeqStore.index('_doc_id_rev'); + + var req; + + if (opts.descending) { + req = bySeqStore.openCursor(null, 'prev'); + } else { + req = bySeqStore.openCursor(IDBKeyRange.lowerBound(opts.since, true)); + } + + req.onsuccess = onsuccess; + } + + fetchChanges(); + + function onTxnComplete() { + + function finish() { + opts.complete(null, { + results: results, + last_seq: lastSeq + }); + } + + if (!opts.continuous && opts.attachments) { + // cannot guarantee that postProcessing was already done, + // so do it again + postProcessAttachments(results).then(finish); + } else { + finish(); + } + } + }; + + api._close = function (callback) { + if (idb === null) { + return callback(createError(NOT_OPEN)); + } + + // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close + // "Returns immediately and closes the connection in a separate thread..." + idb.close(); + cachedDBs.delete(dbName); + idb = null; + callback(); + }; + + api._getRevisionTree = function (docId, callback) { + var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + var txn = txnResult.txn; + var req = txn.objectStore(DOC_STORE).get(docId); + req.onsuccess = function (event) { + var doc = decodeMetadata(event.target.result); + if (!doc) { + callback(createError(MISSING_DOC)); + } else { + callback(null, doc.rev_tree); + } + }; + }; + + // This function removes revisions of document docId + // which are listed in revs and sets this document + // revision to to rev_tree + api._doCompaction = function (docId, revs, callback) { + var stores = [ + DOC_STORE, + BY_SEQ_STORE, + ATTACH_STORE, + ATTACH_AND_SEQ_STORE + ]; + var txnResult = openTransactionSafely(idb, stores, 'readwrite'); + if (txnResult.error) { + return callback(txnResult.error); + } + var txn = txnResult.txn; + + var docStore = txn.objectStore(DOC_STORE); + + docStore.get(docId).onsuccess = function (event) { + var metadata = decodeMetadata(event.target.result); + traverseRevTree(metadata.rev_tree, function (isLeaf, pos, + revHash, ctx, opts) { + var rev = pos + '-' + revHash; + if (revs.indexOf(rev) !== -1) { + opts.status = 'missing'; + } + }); + compactRevs(revs, docId, txn); + var winningRev = metadata.winningRev; + var deleted = metadata.deleted; + txn.objectStore(DOC_STORE).put( + encodeMetadata(metadata, winningRev, deleted)); + }; + txn.onabort = idbError(callback); + txn.oncomplete = function () { + callback(); + }; + }; + + + api._getLocal = function (id, callback) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly'); + if (txnResult.error) { + return callback(txnResult.error); + } + var tx = txnResult.txn; + var req = tx.objectStore(LOCAL_STORE).get(id); + + req.onerror = idbError(callback); + req.onsuccess = function (e) { + var doc = e.target.result; + if (!doc) { + callback(createError(MISSING_DOC)); + } else { + delete doc['_doc_id_rev']; // for backwards compat + callback(null, doc); + } + }; + }; + + api._putLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + delete doc._revisions; // ignore this, trust the rev + var oldRev = doc._rev; + var id = doc._id; + if (!oldRev) { + doc._rev = '0-1'; + } else { + doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1); + } + + var tx = opts.ctx; + var ret; + if (!tx) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite'); + if (txnResult.error) { + return callback(txnResult.error); + } + tx = txnResult.txn; + tx.onerror = idbError(callback); + tx.oncomplete = function () { + if (ret) { + callback(null, ret); + } + }; + } + + var oStore = tx.objectStore(LOCAL_STORE); + var req; + if (oldRev) { + req = oStore.get(id); + req.onsuccess = function (e) { + var oldDoc = e.target.result; + if (!oldDoc || oldDoc._rev !== oldRev) { + callback(createError(REV_CONFLICT)); + } else { // update + var req = oStore.put(doc); + req.onsuccess = function () { + ret = {ok: true, id: doc._id, rev: doc._rev}; + if (opts.ctx) { // return immediately + callback(null, ret); + } + }; + } + }; + } else { // new doc + req = oStore.add(doc); + req.onerror = function (e) { + // constraint error, already exists + callback(createError(REV_CONFLICT)); + e.preventDefault(); // avoid transaction abort + e.stopPropagation(); // avoid transaction onerror + }; + req.onsuccess = function () { + ret = {ok: true, id: doc._id, rev: doc._rev}; + if (opts.ctx) { // return immediately + callback(null, ret); + } + }; + } + }; + + api._removeLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var tx = opts.ctx; + if (!tx) { + var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite'); + if (txnResult.error) { + return callback(txnResult.error); + } + tx = txnResult.txn; + tx.oncomplete = function () { + if (ret) { + callback(null, ret); + } + }; + } + var ret; + var id = doc._id; + var oStore = tx.objectStore(LOCAL_STORE); + var req = oStore.get(id); + + req.onerror = idbError(callback); + req.onsuccess = function (e) { + var oldDoc = e.target.result; + if (!oldDoc || oldDoc._rev !== doc._rev) { + callback(createError(MISSING_DOC)); + } else { + oStore.delete(id); + ret = {ok: true, id: id, rev: '0-0'}; + if (opts.ctx) { // return immediately + callback(null, ret); + } + } + }; + }; + + api._destroy = function (opts, callback) { + idbChanges.removeAllListeners(dbName); + + //Close open request for "dbName" database to fix ie delay. + var openReq = openReqList.get(dbName); + if (openReq && openReq.result) { + openReq.result.close(); + cachedDBs.delete(dbName); + } + var req = indexedDB.deleteDatabase(dbName); + + req.onsuccess = function () { + //Remove open request from the list. + openReqList.delete(dbName); + if (hasLocalStorage() && (dbName in localStorage)) { + delete localStorage[dbName]; + } + callback(null, { 'ok': true }); + }; + + req.onerror = idbError(callback); + }; + + var cached = cachedDBs.get(dbName); + + if (cached) { + idb = cached.idb; + api._meta = cached.global; + process.nextTick(function () { + callback(null, api); + }); + return; + } + + var req; + if (opts.storage) { + req = tryStorageOption(dbName, opts.storage); + } else { + req = indexedDB.open(dbName, ADAPTER_VERSION); + } + + openReqList.set(dbName, req); + + req.onupgradeneeded = function (e) { + var db = e.target.result; + if (e.oldVersion < 1) { + return createSchema(db); // new db, initial schema + } + // do migrations + + var txn = e.currentTarget.transaction; + // these migrations have to be done in this function, before + // control is returned to the event loop, because IndexedDB + + if (e.oldVersion < 3) { + createLocalStoreSchema(db); // v2 -> v3 + } + if (e.oldVersion < 4) { + addAttachAndSeqStore(db); // v3 -> v4 + } + + var migrations = [ + addDeletedOrLocalIndex, // v1 -> v2 + migrateLocalStore, // v2 -> v3 + migrateAttsAndSeqs, // v3 -> v4 + migrateMetadata // v4 -> v5 + ]; + + var i = e.oldVersion; + + function next() { + var migration = migrations[i - 1]; + i++; + if (migration) { + migration(txn, next); + } + } + + next(); + }; + + req.onsuccess = function (e) { + + idb = e.target.result; + + idb.onversionchange = function () { + idb.close(); + cachedDBs.delete(dbName); + }; + + idb.onabort = function (e) { + guardedConsole('error', 'Database has a global failure', e.target.error); + idb.close(); + cachedDBs.delete(dbName); + }; + + var txn = idb.transaction([ + META_STORE, + DETECT_BLOB_SUPPORT_STORE, + DOC_STORE + ], 'readwrite'); + + var req = txn.objectStore(META_STORE).get(META_STORE); + + var blobSupport = null; + var docCount = null; + var instanceId = null; + + req.onsuccess = function (e) { + + var checkSetupComplete = function () { + if (blobSupport === null || docCount === null || + instanceId === null) { + return; + } else { + api._meta = { + name: dbName, + instanceId: instanceId, + blobSupport: blobSupport, + docCount: docCount + }; + + cachedDBs.set(dbName, { + idb: idb, + global: api._meta + }); + callback(null, api); + } + }; + + // + // fetch/store the id + // + + var meta = e.target.result || {id: META_STORE}; + if (dbName + '_id' in meta) { + instanceId = meta[dbName + '_id']; + checkSetupComplete(); + } else { + instanceId = uuid(); + meta[dbName + '_id'] = instanceId; + txn.objectStore(META_STORE).put(meta).onsuccess = function () { + checkSetupComplete(); + }; + } + + // + // check blob support + // + + if (!blobSupportPromise) { + // make sure blob support is only checked once + blobSupportPromise = checkBlobSupport(txn); + } + + blobSupportPromise.then(function (val) { + blobSupport = val; + checkSetupComplete(); + }); + + // + // count docs + // + + var index = txn.objectStore(DOC_STORE).index('deletedOrLocal'); + index.count(IDBKeyRange.only('0')).onsuccess = function (e) { + docCount = e.target.result; + checkSetupComplete(); + }; + + }; + }; + + req.onerror = function () { + var msg = 'Failed to open indexedDB, are you in private browsing mode?'; + guardedConsole('error', msg); + callback(createError(IDB_ERROR, msg)); + }; +} + +IdbPouch.valid = function () { + // Issue #2533, we finally gave up on doing bug + // detection instead of browser sniffing. Safari brought us + // to our knees. + var isSafari = typeof openDatabase !== 'undefined' && + /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && + !/Chrome/.test(navigator.userAgent) && + !/BlackBerry/.test(navigator.platform); + + // some outdated implementations of IDB that appear on Samsung + // and HTC Android devices <4.4 are missing IDBKeyRange + return !isSafari && typeof indexedDB !== 'undefined' && + typeof IDBKeyRange !== 'undefined'; +}; + +function tryStorageOption(dbName, storage) { + try { // option only available in Firefox 26+ + return indexedDB.open(dbName, { + version: ADAPTER_VERSION, + storage: storage + }); + } catch(err) { + return indexedDB.open(dbName, ADAPTER_VERSION); + } +} + +function IDBPouch (PouchDB) { + PouchDB.adapter('idb', IdbPouch, true); +} + +// +// Parsing hex strings. Yeah. +// +// So basically we need this because of a bug in WebSQL: +// https://code.google.com/p/chromium/issues/detail?id=422690 +// https://bugs.webkit.org/show_bug.cgi?id=137637 +// +// UTF-8 and UTF-16 are provided as separate functions +// for meager performance improvements +// + +function decodeUtf8(str) { + return decodeURIComponent(escape(str)); +} + +function hexToInt(charCode) { + // '0'-'9' is 48-57 + // 'A'-'F' is 65-70 + // SQLite will only give us uppercase hex + return charCode < 65 ? (charCode - 48) : (charCode - 55); +} + + +// Example: +// pragma encoding=utf8; +// select hex('A'); +// returns '41' +function parseHexUtf8(str, start, end) { + var result = ''; + while (start < end) { + result += String.fromCharCode( + (hexToInt(str.charCodeAt(start++)) << 4) | + hexToInt(str.charCodeAt(start++))); + } + return result; +} + +// Example: +// pragma encoding=utf16; +// select hex('A'); +// returns '4100' +// notice that the 00 comes after the 41 (i.e. it's swizzled) +function parseHexUtf16(str, start, end) { + var result = ''; + while (start < end) { + // UTF-16, so swizzle the bytes + result += String.fromCharCode( + (hexToInt(str.charCodeAt(start + 2)) << 12) | + (hexToInt(str.charCodeAt(start + 3)) << 8) | + (hexToInt(str.charCodeAt(start)) << 4) | + hexToInt(str.charCodeAt(start + 1))); + start += 4; + } + return result; +} + +function parseHexString(str, encoding) { + if (encoding === 'UTF-8') { + return decodeUtf8(parseHexUtf8(str, 0, str.length)); + } else { + return parseHexUtf16(str, 0, str.length); + } +} + +function quote(str) { + return "'" + str + "'"; +} + +var ADAPTER_VERSION$1 = 7; // used to manage migrations + +// The object stores created for each database +// DOC_STORE stores the document meta data, its revision history and state +var DOC_STORE$1 = quote('document-store'); +// BY_SEQ_STORE stores a particular version of a document, keyed by its +// sequence id +var BY_SEQ_STORE$1 = quote('by-sequence'); +// Where we store attachments +var ATTACH_STORE$1 = quote('attach-store'); +var LOCAL_STORE$1 = quote('local-store'); +var META_STORE$1 = quote('metadata-store'); +// where we store many-to-many relations between attachment +// digests and seqs +var ATTACH_AND_SEQ_STORE$1 = quote('attach-seq-store'); + +// escapeBlob and unescapeBlob are workarounds for a websql bug: +// https://code.google.com/p/chromium/issues/detail?id=422690 +// https://bugs.webkit.org/show_bug.cgi?id=137637 +// The goal is to never actually insert the \u0000 character +// in the database. +function escapeBlob(str) { + return str + .replace(/\u0002/g, '\u0002\u0002') + .replace(/\u0001/g, '\u0001\u0002') + .replace(/\u0000/g, '\u0001\u0001'); +} + +function unescapeBlob(str) { + return str + .replace(/\u0001\u0001/g, '\u0000') + .replace(/\u0001\u0002/g, '\u0001') + .replace(/\u0002\u0002/g, '\u0002'); +} + +function stringifyDoc(doc) { + // don't bother storing the id/rev. it uses lots of space, + // in persistent map/reduce especially + delete doc._id; + delete doc._rev; + return JSON.stringify(doc); +} + +function unstringifyDoc(doc, id, rev) { + doc = JSON.parse(doc); + doc._id = id; + doc._rev = rev; + return doc; +} + +// question mark groups IN queries, e.g. 3 -> '(?,?,?)' +function qMarks(num) { + var s = '('; + while (num--) { + s += '?'; + if (num) { + s += ','; + } + } + return s + ')'; +} + +function select(selector, table, joiner, where, orderBy) { + return 'SELECT ' + selector + ' FROM ' + + (typeof table === 'string' ? table : table.join(' JOIN ')) + + (joiner ? (' ON ' + joiner) : '') + + (where ? (' WHERE ' + + (typeof where === 'string' ? where : where.join(' AND '))) : '') + + (orderBy ? (' ORDER BY ' + orderBy) : ''); +} + +function compactRevs$1(revs, docId, tx) { + + if (!revs.length) { + return; + } + + var numDone = 0; + var seqs = []; + + function checkDone() { + if (++numDone === revs.length) { // done + deleteOrphans(); + } + } + + function deleteOrphans() { + // find orphaned attachment digests + + if (!seqs.length) { + return; + } + + var sql = 'SELECT DISTINCT digest AS digest FROM ' + + ATTACH_AND_SEQ_STORE$1 + ' WHERE seq IN ' + qMarks(seqs.length); + + tx.executeSql(sql, seqs, function (tx, res) { + + var digestsToCheck = []; + for (var i = 0; i < res.rows.length; i++) { + digestsToCheck.push(res.rows.item(i).digest); + } + if (!digestsToCheck.length) { + return; + } + + var sql = 'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 + + ' WHERE seq IN (' + + seqs.map(function () { return '?'; }).join(',') + + ')'; + tx.executeSql(sql, seqs, function (tx) { + + var sql = 'SELECT digest FROM ' + ATTACH_AND_SEQ_STORE$1 + + ' WHERE digest IN (' + + digestsToCheck.map(function () { return '?'; }).join(',') + + ')'; + tx.executeSql(sql, digestsToCheck, function (tx, res) { + var nonOrphanedDigests = new _Set(); + for (var i = 0; i < res.rows.length; i++) { + nonOrphanedDigests.add(res.rows.item(i).digest); + } + digestsToCheck.forEach(function (digest) { + if (nonOrphanedDigests.has(digest)) { + return; + } + tx.executeSql( + 'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 + ' WHERE digest=?', + [digest]); + tx.executeSql( + 'DELETE FROM ' + ATTACH_STORE$1 + ' WHERE digest=?', [digest]); + }); + }); + }); + }); + } + + // update by-seq and attach stores in parallel + revs.forEach(function (rev) { + var sql = 'SELECT seq FROM ' + BY_SEQ_STORE$1 + + ' WHERE doc_id=? AND rev=?'; + + tx.executeSql(sql, [docId, rev], function (tx, res) { + if (!res.rows.length) { // already deleted + return checkDone(); + } + var seq = res.rows.item(0).seq; + seqs.push(seq); + + tx.executeSql( + 'DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?', [seq], checkDone); + }); + }); +} + +function websqlError(callback) { + return function (event) { + guardedConsole('error', 'WebSQL threw an error', event); + // event may actually be a SQLError object, so report is as such + var errorNameMatch = event && event.constructor.toString() + .match(/function ([^\(]+)/); + var errorName = (errorNameMatch && errorNameMatch[1]) || event.type; + var errorReason = event.target || event.message; + callback(createError(WSQ_ERROR, errorReason, errorName)); + }; +} + +function getSize(opts) { + if ('size' in opts) { + // triggers immediate popup in iOS, fixes #2347 + // e.g. 5000001 asks for 5 MB, 10000001 asks for 10 MB, + return opts.size * 1000000; + } + // In iOS, doesn't matter as long as it's <= 5000000. + // Except that if you request too much, our tests fail + // because of the native "do you accept?" popup. + // In Android <=4.3, this value is actually used as an + // honest-to-god ceiling for data, so we need to + // set it to a decently high number. + var isAndroid = typeof navigator !== 'undefined' && + /Android/.test(navigator.userAgent); + return isAndroid ? 5000000 : 1; // in PhantomJS, if you use 0 it will crash +} + +function websqlBulkDocs(dbOpts, req, opts, api, db, websqlChanges, callback) { + var newEdits = opts.new_edits; + var userDocs = req.docs; + + // Parse the docs, give them a sequence number for the result + var docInfos = userDocs.map(function (doc) { + if (doc._id && isLocalId(doc._id)) { + return doc; + } + var newDoc = parseDoc(doc, newEdits); + return newDoc; + }); + + var docInfoErrors = docInfos.filter(function (docInfo) { + return docInfo.error; + }); + if (docInfoErrors.length) { + return callback(docInfoErrors[0]); + } + + var tx; + var results = new Array(docInfos.length); + var fetchedDocs = new _Map(); + + var preconditionErrored; + function complete() { + if (preconditionErrored) { + return callback(preconditionErrored); + } + websqlChanges.notify(api._name); + api._docCount = -1; // invalidate + callback(null, results); + } + + function verifyAttachment(digest, callback) { + var sql = 'SELECT count(*) as cnt FROM ' + ATTACH_STORE$1 + + ' WHERE digest=?'; + tx.executeSql(sql, [digest], function (tx, result) { + if (result.rows.item(0).cnt === 0) { + var err = createError(MISSING_STUB, + 'unknown stub attachment with digest ' + + digest); + callback(err); + } else { + callback(); + } + }); + } + + function verifyAttachments(finish) { + var digests = []; + docInfos.forEach(function (docInfo) { + if (docInfo.data && docInfo.data._attachments) { + Object.keys(docInfo.data._attachments).forEach(function (filename) { + var att = docInfo.data._attachments[filename]; + if (att.stub) { + digests.push(att.digest); + } + }); + } + }); + if (!digests.length) { + return finish(); + } + var numDone = 0; + var err; + + function checkDone() { + if (++numDone === digests.length) { + finish(err); + } + } + digests.forEach(function (digest) { + verifyAttachment(digest, function (attErr) { + if (attErr && !err) { + err = attErr; + } + checkDone(); + }); + }); + } + + function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, + isUpdate, delta, resultsIdx, callback) { + + function finish() { + var data = docInfo.data; + var deletedInt = newRevIsDeleted ? 1 : 0; + + var id = data._id; + var rev = data._rev; + var json = stringifyDoc(data); + var sql = 'INSERT INTO ' + BY_SEQ_STORE$1 + + ' (doc_id, rev, json, deleted) VALUES (?, ?, ?, ?);'; + var sqlArgs = [id, rev, json, deletedInt]; + + // map seqs to attachment digests, which + // we will need later during compaction + function insertAttachmentMappings(seq, callback) { + var attsAdded = 0; + var attsToAdd = Object.keys(data._attachments || {}); + + if (!attsToAdd.length) { + return callback(); + } + function checkDone() { + if (++attsAdded === attsToAdd.length) { + callback(); + } + return false; // ack handling a constraint error + } + function add(att) { + var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 + + ' (digest, seq) VALUES (?,?)'; + var sqlArgs = [data._attachments[att].digest, seq]; + tx.executeSql(sql, sqlArgs, checkDone, checkDone); + // second callback is for a constaint error, which we ignore + // because this docid/rev has already been associated with + // the digest (e.g. when new_edits == false) + } + for (var i = 0; i < attsToAdd.length; i++) { + add(attsToAdd[i]); // do in parallel + } + } + + tx.executeSql(sql, sqlArgs, function (tx, result) { + var seq = result.insertId; + insertAttachmentMappings(seq, function () { + dataWritten(tx, seq); + }); + }, function () { + // constraint error, recover by updating instead (see #1638) + var fetchSql = select('seq', BY_SEQ_STORE$1, null, + 'doc_id=? AND rev=?'); + tx.executeSql(fetchSql, [id, rev], function (tx, res) { + var seq = res.rows.item(0).seq; + var sql = 'UPDATE ' + BY_SEQ_STORE$1 + + ' SET json=?, deleted=? WHERE doc_id=? AND rev=?;'; + var sqlArgs = [json, deletedInt, id, rev]; + tx.executeSql(sql, sqlArgs, function (tx) { + insertAttachmentMappings(seq, function () { + dataWritten(tx, seq); + }); + }); + }); + return false; // ack that we've handled the error + }); + } + + function collectResults(attachmentErr) { + if (!err) { + if (attachmentErr) { + err = attachmentErr; + callback(err); + } else if (recv === attachments.length) { + finish(); + } + } + } + + var err = null; + var recv = 0; + + docInfo.data._id = docInfo.metadata.id; + docInfo.data._rev = docInfo.metadata.rev; + var attachments = Object.keys(docInfo.data._attachments || {}); + + + if (newRevIsDeleted) { + docInfo.data._deleted = true; + } + + function attachmentSaved(err) { + recv++; + collectResults(err); + } + + attachments.forEach(function (key) { + var att = docInfo.data._attachments[key]; + if (!att.stub) { + var data = att.data; + delete att.data; + att.revpos = parseInt(winningRev, 10); + var digest = att.digest; + saveAttachment(digest, data, attachmentSaved); + } else { + recv++; + collectResults(); + } + }); + + if (!attachments.length) { + finish(); + } + + function dataWritten(tx, seq) { + var id = docInfo.metadata.id; + + var revsToCompact = docInfo.stemmedRevs || []; + if (isUpdate && api.auto_compaction) { + revsToCompact = compactTree(docInfo.metadata).concat(revsToCompact); + } + if (revsToCompact.length) { + compactRevs$1(revsToCompact, id, tx); + } + + docInfo.metadata.seq = seq; + delete docInfo.metadata.rev; + + var sql = isUpdate ? + 'UPDATE ' + DOC_STORE$1 + + ' SET json=?, max_seq=?, winningseq=' + + '(SELECT seq FROM ' + BY_SEQ_STORE$1 + + ' WHERE doc_id=' + DOC_STORE$1 + '.id AND rev=?) WHERE id=?' + : 'INSERT INTO ' + DOC_STORE$1 + + ' (id, winningseq, max_seq, json) VALUES (?,?,?,?);'; + var metadataStr = safeJsonStringify(docInfo.metadata); + var params = isUpdate ? + [metadataStr, seq, winningRev, id] : + [id, seq, seq, metadataStr]; + tx.executeSql(sql, params, function () { + results[resultsIdx] = { + ok: true, + id: docInfo.metadata.id, + rev: winningRev + }; + fetchedDocs.set(id, docInfo.metadata); + callback(); + }); + } + } + + function websqlProcessDocs() { + processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs, tx, + results, writeDoc, opts); + } + + function fetchExistingDocs(callback) { + if (!docInfos.length) { + return callback(); + } + + var numFetched = 0; + + function checkDone() { + if (++numFetched === docInfos.length) { + callback(); + } + } + + docInfos.forEach(function (docInfo) { + if (docInfo._id && isLocalId(docInfo._id)) { + return checkDone(); // skip local docs + } + var id = docInfo.metadata.id; + tx.executeSql('SELECT json FROM ' + DOC_STORE$1 + + ' WHERE id = ?', [id], function (tx, result) { + if (result.rows.length) { + var metadata = safeJsonParse(result.rows.item(0).json); + fetchedDocs.set(id, metadata); + } + checkDone(); + }); + }); + } + + function saveAttachment(digest, data, callback) { + var sql = 'SELECT digest FROM ' + ATTACH_STORE$1 + ' WHERE digest=?'; + tx.executeSql(sql, [digest], function (tx, result) { + if (result.rows.length) { // attachment already exists + return callback(); + } + // we could just insert before selecting and catch the error, + // but my hunch is that it's cheaper not to serialize the blob + // from JS to C if we don't have to (TODO: confirm this) + sql = 'INSERT INTO ' + ATTACH_STORE$1 + + ' (digest, body, escaped) VALUES (?,?,1)'; + tx.executeSql(sql, [digest, escapeBlob(data)], function () { + callback(); + }, function () { + // ignore constaint errors, means it already exists + callback(); + return false; // ack we handled the error + }); + }); + } + + preprocessAttachments(docInfos, 'binary', function (err) { + if (err) { + return callback(err); + } + db.transaction(function (txn) { + tx = txn; + verifyAttachments(function (err) { + if (err) { + preconditionErrored = err; + } else { + fetchExistingDocs(websqlProcessDocs); + } + }); + }, websqlError(callback), complete); + }); +} + +var cachedDatabases = new _Map(); + +// openDatabase passed in through opts (e.g. for node-websql) +function openDatabaseWithOpts(opts) { + return opts.websql(opts.name, opts.version, opts.description, opts.size); +} + +function openDBSafely(opts) { + try { + return { + db: openDatabaseWithOpts(opts) + }; + } catch (err) { + return { + error: err + }; + } +} + +function openDB$1(opts) { + var cachedResult = cachedDatabases.get(opts.name); + if (!cachedResult) { + cachedResult = openDBSafely(opts); + cachedDatabases.set(opts.name, cachedResult); + } + return cachedResult; +} + +var websqlChanges = new Changes$1(); + +function fetchAttachmentsIfNecessary$1(doc, opts, api, txn, cb) { + var attachments = Object.keys(doc._attachments || {}); + if (!attachments.length) { + return cb && cb(); + } + var numDone = 0; + + function checkDone() { + if (++numDone === attachments.length && cb) { + cb(); + } + } + + function fetchAttachment(doc, att) { + var attObj = doc._attachments[att]; + var attOpts = {binary: opts.binary, ctx: txn}; + api._getAttachment(doc._id, att, attObj, attOpts, function (_, data) { + doc._attachments[att] = extend( + pick(attObj, ['digest', 'content_type']), + { data: data } + ); + checkDone(); + }); + } + + attachments.forEach(function (att) { + if (opts.attachments && opts.include_docs) { + fetchAttachment(doc, att); + } else { + doc._attachments[att].stub = true; + checkDone(); + } + }); +} + +var POUCH_VERSION = 1; + +// these indexes cover the ground for most allDocs queries +var BY_SEQ_STORE_DELETED_INDEX_SQL = + 'CREATE INDEX IF NOT EXISTS \'by-seq-deleted-idx\' ON ' + + BY_SEQ_STORE$1 + ' (seq, deleted)'; +var BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL = + 'CREATE UNIQUE INDEX IF NOT EXISTS \'by-seq-doc-id-rev\' ON ' + + BY_SEQ_STORE$1 + ' (doc_id, rev)'; +var DOC_STORE_WINNINGSEQ_INDEX_SQL = + 'CREATE INDEX IF NOT EXISTS \'doc-winningseq-idx\' ON ' + + DOC_STORE$1 + ' (winningseq)'; +var ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL = + 'CREATE INDEX IF NOT EXISTS \'attach-seq-seq-idx\' ON ' + + ATTACH_AND_SEQ_STORE$1 + ' (seq)'; +var ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL = + 'CREATE UNIQUE INDEX IF NOT EXISTS \'attach-seq-digest-idx\' ON ' + + ATTACH_AND_SEQ_STORE$1 + ' (digest, seq)'; + +var DOC_STORE_AND_BY_SEQ_JOINER = BY_SEQ_STORE$1 + + '.seq = ' + DOC_STORE$1 + '.winningseq'; + +var SELECT_DOCS = BY_SEQ_STORE$1 + '.seq AS seq, ' + + BY_SEQ_STORE$1 + '.deleted AS deleted, ' + + BY_SEQ_STORE$1 + '.json AS data, ' + + BY_SEQ_STORE$1 + '.rev AS rev, ' + + DOC_STORE$1 + '.json AS metadata'; + +function WebSqlPouch$1(opts, callback) { + var api = this; + var instanceId = null; + var size = getSize(opts); + var idRequests = []; + var encoding; + + api._docCount = -1; // cache sqlite count(*) for performance + api._name = opts.name; + + // extend the options here, because sqlite plugin has a ton of options + // and they are constantly changing, so it's more prudent to allow anything + var websqlOpts = extend({}, opts, { + version: POUCH_VERSION, + description: opts.name, + size: size + }); + var openDBResult = openDB$1(websqlOpts); + if (openDBResult.error) { + return websqlError(callback)(openDBResult.error); + } + var db = openDBResult.db; + if (typeof db.readTransaction !== 'function') { + // doesn't exist in sqlite plugin + db.readTransaction = db.transaction; + } + + function dbCreated() { + // note the db name in case the browser upgrades to idb + if (hasLocalStorage()) { + window.localStorage['_pouch__websqldb_' + api._name] = true; + } + callback(null, api); + } + + // In this migration, we added the 'deleted' and 'local' columns to the + // by-seq and doc store tables. + // To preserve existing user data, we re-process all the existing JSON + // and add these values. + // Called migration2 because it corresponds to adapter version (db_version) #2 + function runMigration2(tx, callback) { + // index used for the join in the allDocs query + tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL); + + tx.executeSql('ALTER TABLE ' + BY_SEQ_STORE$1 + + ' ADD COLUMN deleted TINYINT(1) DEFAULT 0', [], function () { + tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL); + tx.executeSql('ALTER TABLE ' + DOC_STORE$1 + + ' ADD COLUMN local TINYINT(1) DEFAULT 0', [], function () { + tx.executeSql('CREATE INDEX IF NOT EXISTS \'doc-store-local-idx\' ON ' + + DOC_STORE$1 + ' (local, id)'); + + var sql = 'SELECT ' + DOC_STORE$1 + '.winningseq AS seq, ' + DOC_STORE$1 + + '.json AS metadata FROM ' + BY_SEQ_STORE$1 + ' JOIN ' + DOC_STORE$1 + + ' ON ' + BY_SEQ_STORE$1 + '.seq = ' + DOC_STORE$1 + '.winningseq'; + + tx.executeSql(sql, [], function (tx, result) { + + var deleted = []; + var local = []; + + for (var i = 0; i < result.rows.length; i++) { + var item = result.rows.item(i); + var seq = item.seq; + var metadata = JSON.parse(item.metadata); + if (isDeleted(metadata)) { + deleted.push(seq); + } + if (isLocalId(metadata.id)) { + local.push(metadata.id); + } + } + tx.executeSql('UPDATE ' + DOC_STORE$1 + 'SET local = 1 WHERE id IN ' + + qMarks(local.length), local, function () { + tx.executeSql('UPDATE ' + BY_SEQ_STORE$1 + + ' SET deleted = 1 WHERE seq IN ' + + qMarks(deleted.length), deleted, callback); + }); + }); + }); + }); + } + + // in this migration, we make all the local docs unversioned + function runMigration3(tx, callback) { + var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 + + ' (id UNIQUE, rev, json)'; + tx.executeSql(local, [], function () { + var sql = 'SELECT ' + DOC_STORE$1 + '.id AS id, ' + + BY_SEQ_STORE$1 + '.json AS data ' + + 'FROM ' + BY_SEQ_STORE$1 + ' JOIN ' + + DOC_STORE$1 + ' ON ' + BY_SEQ_STORE$1 + '.seq = ' + + DOC_STORE$1 + '.winningseq WHERE local = 1'; + tx.executeSql(sql, [], function (tx, res) { + var rows = []; + for (var i = 0; i < res.rows.length; i++) { + rows.push(res.rows.item(i)); + } + function doNext() { + if (!rows.length) { + return callback(tx); + } + var row = rows.shift(); + var rev = JSON.parse(row.data)._rev; + tx.executeSql('INSERT INTO ' + LOCAL_STORE$1 + + ' (id, rev, json) VALUES (?,?,?)', + [row.id, rev, row.data], function (tx) { + tx.executeSql('DELETE FROM ' + DOC_STORE$1 + ' WHERE id=?', + [row.id], function (tx) { + tx.executeSql('DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?', + [row.seq], function () { + doNext(); + }); + }); + }); + } + doNext(); + }); + }); + } + + // in this migration, we remove doc_id_rev and just use rev + function runMigration4(tx, callback) { + + function updateRows(rows) { + function doNext() { + if (!rows.length) { + return callback(tx); + } + var row = rows.shift(); + var doc_id_rev = parseHexString(row.hex, encoding); + var idx = doc_id_rev.lastIndexOf('::'); + var doc_id = doc_id_rev.substring(0, idx); + var rev = doc_id_rev.substring(idx + 2); + var sql = 'UPDATE ' + BY_SEQ_STORE$1 + + ' SET doc_id=?, rev=? WHERE doc_id_rev=?'; + tx.executeSql(sql, [doc_id, rev, doc_id_rev], function () { + doNext(); + }); + } + doNext(); + } + + var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN doc_id'; + tx.executeSql(sql, [], function (tx) { + var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN rev'; + tx.executeSql(sql, [], function (tx) { + tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL, [], function (tx) { + var sql = 'SELECT hex(doc_id_rev) as hex FROM ' + BY_SEQ_STORE$1; + tx.executeSql(sql, [], function (tx, res) { + var rows = []; + for (var i = 0; i < res.rows.length; i++) { + rows.push(res.rows.item(i)); + } + updateRows(rows); + }); + }); + }); + }); + } + + // in this migration, we add the attach_and_seq table + // for issue #2818 + function runMigration5(tx, callback) { + + function migrateAttsAndSeqs(tx) { + // need to actually populate the table. this is the expensive part, + // so as an optimization, check first that this database even + // contains attachments + var sql = 'SELECT COUNT(*) AS cnt FROM ' + ATTACH_STORE$1; + tx.executeSql(sql, [], function (tx, res) { + var count = res.rows.item(0).cnt; + if (!count) { + return callback(tx); + } + + var offset = 0; + var pageSize = 10; + function nextPage() { + var sql = select( + SELECT_DOCS + ', ' + DOC_STORE$1 + '.id AS id', + [DOC_STORE$1, BY_SEQ_STORE$1], + DOC_STORE_AND_BY_SEQ_JOINER, + null, + DOC_STORE$1 + '.id ' + ); + sql += ' LIMIT ' + pageSize + ' OFFSET ' + offset; + offset += pageSize; + tx.executeSql(sql, [], function (tx, res) { + if (!res.rows.length) { + return callback(tx); + } + var digestSeqs = {}; + function addDigestSeq(digest, seq) { + // uniq digest/seq pairs, just in case there are dups + var seqs = digestSeqs[digest] = (digestSeqs[digest] || []); + if (seqs.indexOf(seq) === -1) { + seqs.push(seq); + } + } + for (var i = 0; i < res.rows.length; i++) { + var row = res.rows.item(i); + var doc = unstringifyDoc(row.data, row.id, row.rev); + var atts = Object.keys(doc._attachments || {}); + for (var j = 0; j < atts.length; j++) { + var att = doc._attachments[atts[j]]; + addDigestSeq(att.digest, row.seq); + } + } + var digestSeqPairs = []; + Object.keys(digestSeqs).forEach(function (digest) { + var seqs = digestSeqs[digest]; + seqs.forEach(function (seq) { + digestSeqPairs.push([digest, seq]); + }); + }); + if (!digestSeqPairs.length) { + return nextPage(); + } + var numDone = 0; + digestSeqPairs.forEach(function (pair) { + var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 + + ' (digest, seq) VALUES (?,?)'; + tx.executeSql(sql, pair, function () { + if (++numDone === digestSeqPairs.length) { + nextPage(); + } + }); + }); + }); + } + nextPage(); + }); + } + + var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' + + ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)'; + tx.executeSql(attachAndRev, [], function (tx) { + tx.executeSql( + ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL, [], function (tx) { + tx.executeSql( + ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL, [], + migrateAttsAndSeqs); + }); + }); + } + + // in this migration, we use escapeBlob() and unescapeBlob() + // instead of reading out the binary as HEX, which is slow + function runMigration6(tx, callback) { + var sql = 'ALTER TABLE ' + ATTACH_STORE$1 + + ' ADD COLUMN escaped TINYINT(1) DEFAULT 0'; + tx.executeSql(sql, [], callback); + } + + // issue #3136, in this migration we need a "latest seq" as well + // as the "winning seq" in the doc store + function runMigration7(tx, callback) { + var sql = 'ALTER TABLE ' + DOC_STORE$1 + + ' ADD COLUMN max_seq INTEGER'; + tx.executeSql(sql, [], function (tx) { + var sql = 'UPDATE ' + DOC_STORE$1 + ' SET max_seq=(SELECT MAX(seq) FROM ' + + BY_SEQ_STORE$1 + ' WHERE doc_id=id)'; + tx.executeSql(sql, [], function (tx) { + // add unique index after filling, else we'll get a constraint + // error when we do the ALTER TABLE + var sql = + 'CREATE UNIQUE INDEX IF NOT EXISTS \'doc-max-seq-idx\' ON ' + + DOC_STORE$1 + ' (max_seq)'; + tx.executeSql(sql, [], callback); + }); + }); + } + + function checkEncoding(tx, cb) { + // UTF-8 on chrome/android, UTF-16 on safari < 7.1 + tx.executeSql('SELECT HEX("a") AS hex', [], function (tx, res) { + var hex = res.rows.item(0).hex; + encoding = hex.length === 2 ? 'UTF-8' : 'UTF-16'; + cb(); + } + ); + } + + function onGetInstanceId() { + while (idRequests.length > 0) { + var idCallback = idRequests.pop(); + idCallback(null, instanceId); + } + } + + function onGetVersion(tx, dbVersion) { + if (dbVersion === 0) { + // initial schema + + var meta = 'CREATE TABLE IF NOT EXISTS ' + META_STORE$1 + + ' (dbid, db_version INTEGER)'; + var attach = 'CREATE TABLE IF NOT EXISTS ' + ATTACH_STORE$1 + + ' (digest UNIQUE, escaped TINYINT(1), body BLOB)'; + var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' + + ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)'; + // TODO: migrate winningseq to INTEGER + var doc = 'CREATE TABLE IF NOT EXISTS ' + DOC_STORE$1 + + ' (id unique, json, winningseq, max_seq INTEGER UNIQUE)'; + var seq = 'CREATE TABLE IF NOT EXISTS ' + BY_SEQ_STORE$1 + + ' (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' + + 'json, deleted TINYINT(1), doc_id, rev)'; + var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 + + ' (id UNIQUE, rev, json)'; + + // creates + tx.executeSql(attach); + tx.executeSql(local); + tx.executeSql(attachAndRev, [], function () { + tx.executeSql(ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL); + tx.executeSql(ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL); + }); + tx.executeSql(doc, [], function () { + tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL); + tx.executeSql(seq, [], function () { + tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL); + tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL); + tx.executeSql(meta, [], function () { + // mark the db version, and new dbid + var initSeq = 'INSERT INTO ' + META_STORE$1 + + ' (db_version, dbid) VALUES (?,?)'; + instanceId = uuid(); + var initSeqArgs = [ADAPTER_VERSION$1, instanceId]; + tx.executeSql(initSeq, initSeqArgs, function () { + onGetInstanceId(); + }); + }); + }); + }); + } else { // version > 0 + + var setupDone = function () { + var migrated = dbVersion < ADAPTER_VERSION$1; + if (migrated) { + // update the db version within this transaction + tx.executeSql('UPDATE ' + META_STORE$1 + ' SET db_version = ' + + ADAPTER_VERSION$1); + } + // notify db.id() callers + var sql = 'SELECT dbid FROM ' + META_STORE$1; + tx.executeSql(sql, [], function (tx, result) { + instanceId = result.rows.item(0).dbid; + onGetInstanceId(); + }); + }; + + // would love to use promises here, but then websql + // ends the transaction early + var tasks = [ + runMigration2, + runMigration3, + runMigration4, + runMigration5, + runMigration6, + runMigration7, + setupDone + ]; + + // run each migration sequentially + var i = dbVersion; + var nextMigration = function (tx) { + tasks[i - 1](tx, nextMigration); + i++; + }; + nextMigration(tx); + } + } + + function setup() { + db.transaction(function (tx) { + // first check the encoding + checkEncoding(tx, function () { + // then get the version + fetchVersion(tx); + }); + }, websqlError(callback), dbCreated); + } + + function fetchVersion(tx) { + var sql = 'SELECT sql FROM sqlite_master WHERE tbl_name = ' + META_STORE$1; + tx.executeSql(sql, [], function (tx, result) { + if (!result.rows.length) { + // database hasn't even been created yet (version 0) + onGetVersion(tx, 0); + } else if (!/db_version/.test(result.rows.item(0).sql)) { + // table was created, but without the new db_version column, + // so add it. + tx.executeSql('ALTER TABLE ' + META_STORE$1 + + ' ADD COLUMN db_version INTEGER', [], function () { + // before version 2, this column didn't even exist + onGetVersion(tx, 1); + }); + } else { // column exists, we can safely get it + tx.executeSql('SELECT db_version FROM ' + META_STORE$1, + [], function (tx, result) { + var dbVersion = result.rows.item(0).db_version; + onGetVersion(tx, dbVersion); + }); + } + }); + } + + setup(); + + api.type = function () { + return 'websql'; + }; + + api._id = toPromise(function (callback) { + callback(null, instanceId); + }); + + api._info = function (callback) { + db.readTransaction(function (tx) { + countDocs(tx, function (docCount) { + var sql = 'SELECT MAX(seq) AS seq FROM ' + BY_SEQ_STORE$1; + tx.executeSql(sql, [], function (tx, res) { + var updateSeq = res.rows.item(0).seq || 0; + callback(null, { + doc_count: docCount, + update_seq: updateSeq, + websql_encoding: encoding + }); + }); + }); + }, websqlError(callback)); + }; + + api._bulkDocs = function (req, reqOpts, callback) { + websqlBulkDocs(opts, req, reqOpts, api, db, websqlChanges, callback); + }; + + api._get = function (id, opts, callback) { + var doc; + var metadata; + var err; + var tx = opts.ctx; + if (!tx) { + return db.readTransaction(function (txn) { + api._get(id, extend({ctx: txn}, opts), callback); + }); + } + + function finish() { + callback(err, {doc: doc, metadata: metadata, ctx: tx}); + } + + var sql; + var sqlArgs; + if (opts.rev) { + sql = select( + SELECT_DOCS, + [DOC_STORE$1, BY_SEQ_STORE$1], + DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id', + [BY_SEQ_STORE$1 + '.doc_id=?', BY_SEQ_STORE$1 + '.rev=?']); + sqlArgs = [id, opts.rev]; + } else { + sql = select( + SELECT_DOCS, + [DOC_STORE$1, BY_SEQ_STORE$1], + DOC_STORE_AND_BY_SEQ_JOINER, + DOC_STORE$1 + '.id=?'); + sqlArgs = [id]; + } + tx.executeSql(sql, sqlArgs, function (a, results) { + if (!results.rows.length) { + err = createError(MISSING_DOC, 'missing'); + return finish(); + } + var item = results.rows.item(0); + metadata = safeJsonParse(item.metadata); + if (item.deleted && !opts.rev) { + err = createError(MISSING_DOC, 'deleted'); + return finish(); + } + doc = unstringifyDoc(item.data, metadata.id, item.rev); + finish(); + }); + }; + + function countDocs(tx, callback) { + + if (api._docCount !== -1) { + return callback(api._docCount); + } + + // count the total rows + var sql = select( + 'COUNT(' + DOC_STORE$1 + '.id) AS \'num\'', + [DOC_STORE$1, BY_SEQ_STORE$1], + DOC_STORE_AND_BY_SEQ_JOINER, + BY_SEQ_STORE$1 + '.deleted=0'); + + tx.executeSql(sql, [], function (tx, result) { + api._docCount = result.rows.item(0).num; + callback(api._docCount); + }); + } + + api._allDocs = function (opts, callback) { + var results = []; + var totalRows; + + var start = 'startkey' in opts ? opts.startkey : false; + var end = 'endkey' in opts ? opts.endkey : false; + var key = 'key' in opts ? opts.key : false; + var descending = 'descending' in opts ? opts.descending : false; + var limit = 'limit' in opts ? opts.limit : -1; + var offset = 'skip' in opts ? opts.skip : 0; + var inclusiveEnd = opts.inclusive_end !== false; + + var sqlArgs = []; + var criteria = []; + + if (key !== false) { + criteria.push(DOC_STORE$1 + '.id = ?'); + sqlArgs.push(key); + } else if (start !== false || end !== false) { + if (start !== false) { + criteria.push(DOC_STORE$1 + '.id ' + (descending ? '<=' : '>=') + ' ?'); + sqlArgs.push(start); + } + if (end !== false) { + var comparator = descending ? '>' : '<'; + if (inclusiveEnd) { + comparator += '='; + } + criteria.push(DOC_STORE$1 + '.id ' + comparator + ' ?'); + sqlArgs.push(end); + } + if (key !== false) { + criteria.push(DOC_STORE$1 + '.id = ?'); + sqlArgs.push(key); + } + } + + if (opts.deleted !== 'ok') { + // report deleted if keys are specified + criteria.push(BY_SEQ_STORE$1 + '.deleted = 0'); + } + + db.readTransaction(function (tx) { + + // first count up the total rows + countDocs(tx, function (count) { + totalRows = count; + + if (limit === 0) { + return; + } + + // then actually fetch the documents + var sql = select( + SELECT_DOCS, + [DOC_STORE$1, BY_SEQ_STORE$1], + DOC_STORE_AND_BY_SEQ_JOINER, + criteria, + DOC_STORE$1 + '.id ' + (descending ? 'DESC' : 'ASC') + ); + sql += ' LIMIT ' + limit + ' OFFSET ' + offset; + + tx.executeSql(sql, sqlArgs, function (tx, result) { + for (var i = 0, l = result.rows.length; i < l; i++) { + var item = result.rows.item(i); + var metadata = safeJsonParse(item.metadata); + var id = metadata.id; + var data = unstringifyDoc(item.data, id, item.rev); + var winningRev = data._rev; + var doc = { + id: id, + key: id, + value: {rev: winningRev} + }; + if (opts.include_docs) { + doc.doc = data; + doc.doc._rev = winningRev; + if (opts.conflicts) { + doc.doc._conflicts = collectConflicts(metadata); + } + fetchAttachmentsIfNecessary$1(doc.doc, opts, api, tx); + } + if (item.deleted) { + if (opts.deleted === 'ok') { + doc.value.deleted = true; + doc.doc = null; + } else { + continue; + } + } + results.push(doc); + } + }); + }); + }, websqlError(callback), function () { + callback(null, { + total_rows: totalRows, + offset: opts.skip, + rows: results + }); + }); + }; + + api._changes = function (opts) { + opts = clone(opts); + + if (opts.continuous) { + var id = api._name + ':' + uuid(); + websqlChanges.addListener(api._name, id, api, opts); + websqlChanges.notify(api._name); + return { + cancel: function () { + websqlChanges.removeListener(api._name, id); + } + }; + } + + var descending = opts.descending; + + // Ignore the `since` parameter when `descending` is true + opts.since = opts.since && !descending ? opts.since : 0; + + var limit = 'limit' in opts ? opts.limit : -1; + if (limit === 0) { + limit = 1; // per CouchDB _changes spec + } + + var returnDocs; + if ('return_docs' in opts) { + returnDocs = opts.return_docs; + } else if ('returnDocs' in opts) { + // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release + returnDocs = opts.returnDocs; + } else { + returnDocs = true; + } + var results = []; + var numResults = 0; + + function fetchChanges() { + + var selectStmt = + DOC_STORE$1 + '.json AS metadata, ' + + DOC_STORE$1 + '.max_seq AS maxSeq, ' + + BY_SEQ_STORE$1 + '.json AS winningDoc, ' + + BY_SEQ_STORE$1 + '.rev AS winningRev '; + + var from = DOC_STORE$1 + ' JOIN ' + BY_SEQ_STORE$1; + + var joiner = DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id' + + ' AND ' + DOC_STORE$1 + '.winningseq=' + BY_SEQ_STORE$1 + '.seq'; + + var criteria = ['maxSeq > ?']; + var sqlArgs = [opts.since]; + + if (opts.doc_ids) { + criteria.push(DOC_STORE$1 + '.id IN ' + qMarks(opts.doc_ids.length)); + sqlArgs = sqlArgs.concat(opts.doc_ids); + } + + var orderBy = 'maxSeq ' + (descending ? 'DESC' : 'ASC'); + + var sql = select(selectStmt, from, joiner, criteria, orderBy); + + var filter = filterChange(opts); + if (!opts.view && !opts.filter) { + // we can just limit in the query + sql += ' LIMIT ' + limit; + } + + var lastSeq = opts.since || 0; + db.readTransaction(function (tx) { + tx.executeSql(sql, sqlArgs, function (tx, result) { + function reportChange(change) { + return function () { + opts.onChange(change); + }; + } + for (var i = 0, l = result.rows.length; i < l; i++) { + var item = result.rows.item(i); + var metadata = safeJsonParse(item.metadata); + lastSeq = item.maxSeq; + + var doc = unstringifyDoc(item.winningDoc, metadata.id, + item.winningRev); + var change = opts.processChange(doc, metadata, opts); + change.seq = item.maxSeq; + + var filtered = filter(change); + if (typeof filtered === 'object') { + return opts.complete(filtered); + } + + if (filtered) { + numResults++; + if (returnDocs) { + results.push(change); + } + // process the attachment immediately + // for the benefit of live listeners + if (opts.attachments && opts.include_docs) { + fetchAttachmentsIfNecessary$1(doc, opts, api, tx, + reportChange(change)); + } else { + reportChange(change)(); + } + } + if (numResults === limit) { + break; + } + } + }); + }, websqlError(opts.complete), function () { + if (!opts.continuous) { + opts.complete(null, { + results: results, + last_seq: lastSeq + }); + } + }); + } + + fetchChanges(); + }; + + api._close = function (callback) { + //WebSQL databases do not need to be closed + callback(); + }; + + api._getAttachment = function (docId, attachId, attachment, opts, callback) { + var res; + var tx = opts.ctx; + var digest = attachment.digest; + var type = attachment.content_type; + var sql = 'SELECT escaped, ' + + 'CASE WHEN escaped = 1 THEN body ELSE HEX(body) END AS body FROM ' + + ATTACH_STORE$1 + ' WHERE digest=?'; + tx.executeSql(sql, [digest], function (tx, result) { + // websql has a bug where \u0000 causes early truncation in strings + // and blobs. to work around this, we used to use the hex() function, + // but that's not performant. after migration 6, we remove \u0000 + // and add it back in afterwards + var item = result.rows.item(0); + var data = item.escaped ? unescapeBlob(item.body) : + parseHexString(item.body, encoding); + if (opts.binary) { + res = binStringToBluffer(data, type); + } else { + res = btoa$1(data); + } + callback(null, res); + }); + }; + + api._getRevisionTree = function (docId, callback) { + db.readTransaction(function (tx) { + var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?'; + tx.executeSql(sql, [docId], function (tx, result) { + if (!result.rows.length) { + callback(createError(MISSING_DOC)); + } else { + var data = safeJsonParse(result.rows.item(0).metadata); + callback(null, data.rev_tree); + } + }); + }); + }; + + api._doCompaction = function (docId, revs, callback) { + if (!revs.length) { + return callback(); + } + db.transaction(function (tx) { + + // update doc store + var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?'; + tx.executeSql(sql, [docId], function (tx, result) { + var metadata = safeJsonParse(result.rows.item(0).metadata); + traverseRevTree(metadata.rev_tree, function (isLeaf, pos, + revHash, ctx, opts) { + var rev = pos + '-' + revHash; + if (revs.indexOf(rev) !== -1) { + opts.status = 'missing'; + } + }); + + var sql = 'UPDATE ' + DOC_STORE$1 + ' SET json = ? WHERE id = ?'; + tx.executeSql(sql, [safeJsonStringify(metadata), docId]); + }); + + compactRevs$1(revs, docId, tx); + }, websqlError(callback), function () { + callback(); + }); + }; + + api._getLocal = function (id, callback) { + db.readTransaction(function (tx) { + var sql = 'SELECT json, rev FROM ' + LOCAL_STORE$1 + ' WHERE id=?'; + tx.executeSql(sql, [id], function (tx, res) { + if (res.rows.length) { + var item = res.rows.item(0); + var doc = unstringifyDoc(item.json, id, item.rev); + callback(null, doc); + } else { + callback(createError(MISSING_DOC)); + } + }); + }); + }; + + api._putLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + delete doc._revisions; // ignore this, trust the rev + var oldRev = doc._rev; + var id = doc._id; + var newRev; + if (!oldRev) { + newRev = doc._rev = '0-1'; + } else { + newRev = doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1); + } + var json = stringifyDoc(doc); + + var ret; + function putLocal(tx) { + var sql; + var values; + if (oldRev) { + sql = 'UPDATE ' + LOCAL_STORE$1 + ' SET rev=?, json=? ' + + 'WHERE id=? AND rev=?'; + values = [newRev, json, id, oldRev]; + } else { + sql = 'INSERT INTO ' + LOCAL_STORE$1 + ' (id, rev, json) VALUES (?,?,?)'; + values = [id, newRev, json]; + } + tx.executeSql(sql, values, function (tx, res) { + if (res.rowsAffected) { + ret = {ok: true, id: id, rev: newRev}; + if (opts.ctx) { // return immediately + callback(null, ret); + } + } else { + callback(createError(REV_CONFLICT)); + } + }, function () { + callback(createError(REV_CONFLICT)); + return false; // ack that we handled the error + }); + } + + if (opts.ctx) { + putLocal(opts.ctx); + } else { + db.transaction(putLocal, websqlError(callback), function () { + if (ret) { + callback(null, ret); + } + }); + } + }; + + api._removeLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var ret; + + function removeLocal(tx) { + var sql = 'DELETE FROM ' + LOCAL_STORE$1 + ' WHERE id=? AND rev=?'; + var params = [doc._id, doc._rev]; + tx.executeSql(sql, params, function (tx, res) { + if (!res.rowsAffected) { + return callback(createError(MISSING_DOC)); + } + ret = {ok: true, id: doc._id, rev: '0-0'}; + if (opts.ctx) { // return immediately + callback(null, ret); + } + }); + } + + if (opts.ctx) { + removeLocal(opts.ctx); + } else { + db.transaction(removeLocal, websqlError(callback), function () { + if (ret) { + callback(null, ret); + } + }); + } + }; + + api._destroy = function (opts, callback) { + websqlChanges.removeAllListeners(api._name); + db.transaction(function (tx) { + var stores = [DOC_STORE$1, BY_SEQ_STORE$1, ATTACH_STORE$1, META_STORE$1, + LOCAL_STORE$1, ATTACH_AND_SEQ_STORE$1]; + stores.forEach(function (store) { + tx.executeSql('DROP TABLE IF EXISTS ' + store, []); + }); + }, websqlError(callback), function () { + if (hasLocalStorage()) { + delete window.localStorage['_pouch__websqldb_' + api._name]; + delete window.localStorage[api._name]; + } + callback(null, {'ok': true}); + }); + }; +} + +function canOpenTestDB() { + try { + openDatabase('_pouch_validate_websql', 1, '', 1); + return true; + } catch (err) { + return false; + } +} + +// WKWebView had a bug where WebSQL would throw a DOM Exception 18 +// (see https://bugs.webkit.org/show_bug.cgi?id=137760 and +// https://github.com/pouchdb/pouchdb/issues/5079) +// This has been fixed in latest WebKit, so we try to detect it here. +function isValidWebSQL() { + // WKWebView UA: + // Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) + // AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 + // Chrome for iOS UA: + // Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; en) + // AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 + // Mobile/9B206 Safari/7534.48.3 + // Firefox for iOS UA: + // Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 + // (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4 + + // indexedDB is null on some UIWebViews and undefined in others + // see: https://bugs.webkit.org/show_bug.cgi?id=137034 + if (typeof indexedDB === 'undefined' || indexedDB === null || + !/iP(hone|od|ad)/.test(navigator.userAgent)) { + // definitely not WKWebView, avoid creating an unnecessary database + return true; + } + // Cache the result in LocalStorage. Reason we do this is because if we + // call openDatabase() too many times, Safari craps out in SauceLabs and + // starts throwing DOM Exception 14s. + var hasLS = hasLocalStorage(); + // Include user agent in the hash, so that if Safari is upgraded, we don't + // continually think it's broken. + var localStorageKey = '_pouch__websqldb_valid_' + navigator.userAgent; + if (hasLS && localStorage[localStorageKey]) { + return localStorage[localStorageKey] === '1'; + } + var openedTestDB = canOpenTestDB(); + if (hasLS) { + localStorage[localStorageKey] = openedTestDB ? '1' : '0'; + } + return openedTestDB; +} + +function valid() { + if (typeof openDatabase !== 'function') { + return false; + } + return isValidWebSQL(); +} + +function openDB(name, version, description, size) { + // Traditional WebSQL API + return openDatabase(name, version, description, size); +} + +function WebSQLPouch(opts, callback) { + var _opts = extend({ + websql: openDB + }, opts); + + WebSqlPouch$1.call(this, _opts, callback); +} + +WebSQLPouch.valid = valid; + +WebSQLPouch.use_prefix = true; + +function WebSqlPouch (PouchDB) { + PouchDB.adapter('websql', WebSQLPouch, true); +} + +/* global fetch */ +/* global Headers */ +function wrappedFetch() { + var wrappedPromise = {}; + + var promise = new PouchPromise(function (resolve, reject) { + wrappedPromise.resolve = resolve; + wrappedPromise.reject = reject; + }); + + var args = new Array(arguments.length); + + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + wrappedPromise.promise = promise; + + PouchPromise.resolve().then(function () { + return fetch.apply(null, args); + }).then(function (response) { + wrappedPromise.resolve(response); + }).catch(function (error) { + wrappedPromise.reject(error); + }); + + return wrappedPromise; +} + +function fetchRequest(options, callback) { + var wrappedPromise, timer, response; + + var headers = new Headers(); + + var fetchOptions = { + method: options.method, + credentials: 'include', + headers: headers + }; + + if (options.json) { + headers.set('Accept', 'application/json'); + headers.set('Content-Type', options.headers['Content-Type'] || + 'application/json'); + } + + if (options.body && (options.body instanceof Blob)) { + readAsArrayBuffer(options.body, function (arrayBuffer) { + fetchOptions.body = arrayBuffer; + }); + } else if (options.body && + options.processData && + typeof options.body !== 'string') { + fetchOptions.body = JSON.stringify(options.body); + } else if ('body' in options) { + fetchOptions.body = options.body; + } else { + fetchOptions.body = null; + } + + Object.keys(options.headers).forEach(function (key) { + if (options.headers.hasOwnProperty(key)) { + headers.set(key, options.headers[key]); + } + }); + + wrappedPromise = wrappedFetch(options.url, fetchOptions); + + if (options.timeout > 0) { + timer = setTimeout(function () { + wrappedPromise.reject(new Error('Load timeout for resource: ' + + options.url)); + }, options.timeout); + } + + wrappedPromise.promise.then(function (fetchResponse) { + response = { + statusCode: fetchResponse.status + }; + + if (options.timeout > 0) { + clearTimeout(timer); + } + + if (response.statusCode >= 200 && response.statusCode < 300) { + return options.binary ? fetchResponse.blob() : fetchResponse.text(); + } + + return fetchResponse.json(); + }).then(function (result) { + if (response.statusCode >= 200 && response.statusCode < 300) { + callback(null, response, result); + } else { + callback(result, response); + } + }).catch(function (error) { + callback(error, response); + }); + + return {abort: wrappedPromise.reject}; +} + +function xhRequest(options, callback) { + + var xhr, timer; + var timedout = false; + + var abortReq = function () { + xhr.abort(); + cleanUp(); + }; + + var timeoutReq = function () { + timedout = true; + xhr.abort(); + cleanUp(); + }; + + var ret = {abort: abortReq}; + + var cleanUp = function () { + clearTimeout(timer); + ret.abort = function () {}; + if (xhr) { + xhr.onprogress = undefined; + if (xhr.upload) { + xhr.upload.onprogress = undefined; + } + xhr.onreadystatechange = undefined; + xhr = undefined; + } + }; + + if (options.xhr) { + xhr = new options.xhr(); + } else { + xhr = new XMLHttpRequest(); + } + + try { + xhr.open(options.method, options.url); + } catch (exception) { + return callback(new Error(exception.name || 'Url is invalid')); + } + + xhr.withCredentials = ('withCredentials' in options) ? + options.withCredentials : true; + + if (options.method === 'GET') { + delete options.headers['Content-Type']; + } else if (options.json) { + options.headers.Accept = 'application/json'; + options.headers['Content-Type'] = options.headers['Content-Type'] || + 'application/json'; + if (options.body && + options.processData && + typeof options.body !== "string") { + options.body = JSON.stringify(options.body); + } + } + + if (options.binary) { + xhr.responseType = 'arraybuffer'; + } + + if (!('body' in options)) { + options.body = null; + } + + for (var key in options.headers) { + if (options.headers.hasOwnProperty(key)) { + xhr.setRequestHeader(key, options.headers[key]); + } + } + + if (options.timeout > 0) { + timer = setTimeout(timeoutReq, options.timeout); + xhr.onprogress = function () { + clearTimeout(timer); + if(xhr.readyState !== 4) { + timer = setTimeout(timeoutReq, options.timeout); + } + }; + if (typeof xhr.upload !== 'undefined') { // does not exist in ie9 + xhr.upload.onprogress = xhr.onprogress; + } + } + + xhr.onreadystatechange = function () { + if (xhr.readyState !== 4) { + return; + } + + var response = { + statusCode: xhr.status + }; + + if (xhr.status >= 200 && xhr.status < 300) { + var data; + if (options.binary) { + data = createBlob([xhr.response || ''], { + type: xhr.getResponseHeader('Content-Type') + }); + } else { + data = xhr.responseText; + } + callback(null, response, data); + } else { + var err = {}; + if (timedout) { + err = new Error('ETIMEDOUT'); + err.code = 'ETIMEDOUT'; + } else if (typeof xhr.response === 'string') { + try { + err = JSON.parse(xhr.response); + } catch(e) {} + } + err.status = xhr.status; + callback(err); + } + cleanUp(); + }; + + if (options.body && (options.body instanceof Blob)) { + readAsArrayBuffer(options.body, function (arrayBuffer) { + xhr.send(arrayBuffer); + }); + } else { + xhr.send(options.body); + } + + return ret; +} + +function testXhr() { + try { + new XMLHttpRequest(); + return true; + } catch (err) { + return false; + } +} + +var hasXhr = testXhr(); + +function ajax$1(options, callback) { + if (hasXhr || options.xhr) { + return xhRequest(options, callback); + } else { + return fetchRequest(options, callback); + } +} + +// the blob already has a type; do nothing +var res$2 = function () {}; + +function defaultBody() { + return ''; +} + +function ajaxCore(options, callback) { + + options = clone(options); + + var defaultOptions = { + method : "GET", + headers: {}, + json: true, + processData: true, + timeout: 10000, + cache: false + }; + + options = extend(defaultOptions, options); + + function onSuccess(obj, resp, cb) { + if (!options.binary && options.json && typeof obj === 'string') { + /* istanbul ignore next */ + try { + obj = JSON.parse(obj); + } catch (e) { + // Probably a malformed JSON from server + return cb(e); + } + } + if (Array.isArray(obj)) { + obj = obj.map(function (v) { + if (v.error || v.missing) { + return generateErrorFromResponse(v); + } else { + return v; + } + }); + } + if (options.binary) { + res$2(obj, resp); + } + cb(null, obj, resp); + } + + if (options.json) { + if (!options.binary) { + options.headers.Accept = 'application/json'; + } + options.headers['Content-Type'] = options.headers['Content-Type'] || + 'application/json'; + } + + if (options.binary) { + options.encoding = null; + options.json = false; + } + + if (!options.processData) { + options.json = false; + } + + return ajax$1(options, function (err, response, body) { + + if (err) { + return callback(generateErrorFromResponse(err)); + } + + var error; + var content_type = response.headers && response.headers['content-type']; + var data = body || defaultBody(); + + // CouchDB doesn't always return the right content-type for JSON data, so + // we check for ^{ and }$ (ignoring leading/trailing whitespace) + if (!options.binary && (options.json || !options.processData) && + typeof data !== 'object' && + (/json/.test(content_type) || + (/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) { + try { + data = JSON.parse(data.toString()); + } catch (e) {} + } + + if (response.statusCode >= 200 && response.statusCode < 300) { + onSuccess(data, response, callback); + } else { + error = generateErrorFromResponse(data); + error.status = response.statusCode; + callback(error); + } + }); +} + +function ajax(opts, callback) { + + // cache-buster, specifically designed to work around IE's aggressive caching + // see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/ + // Also Safari caches POSTs, so we need to cache-bust those too. + var ua = (navigator && navigator.userAgent) ? + navigator.userAgent.toLowerCase() : ''; + + var isSafari = ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1; + var isIE = ua.indexOf('msie') !== -1; + var isEdge = ua.indexOf('edge') !== -1; + + // it appears the new version of safari also caches GETs, + // see https://github.com/pouchdb/pouchdb/issues/5010 + var shouldCacheBust = (isSafari || + ((isIE || isEdge) && opts.method === 'GET')); + + var cache = 'cache' in opts ? opts.cache : true; + + var isBlobUrl = /^blob:/.test(opts.url); // don't append nonces for blob URLs + + if (!isBlobUrl && (shouldCacheBust || !cache)) { + var hasArgs = opts.url.indexOf('?') !== -1; + opts.url += (hasArgs ? '&' : '?') + '_nonce=' + Date.now(); + } + + return ajaxCore(opts, callback); +} + +var CHANGES_BATCH_SIZE = 25; +var MAX_SIMULTANEOUS_REVS = 50; + +var supportsBulkGetMap = {}; + +var log$1 = debug('pouchdb:http'); + +function readAttachmentsAsBlobOrBuffer(row) { + var atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function (filename) { + var att = atts[filename]; + att.data = b64ToBluffer(att.data, att.content_type); + }); +} + +function encodeDocId(id) { + if (/^_design/.test(id)) { + return '_design/' + encodeURIComponent(id.slice(8)); + } + if (/^_local/.test(id)) { + return '_local/' + encodeURIComponent(id.slice(7)); + } + return encodeURIComponent(id); +} + +function preprocessAttachments$1(doc) { + if (!doc._attachments || !Object.keys(doc._attachments)) { + return PouchPromise.resolve(); + } + + return PouchPromise.all(Object.keys(doc._attachments).map(function (key) { + var attachment = doc._attachments[key]; + if (attachment.data && typeof attachment.data !== 'string') { + return new PouchPromise(function (resolve) { + blobToBase64(attachment.data, resolve); + }).then(function (b64) { + attachment.data = b64; + }); + } + })); +} + +function hasUrlPrefix(opts) { + if (!opts.prefix) { + return false; + } + + var protocol = parseUri(opts.prefix).protocol; + + return protocol === 'http' || protocol === 'https'; +} + +// Get all the information you possibly can about the URI given by name and +// return it as a suitable object. +function getHost(name, opts) { + + // encode db name if opts.prefix is a url (#5574) + if (hasUrlPrefix(opts)) { + var dbName = opts.name.substr(opts.prefix.length); + name = opts.prefix + encodeURIComponent(dbName); + } + + // Prase the URI into all its little bits + var uri = parseUri(name); + + // Store the user and password as a separate auth object + if (uri.user || uri.password) { + uri.auth = {username: uri.user, password: uri.password}; + } + + // Split the path part of the URI into parts using '/' as the delimiter + // after removing any leading '/' and any trailing '/' + var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/'); + + // Store the first part as the database name and remove it from the parts + // array + uri.db = parts.pop(); + // Prevent double encoding of URI component + if (uri.db.indexOf('%') === -1) { + uri.db = encodeURIComponent(uri.db); + } + + // Restore the path by joining all the remaining parts (all the parts + // except for the database name) with '/'s + uri.path = parts.join('/'); + + return uri; +} + +// Generate a URL with the host data given by opts and the given path +function genDBUrl(opts, path) { + return genUrl(opts, opts.db + '/' + path); +} + +// Generate a URL with the host data given by opts and the given path +function genUrl(opts, path) { + // If the host already has a path, then we need to have a path delimiter + // Otherwise, the path delimiter is the empty string + var pathDel = !opts.path ? '' : '/'; + + // If the host already has a path, then we need to have a path delimiter + // Otherwise, the path delimiter is the empty string + return opts.protocol + '://' + opts.host + + (opts.port ? (':' + opts.port) : '') + + '/' + opts.path + pathDel + path; +} + +function paramsToStr(params) { + return '?' + Object.keys(params).map(function (k) { + return k + '=' + encodeURIComponent(params[k]); + }).join('&'); +} + +// Implements the PouchDB API for dealing with CouchDB instances over HTTP +function HttpPouch(opts, callback) { + + // The functions that will be publicly available for HttpPouch + var api = this; + + var host = getHost(opts.name, opts); + var dbUrl = genDBUrl(host, ''); + + opts = clone(opts); + var ajaxOpts = opts.ajax || {}; + + if (opts.auth || host.auth) { + var nAuth = opts.auth || host.auth; + var str = nAuth.username + ':' + nAuth.password; + var token = btoa$1(unescape(encodeURIComponent(str))); + ajaxOpts.headers = ajaxOpts.headers || {}; + ajaxOpts.headers.Authorization = 'Basic ' + token; + } + + // Not strictly necessary, but we do this because numerous tests + // rely on swapping ajax in and out. + api._ajax = ajax; + + function ajax$$(userOpts, options, callback) { + var reqAjax = userOpts.ajax || {}; + var reqOpts = extend(clone(ajaxOpts), reqAjax, options); + log$1(reqOpts.method + ' ' + reqOpts.url); + return api._ajax(reqOpts, callback); + } + + function ajaxPromise(userOpts, opts) { + return new PouchPromise(function (resolve, reject) { + ajax$$(userOpts, opts, function (err, res) { + /* istanbul ignore if */ + if (err) { + return reject(err); + } + resolve(res); + }); + }); + } + + function adapterFun$$(name, fun) { + return adapterFun(name, getArguments(function (args) { + setup().then(function () { + return fun.apply(this, args); + }).catch(function (e) { + var callback = args.pop(); + callback(e); + }); + })); + } + + var setupPromise; + + function setup() { + // TODO: Remove `skipSetup` in favor of `skip_setup` in a future release + if (opts.skipSetup || opts.skip_setup) { + return PouchPromise.resolve(); + } + + // If there is a setup in process or previous successful setup + // done then we will use that + // If previous setups have been rejected we will try again + if (setupPromise) { + return setupPromise; + } + + var checkExists = {method: 'GET', url: dbUrl}; + setupPromise = ajaxPromise({}, checkExists).catch(function (err) { + if (err && err.status && err.status === 404) { + // Doesnt exist, create it + explainError(404, 'PouchDB is just detecting if the remote exists.'); + return ajaxPromise({}, {method: 'PUT', url: dbUrl}); + } else { + return PouchPromise.reject(err); + } + }).catch(function (err) { + // If we try to create a database that already exists, skipped in + // istanbul since its catching a race condition. + /* istanbul ignore if */ + if (err && err.status && err.status === 412) { + return true; + } + return PouchPromise.reject(err); + }); + + setupPromise.catch(function () { + setupPromise = null; + }); + + return setupPromise; + } + + setTimeout(function () { + callback(null, api); + }); + + api.type = function () { + return 'http'; + }; + + api.id = adapterFun$$('id', function (callback) { + ajax$$({}, {method: 'GET', url: genUrl(host, '')}, function (err, result) { + var uuid = (result && result.uuid) ? + (result.uuid + host.db) : genDBUrl(host, ''); + callback(null, uuid); + }); + }); + + api.request = adapterFun$$('request', function (options, callback) { + options.url = genDBUrl(host, options.url); + ajax$$({}, options, callback); + }); + + // Sends a POST request to the host calling the couchdb _compact function + // version: The version of CouchDB it is running + api.compact = adapterFun$$('compact', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + ajax$$(opts, { + url: genDBUrl(host, '_compact'), + method: 'POST' + }, function () { + function ping() { + api.info(function (err, res) { + if (res && !res.compact_running) { + callback(null, {ok: true}); + } else { + setTimeout(ping, opts.interval || 200); + } + }); + } + // Ping the http if it's finished compaction + ping(); + }); + }); + + api.bulkGet = adapterFun('bulkGet', function (opts, callback) { + var self = this; + + function doBulkGet(cb) { + var params = {}; + if (opts.revs) { + params.revs = true; + } + if (opts.attachments) { + /* istanbul ignore next */ + params.attachments = true; + } + ajax$$({}, { + url: genDBUrl(host, '_bulk_get' + paramsToStr(params)), + method: 'POST', + body: { docs: opts.docs} + }, cb); + } + + function doBulkGetShim() { + // avoid "url too long error" by splitting up into multiple requests + var batchSize = MAX_SIMULTANEOUS_REVS; + var numBatches = Math.ceil(opts.docs.length / batchSize); + var numDone = 0; + var results = new Array(numBatches); + + function onResult(batchNum) { + return function (err, res) { + // err is impossible because shim returns a list of errs in that case + results[batchNum] = res.results; + if (++numDone === numBatches) { + callback(null, {results: flatten(results)}); + } + }; + } + + for (var i = 0; i < numBatches; i++) { + var subOpts = pick(opts, ['revs', 'attachments']); + subOpts.ajax = ajaxOpts; + subOpts.docs = opts.docs.slice(i * batchSize, + Math.min(opts.docs.length, (i + 1) * batchSize)); + bulkGet(self, subOpts, onResult(i)); + } + } + + // mark the whole database as either supporting or not supporting _bulk_get + var dbUrl = genUrl(host, ''); + var supportsBulkGet = supportsBulkGetMap[dbUrl]; + + if (typeof supportsBulkGet !== 'boolean') { + // check if this database supports _bulk_get + doBulkGet(function (err, res) { + /* istanbul ignore else */ + if (err) { + var status = Math.floor(err.status / 100); + /* istanbul ignore else */ + if (status === 4 || status === 5) { // 40x or 50x + supportsBulkGetMap[dbUrl] = false; + explainError( + err.status, + 'PouchDB is just detecting if the remote ' + + 'supports the _bulk_get API.' + ); + doBulkGetShim(); + } else { + callback(err); + } + } else { + supportsBulkGetMap[dbUrl] = true; + callback(null, res); + } + }); + } else if (supportsBulkGet) { + /* istanbul ignore next */ + doBulkGet(callback); + } else { + doBulkGetShim(); + } + }); + + // Calls GET on the host, which gets back a JSON string containing + // couchdb: A welcome string + // version: The version of CouchDB it is running + api._info = function (callback) { + setup().then(function () { + ajax$$({}, { + method: 'GET', + url: genDBUrl(host, '') + }, function (err, res) { + /* istanbul ignore next */ + if (err) { + return callback(err); + } + res.host = genDBUrl(host, ''); + callback(null, res); + }); + }).catch(callback); + }; + + // Get the document with the given id from the database given by host. + // The id could be solely the _id in the database, or it may be a + // _design/ID or _local/ID path + api.get = adapterFun$$('get', function (id, opts, callback) { + // If no options were given, set the callback to the second parameter + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + + // List of parameters to add to the GET request + var params = {}; + + if (opts.revs) { + params.revs = true; + } + + if (opts.revs_info) { + params.revs_info = true; + } + + if (opts.open_revs) { + if (opts.open_revs !== "all") { + opts.open_revs = JSON.stringify(opts.open_revs); + } + params.open_revs = opts.open_revs; + } + + if (opts.rev) { + params.rev = opts.rev; + } + + if (opts.conflicts) { + params.conflicts = opts.conflicts; + } + + id = encodeDocId(id); + + // Set the options for the ajax call + var options = { + method: 'GET', + url: genDBUrl(host, id + paramsToStr(params)) + }; + + function fetchAttachments(doc) { + var atts = doc._attachments; + var filenames = atts && Object.keys(atts); + if (!atts || !filenames.length) { + return; + } + // we fetch these manually in separate XHRs, because + // Sync Gateway would normally send it back as multipart/mixed, + // which we cannot parse. Also, this is more efficient than + // receiving attachments as base64-encoded strings. + function fetch() { + + if (!filenames.length) { + return null; + } + + var filename = filenames.pop(); + var att = atts[filename]; + var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) + + '?rev=' + doc._rev; + return ajaxPromise(opts, { + method: 'GET', + url: genDBUrl(host, path), + binary: true + }).then(function (blob) { + if (opts.binary) { + return blob; + } + return new PouchPromise(function (resolve) { + blobToBase64(blob, resolve); + }); + }).then(function (data) { + delete att.stub; + delete att.length; + att.data = data; + }); + } + + // This limits the number of parallel xhr requests to 5 any time + // to avoid issues with maximum browser request limits + return new PromisePool(fetch, 5, {promise: PouchPromise}).start(); + } + + function fetchAllAttachments(docOrDocs) { + if (Array.isArray(docOrDocs)) { + return PouchPromise.all(docOrDocs.map(function (doc) { + if (doc.ok) { + return fetchAttachments(doc.ok); + } + })); + } + return fetchAttachments(docOrDocs); + } + + ajaxPromise(opts, options).then(function (res) { + return PouchPromise.resolve().then(function () { + if (opts.attachments) { + return fetchAllAttachments(res); + } + }).then(function () { + callback(null, res); + }); + }).catch(callback); + }); + + // Delete the document given by doc from the database given by host. + api.remove = adapterFun$$('remove', + function (docOrId, optsOrRev, opts, callback) { + var doc; + if (typeof optsOrRev === 'string') { + // id, rev, opts, callback style + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + } else { + // doc, opts, callback style + doc = docOrId; + if (typeof optsOrRev === 'function') { + callback = optsOrRev; + opts = {}; + } else { + callback = opts; + opts = optsOrRev; + } + } + + var rev = (doc._rev || opts.rev); + + // Delete the document + ajax$$(opts, { + method: 'DELETE', + url: genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev + }, callback); + }); + + function encodeAttachmentId(attachmentId) { + return attachmentId.split("/").map(encodeURIComponent).join("/"); + } + + // Get the attachment + api.getAttachment = + adapterFun$$('getAttachment', function (docId, attachmentId, opts, + callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var params = opts.rev ? ('?rev=' + opts.rev) : ''; + var url = genDBUrl(host, encodeDocId(docId)) + '/' + + encodeAttachmentId(attachmentId) + params; + ajax$$(opts, { + method: 'GET', + url: url, + binary: true + }, callback); + }); + + // Remove the attachment given by the id and rev + api.removeAttachment = + adapterFun$$('removeAttachment', function (docId, attachmentId, rev, + callback) { + + var url = genDBUrl(host, encodeDocId(docId) + '/' + + encodeAttachmentId(attachmentId)) + '?rev=' + rev; + + ajax$$({}, { + method: 'DELETE', + url: url + }, callback); + }); + + // Add the attachment given by blob and its contentType property + // to the document with the given id, the revision given by rev, and + // add it to the database given by host. + api.putAttachment = + adapterFun$$('putAttachment', function (docId, attachmentId, rev, blob, + type, callback) { + if (typeof type === 'function') { + callback = type; + type = blob; + blob = rev; + rev = null; + } + var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId); + var url = genDBUrl(host, id); + if (rev) { + url += '?rev=' + rev; + } + + if (typeof blob === 'string') { + // input is assumed to be a base64 string + var binary; + try { + binary = atob$1(blob); + } catch (err) { + return callback(createError(BAD_ARG, + 'Attachment is not a valid base64 string')); + } + blob = binary ? binStringToBluffer(binary, type) : ''; + } + + var opts = { + headers: {'Content-Type': type}, + method: 'PUT', + url: url, + processData: false, + body: blob, + timeout: ajaxOpts.timeout || 60000 + }; + // Add the attachment + ajax$$({}, opts, callback); + }); + + // Update/create multiple documents given by req in the database + // given by host. + api._bulkDocs = function (req, opts, callback) { + // If new_edits=false then it prevents the database from creating + // new revision numbers for the documents. Instead it just uses + // the old ones. This is used in database replication. + req.new_edits = opts.new_edits; + + setup().then(function () { + return PouchPromise.all(req.docs.map(preprocessAttachments$1)); + }).then(function () { + // Update/create the documents + ajax$$(opts, { + method: 'POST', + url: genDBUrl(host, '_bulk_docs'), + timeout: opts.timeout, + body: req + }, function (err, results) { + if (err) { + return callback(err); + } + results.forEach(function (result) { + result.ok = true; // smooths out cloudant not adding this + }); + callback(null, results); + }); + }).catch(callback); + }; + + + // Update/create document + api._put = function (doc, opts, callback) { + setup().then(function () { + return preprocessAttachments$1(doc); + }).then(function () { + // Update/create the document + ajax$$(opts, { + method: 'PUT', + url: genDBUrl(host, encodeDocId(doc._id)), + body: doc + }, function (err, result) { + if (err) { + return callback(err); + } + callback(null, result); + }); + }).catch(callback); + }; + + + // Get a listing of the documents in the database given + // by host and ordered by increasing id. + api.allDocs = adapterFun$$('allDocs', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + + // List of parameters to add to the GET request + var params = {}; + var body; + var method = 'GET'; + + if (opts.conflicts) { + params.conflicts = true; + } + + if (opts.descending) { + params.descending = true; + } + + if (opts.include_docs) { + params.include_docs = true; + } + + // added in CouchDB 1.6.0 + if (opts.attachments) { + params.attachments = true; + } + + if (opts.key) { + params.key = JSON.stringify(opts.key); + } + + if (opts.start_key) { + opts.startkey = opts.start_key; + } + + if (opts.startkey) { + params.startkey = JSON.stringify(opts.startkey); + } + + if (opts.end_key) { + opts.endkey = opts.end_key; + } + + if (opts.endkey) { + params.endkey = JSON.stringify(opts.endkey); + } + + if (typeof opts.inclusive_end !== 'undefined') { + params.inclusive_end = !!opts.inclusive_end; + } + + if (typeof opts.limit !== 'undefined') { + params.limit = opts.limit; + } + + if (typeof opts.skip !== 'undefined') { + params.skip = opts.skip; + } + + var paramStr = paramsToStr(params); + + if (typeof opts.keys !== 'undefined') { + method = 'POST'; + body = {keys: opts.keys}; + } + + // Get the document listing + ajaxPromise(opts, { + method: method, + url: genDBUrl(host, '_all_docs' + paramStr), + body: body + }).then(function (res) { + if (opts.include_docs && opts.attachments && opts.binary) { + res.rows.forEach(readAttachmentsAsBlobOrBuffer); + } + callback(null, res); + }).catch(callback); + }); + + // Get a list of changes made to documents in the database given by host. + // TODO According to the README, there should be two other methods here, + // api.changes.addListener and api.changes.removeListener. + api._changes = function (opts) { + + // We internally page the results of a changes request, this means + // if there is a large set of changes to be returned we can start + // processing them quicker instead of waiting on the entire + // set of changes to return and attempting to process them at once + var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE; + + opts = clone(opts); + opts.timeout = ('timeout' in opts) ? opts.timeout : + ('timeout' in ajaxOpts) ? ajaxOpts.timeout : + 30 * 1000; + + // We give a 5 second buffer for CouchDB changes to respond with + // an ok timeout (if a timeout it set) + var params = opts.timeout ? {timeout: opts.timeout - (5 * 1000)} : {}; + var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false; + var returnDocs; + if ('return_docs' in opts) { + returnDocs = opts.return_docs; + } else if ('returnDocs' in opts) { + // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release + returnDocs = opts.returnDocs; + } else { + returnDocs = true; + } + // + var leftToFetch = limit; + + if (opts.style) { + params.style = opts.style; + } + + if (opts.include_docs || opts.filter && typeof opts.filter === 'function') { + params.include_docs = true; + } + + if (opts.attachments) { + params.attachments = true; + } + + if (opts.continuous) { + params.feed = 'longpoll'; + } + + if (opts.conflicts) { + params.conflicts = true; + } + + if (opts.descending) { + params.descending = true; + } + + if ('heartbeat' in opts) { + // If the heartbeat value is false, it disables the default heartbeat + if (opts.heartbeat) { + params.heartbeat = opts.heartbeat; + } + } else { + // Default heartbeat to 10 seconds + params.heartbeat = 10000; + } + + if (opts.filter && typeof opts.filter === 'string') { + params.filter = opts.filter; + } + + if (opts.view && typeof opts.view === 'string') { + params.filter = '_view'; + params.view = opts.view; + } + + // If opts.query_params exists, pass it through to the changes request. + // These parameters may be used by the filter on the source database. + if (opts.query_params && typeof opts.query_params === 'object') { + for (var param_name in opts.query_params) { + /* istanbul ignore else */ + if (opts.query_params.hasOwnProperty(param_name)) { + params[param_name] = opts.query_params[param_name]; + } + } + } + + var method = 'GET'; + var body; + + if (opts.doc_ids) { + // set this automagically for the user; it's annoying that couchdb + // requires both a "filter" and a "doc_ids" param. + params.filter = '_doc_ids'; + method = 'POST'; + body = {doc_ids: opts.doc_ids }; + } + + var xhr; + var lastFetchedSeq; + + // Get all the changes starting wtih the one immediately after the + // sequence number given by since. + var fetch = function (since, callback) { + if (opts.aborted) { + return; + } + params.since = since; + // "since" can be any kind of json object in Coudant/CouchDB 2.x + /* istanbul ignore next */ + if (typeof params.since === "object") { + params.since = JSON.stringify(params.since); + } + + if (opts.descending) { + if (limit) { + params.limit = leftToFetch; + } + } else { + params.limit = (!limit || leftToFetch > batchSize) ? + batchSize : leftToFetch; + } + + // Set the options for the ajax call + var xhrOpts = { + method: method, + url: genDBUrl(host, '_changes' + paramsToStr(params)), + timeout: opts.timeout, + body: body + }; + lastFetchedSeq = since; + + /* istanbul ignore if */ + if (opts.aborted) { + return; + } + + // Get the changes + setup().then(function () { + xhr = ajax$$(opts, xhrOpts, callback); + }).catch(callback); + }; + + // If opts.since exists, get all the changes from the sequence + // number given by opts.since. Otherwise, get all the changes + // from the sequence number 0. + var results = {results: []}; + + var fetched = function (err, res) { + if (opts.aborted) { + return; + } + var raw_results_length = 0; + // If the result of the ajax call (res) contains changes (res.results) + if (res && res.results) { + raw_results_length = res.results.length; + results.last_seq = res.last_seq; + // For each change + var req = {}; + req.query = opts.query_params; + res.results = res.results.filter(function (c) { + leftToFetch--; + var ret = filterChange(opts)(c); + if (ret) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer(c); + } + if (returnDocs) { + results.results.push(c); + } + opts.onChange(c); + } + return ret; + }); + } else if (err) { + // In case of an error, stop listening for changes and call + // opts.complete + opts.aborted = true; + opts.complete(err); + return; + } + + // The changes feed may have timed out with no results + // if so reuse last update sequence + if (res && res.last_seq) { + lastFetchedSeq = res.last_seq; + } + + var finished = (limit && leftToFetch <= 0) || + (res && raw_results_length < batchSize) || + (opts.descending); + + if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) { + // Queue a call to fetch again with the newest sequence number + setTimeout(function () { fetch(lastFetchedSeq, fetched); }, 0); + } else { + // We're done, call the callback + opts.complete(null, results); + } + }; + + fetch(opts.since || 0, fetched); + + // Return a method to cancel this method from processing any more + return { + cancel: function () { + opts.aborted = true; + if (xhr) { + xhr.abort(); + } + } + }; + }; + + // Given a set of document/revision IDs (given by req), tets the subset of + // those that do NOT correspond to revisions stored in the database. + // See http://wiki.apache.org/couchdb/HttpPostRevsDiff + api.revsDiff = adapterFun$$('revsDiff', function (req, opts, callback) { + // If no options were given, set the callback to be the second parameter + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + // Get the missing document/revision IDs + ajax$$(opts, { + method: 'POST', + url: genDBUrl(host, '_revs_diff'), + body: req + }, callback); + }); + + api._close = function (callback) { + callback(); + }; + + api._destroy = function (options, callback) { + ajax$$(options, { + url: genDBUrl(host, ''), + method: 'DELETE' + }, function (err, resp) { + if (err && err.status && err.status !== 404) { + return callback(err); + } + callback(null, resp); + }); + }; +} + +// HttpPouch is a valid adapter. +HttpPouch.valid = function () { + return true; +}; + +function HttpPouch$1 (PouchDB) { + PouchDB.adapter('http', HttpPouch, false); + PouchDB.adapter('https', HttpPouch, false); +} + +function pad(str, padWith, upToLength) { + var padding = ''; + var targetLength = upToLength - str.length; + /* istanbul ignore next */ + while (padding.length < targetLength) { + padding += padWith; + } + return padding; +} + +function padLeft(str, padWith, upToLength) { + var padding = pad(str, padWith, upToLength); + return padding + str; +} + +var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE +var MAGNITUDE_DIGITS = 3; // ditto +var SEP = ''; // set to '_' for easier debugging + +function collate(a, b) { + + if (a === b) { + return 0; + } + + a = normalizeKey(a); + b = normalizeKey(b); + + var ai = collationIndex(a); + var bi = collationIndex(b); + if ((ai - bi) !== 0) { + return ai - bi; + } + if (a === null) { + return 0; + } + switch (typeof a) { + case 'number': + return a - b; + case 'boolean': + return a === b ? 0 : (a < b ? -1 : 1); + case 'string': + return stringCollate(a, b); + } + return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b); +} + +// couch considers null/NaN/Infinity/-Infinity === undefined, +// for the purposes of mapreduce indexes. also, dates get stringified. +function normalizeKey(key) { + switch (typeof key) { + case 'undefined': + return null; + case 'number': + if (key === Infinity || key === -Infinity || isNaN(key)) { + return null; + } + return key; + case 'object': + var origKey = key; + if (Array.isArray(key)) { + var len = key.length; + key = new Array(len); + for (var i = 0; i < len; i++) { + key[i] = normalizeKey(origKey[i]); + } + /* istanbul ignore next */ + } else if (key instanceof Date) { + return key.toJSON(); + } else if (key !== null) { // generic object + key = {}; + for (var k in origKey) { + if (origKey.hasOwnProperty(k)) { + var val = origKey[k]; + if (typeof val !== 'undefined') { + key[k] = normalizeKey(val); + } + } + } + } + } + return key; +} + +function indexify(key) { + if (key !== null) { + switch (typeof key) { + case 'boolean': + return key ? 1 : 0; + case 'number': + return numToIndexableString(key); + case 'string': + // We've to be sure that key does not contain \u0000 + // Do order-preserving replacements: + // 0 -> 1, 1 + // 1 -> 1, 2 + // 2 -> 2, 2 + return key + .replace(/\u0002/g, '\u0002\u0002') + .replace(/\u0001/g, '\u0001\u0002') + .replace(/\u0000/g, '\u0001\u0001'); + case 'object': + var isArray = Array.isArray(key); + var arr = isArray ? key : Object.keys(key); + var i = -1; + var len = arr.length; + var result = ''; + if (isArray) { + while (++i < len) { + result += toIndexableString(arr[i]); + } + } else { + while (++i < len) { + var objKey = arr[i]; + result += toIndexableString(objKey) + + toIndexableString(key[objKey]); + } + } + return result; + } + } + return ''; +} + +// convert the given key to a string that would be appropriate +// for lexical sorting, e.g. within a database, where the +// sorting is the same given by the collate() function. +function toIndexableString(key) { + var zero = '\u0000'; + key = normalizeKey(key); + return collationIndex(key) + SEP + indexify(key) + zero; +} + +function parseNumber(str, i) { + var originalIdx = i; + var num; + var zero = str[i] === '1'; + if (zero) { + num = 0; + i++; + } else { + var neg = str[i] === '0'; + i++; + var numAsString = ''; + var magAsString = str.substring(i, i + MAGNITUDE_DIGITS); + var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE; + /* istanbul ignore next */ + if (neg) { + magnitude = -magnitude; + } + i += MAGNITUDE_DIGITS; + while (true) { + var ch = str[i]; + if (ch === '\u0000') { + break; + } else { + numAsString += ch; + } + i++; + } + numAsString = numAsString.split('.'); + if (numAsString.length === 1) { + num = parseInt(numAsString, 10); + } else { + /* istanbul ignore next */ + num = parseFloat(numAsString[0] + '.' + numAsString[1]); + } + /* istanbul ignore next */ + if (neg) { + num = num - 10; + } + /* istanbul ignore next */ + if (magnitude !== 0) { + // parseFloat is more reliable than pow due to rounding errors + // e.g. Number.MAX_VALUE would return Infinity if we did + // num * Math.pow(10, magnitude); + num = parseFloat(num + 'e' + magnitude); + } + } + return {num: num, length : i - originalIdx}; +} + +// move up the stack while parsing +// this function moved outside of parseIndexableString for performance +function pop(stack, metaStack) { + var obj = stack.pop(); + + if (metaStack.length) { + var lastMetaElement = metaStack[metaStack.length - 1]; + if (obj === lastMetaElement.element) { + // popping a meta-element, e.g. an object whose value is another object + metaStack.pop(); + lastMetaElement = metaStack[metaStack.length - 1]; + } + var element = lastMetaElement.element; + var lastElementIndex = lastMetaElement.index; + if (Array.isArray(element)) { + element.push(obj); + } else if (lastElementIndex === stack.length - 2) { // obj with key+value + var key = stack.pop(); + element[key] = obj; + } else { + stack.push(obj); // obj with key only + } + } +} + +function parseIndexableString(str) { + var stack = []; + var metaStack = []; // stack for arrays and objects + var i = 0; + + /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ + while (true) { + var collationIndex = str[i++]; + if (collationIndex === '\u0000') { + if (stack.length === 1) { + return stack.pop(); + } else { + pop(stack, metaStack); + continue; + } + } + switch (collationIndex) { + case '1': + stack.push(null); + break; + case '2': + stack.push(str[i] === '1'); + i++; + break; + case '3': + var parsedNum = parseNumber(str, i); + stack.push(parsedNum.num); + i += parsedNum.length; + break; + case '4': + var parsedStr = ''; + /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ + while (true) { + var ch = str[i]; + if (ch === '\u0000') { + break; + } + parsedStr += ch; + i++; + } + // perform the reverse of the order-preserving replacement + // algorithm (see above) + parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000') + .replace(/\u0001\u0002/g, '\u0001') + .replace(/\u0002\u0002/g, '\u0002'); + stack.push(parsedStr); + break; + case '5': + var arrayElement = { element: [], index: stack.length }; + stack.push(arrayElement.element); + metaStack.push(arrayElement); + break; + case '6': + var objElement = { element: {}, index: stack.length }; + stack.push(objElement.element); + metaStack.push(objElement); + break; + /* istanbul ignore next */ + default: + throw new Error( + 'bad collationIndex or unexpectedly reached end of input: ' + + collationIndex); + } + } +} + +function arrayCollate(a, b) { + var len = Math.min(a.length, b.length); + for (var i = 0; i < len; i++) { + var sort = collate(a[i], b[i]); + if (sort !== 0) { + return sort; + } + } + return (a.length === b.length) ? 0 : + (a.length > b.length) ? 1 : -1; +} +function stringCollate(a, b) { + // See: https://github.com/daleharvey/pouchdb/issues/40 + // This is incompatible with the CouchDB implementation, but its the + // best we can do for now + return (a === b) ? 0 : ((a > b) ? 1 : -1); +} +function objectCollate(a, b) { + var ak = Object.keys(a), bk = Object.keys(b); + var len = Math.min(ak.length, bk.length); + for (var i = 0; i < len; i++) { + // First sort the keys + var sort = collate(ak[i], bk[i]); + if (sort !== 0) { + return sort; + } + // if the keys are equal sort the values + sort = collate(a[ak[i]], b[bk[i]]); + if (sort !== 0) { + return sort; + } + + } + return (ak.length === bk.length) ? 0 : + (ak.length > bk.length) ? 1 : -1; +} +// The collation is defined by erlangs ordered terms +// the atoms null, true, false come first, then numbers, strings, +// arrays, then objects +// null/undefined/NaN/Infinity/-Infinity are all considered null +function collationIndex(x) { + var id = ['boolean', 'number', 'string', 'object']; + var idx = id.indexOf(typeof x); + //false if -1 otherwise true, but fast!!!!1 + if (~idx) { + if (x === null) { + return 1; + } + if (Array.isArray(x)) { + return 5; + } + return idx < 3 ? (idx + 2) : (idx + 3); + } + /* istanbul ignore next */ + if (Array.isArray(x)) { + return 5; + } +} + +// conversion: +// x yyy zz...zz +// x = 0 for negative, 1 for 0, 2 for positive +// y = exponent (for negative numbers negated) moved so that it's >= 0 +// z = mantisse +function numToIndexableString(num) { + + if (num === 0) { + return '1'; + } + + // convert number to exponential format for easier and + // more succinct string sorting + var expFormat = num.toExponential().split(/e\+?/); + var magnitude = parseInt(expFormat[1], 10); + + var neg = num < 0; + + var result = neg ? '0' : '2'; + + // first sort by magnitude + // it's easier if all magnitudes are positive + var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE); + var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS); + + result += SEP + magString; + + // then sort by the factor + var factor = Math.abs(parseFloat(expFormat[0])); // [1..10) + /* istanbul ignore next */ + if (neg) { // for negative reverse ordering + factor = 10 - factor; + } + + var factorStr = factor.toFixed(20); + + // strip zeros from the end + factorStr = factorStr.replace(/\.?0+$/, ''); + + result += SEP + factorStr; + + return result; +} + +/* + * Simple task queue to sequentialize actions. Assumes + * callbacks will eventually fire (once). + */ + +function TaskQueue$1() { + this.promise = new PouchPromise(function (fulfill) {fulfill(); }); +} +TaskQueue$1.prototype.add = function (promiseFactory) { + this.promise = this.promise.catch(function () { + // just recover + }).then(function () { + return promiseFactory(); + }); + return this.promise; +}; +TaskQueue$1.prototype.finish = function () { + return this.promise; +}; + +function createView(opts) { + var sourceDB = opts.db; + var viewName = opts.viewName; + var mapFun = opts.map; + var reduceFun = opts.reduce; + var temporary = opts.temporary; + + // the "undefined" part is for backwards compatibility + var viewSignature = mapFun.toString() + (reduceFun && reduceFun.toString()) + + 'undefined'; + + var cachedViews; + if (!temporary) { + // cache this to ensure we don't try to update the same view twice + cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {}; + if (cachedViews[viewSignature]) { + return cachedViews[viewSignature]; + } + } + + var promiseForView = sourceDB.info().then(function (info) { + + var depDbName = info.db_name + '-mrview-' + + (temporary ? 'temp' : stringMd5(viewSignature)); + + // save the view name in the source db so it can be cleaned up if necessary + // (e.g. when the _design doc is deleted, remove all associated view data) + function diffFunction(doc) { + doc.views = doc.views || {}; + var fullViewName = viewName; + if (fullViewName.indexOf('/') === -1) { + fullViewName = viewName + '/' + viewName; + } + var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {}; + /* istanbul ignore if */ + if (depDbs[depDbName]) { + return; // no update necessary + } + depDbs[depDbName] = true; + return doc; + } + return upsert(sourceDB, '_local/mrviews', diffFunction).then(function () { + return sourceDB.registerDependentDatabase(depDbName).then(function (res) { + var db = res.db; + db.auto_compaction = true; + var view = { + name: depDbName, + db: db, + sourceDB: sourceDB, + adapter: sourceDB.adapter, + mapFun: mapFun, + reduceFun: reduceFun + }; + return view.db.get('_local/lastSeq').catch(function (err) { + /* istanbul ignore if */ + if (err.status !== 404) { + throw err; + } + }).then(function (lastSeqDoc) { + view.seq = lastSeqDoc ? lastSeqDoc.seq : 0; + if (cachedViews) { + view.db.once('destroyed', function () { + delete cachedViews[viewSignature]; + }); + } + return view; + }); + }); + }); + }); + + if (cachedViews) { + cachedViews[viewSignature] = promiseForView; + } + return promiseForView; +} + +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} + +inherits(QueryParseError, Error); + +function NotFoundError(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError); + } catch (e) {} +} + +inherits(NotFoundError, Error); + +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} + +inherits(BuiltInError, Error); + +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} + +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} + +var log$2 = guardedConsole.bind(null, 'log'); +var isArray = Array.isArray; +var toJSON = JSON.parse; + +function evalFunctionWithEval(func, emit) { + return scopedEval( + "return (" + func.replace(/;\s*$/, "") + ");", + { + emit: emit, + sum: sum, + log: log$2, + isArray: isArray, + toJSON: toJSON + } + ); +} + +var promisedCallback = function (promise, callback) { + if (callback) { + promise.then(function (res) { + process.nextTick(function () { + callback(null, res); + }); + }, function (reason) { + process.nextTick(function () { + callback(reason); + }); + }); + } + return promise; +}; + +var callbackify = function (fun) { + return getArguments(function (args) { + var cb = args.pop(); + var promise = fun.apply(this, args); + if (typeof cb === 'function') { + promisedCallback(promise, cb); + } + return promise; + }); +}; + +// Promise finally util similar to Q.finally +var fin = function (promise, finalPromiseFactory) { + return promise.then(function (res) { + return finalPromiseFactory().then(function () { + return res; + }); + }, function (reason) { + return finalPromiseFactory().then(function () { + throw reason; + }); + }); +}; + +var sequentialize = function (queue, promiseFactory) { + return function () { + var args = arguments; + var that = this; + return queue.add(function () { + return promiseFactory.apply(that, args); + }); + }; +}; + +// uniq an array of strings, order not guaranteed +// similar to underscore/lodash _.uniq +var uniq = function (arr) { + var map = {}; + + for (var i = 0, len = arr.length; i < len; i++) { + map['$' + arr[i]] = true; + } + + var keys = Object.keys(map); + var output = new Array(keys.length); + + for (i = 0, len = keys.length; i < len; i++) { + output[i] = keys[i].substring(1); + } + return output; +}; + +var persistentQueues = {}; +var tempViewQueue = new TaskQueue$1(); +var CHANGES_BATCH_SIZE$1 = 50; + +function parseViewName(name) { + // can be either 'ddocname/viewname' or just 'viewname' + // (where the ddoc name is the same) + return name.indexOf('/') === -1 ? [name, name] : name.split('/'); +} + +function isGenOne(changes) { + // only return true if the current change is 1- + // and there are no other leafs + return changes.length === 1 && /^1-/.test(changes[0].rev); +} + +function emitError(db, e) { + try { + db.emit('error', e); + } catch (err) { + guardedConsole('error', + 'The user\'s map/reduce function threw an uncaught error.\n' + + 'You can debug this error by doing:\n' + + 'myDatabase.on(\'error\', function (err) { debugger; });\n' + + 'Please double-check your map/reduce function.'); + guardedConsole('error', e); + } +} + +function tryCode$1(db, fun, args) { + // emit an event if there was an error thrown by a map/reduce function. + // putting try/catches in a single function also avoids deoptimizations. + try { + return { + output : fun.apply(null, args) + }; + } catch (e) { + emitError(db, e); + return {error: e}; + } +} + +function sortByKeyThenValue(x, y) { + var keyCompare = collate(x.key, y.key); + return keyCompare !== 0 ? keyCompare : collate(x.value, y.value); +} + +function sliceResults(results, limit, skip) { + skip = skip || 0; + if (typeof limit === 'number') { + return results.slice(skip, limit + skip); + } else if (skip > 0) { + return results.slice(skip); + } + return results; +} + +function rowToDocId(row) { + var val = row.value; + // Users can explicitly specify a joined doc _id, or it + // defaults to the doc _id that emitted the key/value. + var docId = (val && typeof val === 'object' && val._id) || row.id; + return docId; +} + +function readAttachmentsAsBlobOrBuffer$1(res) { + res.rows.forEach(function (row) { + var atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function (filename) { + var att = atts[filename]; + atts[filename].data = b64ToBluffer(att.data, att.content_type); + }); + }); +} + +function postprocessAttachments(opts) { + return function (res) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer$1(res); + } + return res; + }; +} + +var builtInReduce = { + _sum: function (keys, values) { + return sum(values); + }, + + _count: function (keys, values) { + return values.length; + }, + + _stats: function (keys, values) { + // no need to implement rereduce=true, because Pouch + // will never call it + function sumsqr(values) { + var _sumsqr = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + _sumsqr += (num * num); + } + return _sumsqr; + } + return { + sum : sum(values), + min : Math.min.apply(null, values), + max : Math.max.apply(null, values), + count : values.length, + sumsqr : sumsqr(values) + }; + } +}; + +function addHttpParam(paramName, opts, params, asJson) { + // add an http param from opts to params, optionally json-encoded + var val = opts[paramName]; + if (typeof val !== 'undefined') { + if (asJson) { + val = encodeURIComponent(JSON.stringify(val)); + } + params.push(paramName + '=' + val); + } +} + +function coerceInteger(integerCandidate) { + if (typeof integerCandidate !== 'undefined') { + var asNumber = Number(integerCandidate); + // prevents e.g. '1foo' or '1.1' being coerced to 1 + if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) { + return asNumber; + } else { + return integerCandidate; + } + } +} + +function coerceOptions(opts) { + opts.group_level = coerceInteger(opts.group_level); + opts.limit = coerceInteger(opts.limit); + opts.skip = coerceInteger(opts.skip); + return opts; +} + +function checkPositiveInteger(number) { + if (number) { + if (typeof number !== 'number') { + return new QueryParseError('Invalid value for integer: "' + + number + '"'); + } + if (number < 0) { + return new QueryParseError('Invalid value for positive integer: ' + + '"' + number + '"'); + } + } +} + +function checkQueryParseError(options, fun) { + var startkeyName = options.descending ? 'endkey' : 'startkey'; + var endkeyName = options.descending ? 'startkey' : 'endkey'; + + if (typeof options[startkeyName] !== 'undefined' && + typeof options[endkeyName] !== 'undefined' && + collate(options[startkeyName], options[endkeyName]) > 0) { + throw new QueryParseError('No rows can match your key range, ' + + 'reverse your start_key and end_key or set {descending : true}'); + } else if (fun.reduce && options.reduce !== false) { + if (options.include_docs) { + throw new QueryParseError('{include_docs:true} is invalid for reduce'); + } else if (options.keys && options.keys.length > 1 && + !options.group && !options.group_level) { + throw new QueryParseError('Multi-key fetches for reduce views must use ' + + '{group: true}'); + } + } + ['group_level', 'limit', 'skip'].forEach(function (optionName) { + var error = checkPositiveInteger(options[optionName]); + if (error) { + throw error; + } + }); +} + +function httpQuery(db, fun, opts) { + // List of parameters to add to the PUT request + var params = []; + var body; + var method = 'GET'; + + // If opts.reduce exists and is defined, then add it to the list + // of parameters. + // If reduce=false then the results are that of only the map function + // not the final result of map and reduce. + addHttpParam('reduce', opts, params); + addHttpParam('include_docs', opts, params); + addHttpParam('attachments', opts, params); + addHttpParam('limit', opts, params); + addHttpParam('descending', opts, params); + addHttpParam('group', opts, params); + addHttpParam('group_level', opts, params); + addHttpParam('skip', opts, params); + addHttpParam('stale', opts, params); + addHttpParam('conflicts', opts, params); + addHttpParam('startkey', opts, params, true); + addHttpParam('start_key', opts, params, true); + addHttpParam('endkey', opts, params, true); + addHttpParam('end_key', opts, params, true); + addHttpParam('inclusive_end', opts, params); + addHttpParam('key', opts, params, true); + + // Format the list of parameters into a valid URI query string + params = params.join('&'); + params = params === '' ? '' : '?' + params; + + // If keys are supplied, issue a POST to circumvent GET query string limits + // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options + if (typeof opts.keys !== 'undefined') { + var MAX_URL_LENGTH = 2000; + // according to http://stackoverflow.com/a/417184/680742, + // the de facto URL length limit is 2000 characters + + var keysAsString = + 'keys=' + encodeURIComponent(JSON.stringify(opts.keys)); + if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) { + // If the keys are short enough, do a GET. we do this to work around + // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239) + params += (params[0] === '?' ? '&' : '?') + keysAsString; + } else { + method = 'POST'; + if (typeof fun === 'string') { + body = {keys: opts.keys}; + } else { // fun is {map : mapfun}, so append to this + fun.keys = opts.keys; + } + } + } + + // We are referencing a query defined in the design doc + if (typeof fun === 'string') { + var parts = parseViewName(fun); + return db.request({ + method: method, + url: '_design/' + parts[0] + '/_view/' + parts[1] + params, + body: body + }).then(postprocessAttachments(opts)); + } + + // We are using a temporary view, terrible for performance, good for testing + body = body || {}; + Object.keys(fun).forEach(function (key) { + if (Array.isArray(fun[key])) { + body[key] = fun[key]; + } else { + body[key] = fun[key].toString(); + } + }); + return db.request({ + method: 'POST', + url: '_temp_view' + params, + body: body + }).then(postprocessAttachments(opts)); +} + +// custom adapters can define their own api._query +// and override the default behavior +/* istanbul ignore next */ +function customQuery(db, fun, opts) { + return new PouchPromise(function (resolve, reject) { + db._query(fun, opts, function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} + +// custom adapters can define their own api._viewCleanup +// and override the default behavior +/* istanbul ignore next */ +function customViewCleanup(db) { + return new PouchPromise(function (resolve, reject) { + db._viewCleanup(function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} + +function defaultsTo(value) { + return function (reason) { + /* istanbul ignore else */ + if (reason.status === 404) { + return value; + } else { + throw reason; + } + }; +} + +// returns a promise for a list of docs to update, based on the input docId. +// the order doesn't matter, because post-3.2.0, bulkDocs +// is an atomic operation in all three adapters. +function getDocsToPersist(docId, view, docIdsToChangesAndEmits) { + var metaDocId = '_local/doc_' + docId; + var defaultMetaDoc = {_id: metaDocId, keys: []}; + var docData = docIdsToChangesAndEmits[docId]; + var indexableKeysToKeyValues = docData.indexableKeysToKeyValues; + var changes = docData.changes; + + function getMetaDoc() { + if (isGenOne(changes)) { + // generation 1, so we can safely assume initial state + // for performance reasons (avoids unnecessary GETs) + return PouchPromise.resolve(defaultMetaDoc); + } + return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc)); + } + + function getKeyValueDocs(metaDoc) { + if (!metaDoc.keys.length) { + // no keys, no need for a lookup + return PouchPromise.resolve({rows: []}); + } + return view.db.allDocs({ + keys: metaDoc.keys, + include_docs: true + }); + } + + function processKvDocs(metaDoc, kvDocsRes) { + var kvDocs = []; + var oldKeysMap = {}; + + for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) { + var row = kvDocsRes.rows[i]; + var doc = row.doc; + if (!doc) { // deleted + continue; + } + kvDocs.push(doc); + oldKeysMap[doc._id] = true; + doc._deleted = !indexableKeysToKeyValues[doc._id]; + if (!doc._deleted) { + var keyValue = indexableKeysToKeyValues[doc._id]; + if ('value' in keyValue) { + doc.value = keyValue.value; + } + } + } + + var newKeys = Object.keys(indexableKeysToKeyValues); + newKeys.forEach(function (key) { + if (!oldKeysMap[key]) { + // new doc + var kvDoc = { + _id: key + }; + var keyValue = indexableKeysToKeyValues[key]; + if ('value' in keyValue) { + kvDoc.value = keyValue.value; + } + kvDocs.push(kvDoc); + } + }); + metaDoc.keys = uniq(newKeys.concat(metaDoc.keys)); + kvDocs.push(metaDoc); + + return kvDocs; + } + + return getMetaDoc().then(function (metaDoc) { + return getKeyValueDocs(metaDoc).then(function (kvDocsRes) { + return processKvDocs(metaDoc, kvDocsRes); + }); + }); +} + +// updates all emitted key/value docs and metaDocs in the mrview database +// for the given batch of documents from the source database +function saveKeyValues(view, docIdsToChangesAndEmits, seq) { + var seqDocId = '_local/lastSeq'; + return view.db.get(seqDocId) + .catch(defaultsTo({_id: seqDocId, seq: 0})) + .then(function (lastSeqDoc) { + var docIds = Object.keys(docIdsToChangesAndEmits); + return PouchPromise.all(docIds.map(function (docId) { + return getDocsToPersist(docId, view, docIdsToChangesAndEmits); + })).then(function (listOfDocsToPersist) { + var docsToPersist = flatten(listOfDocsToPersist); + lastSeqDoc.seq = seq; + docsToPersist.push(lastSeqDoc); + // write all docs in a single operation, update the seq once + return view.db.bulkDocs({docs : docsToPersist}); + }); + }); +} + +function getQueue(view) { + var viewName = typeof view === 'string' ? view : view.name; + var queue = persistentQueues[viewName]; + if (!queue) { + queue = persistentQueues[viewName] = new TaskQueue$1(); + } + return queue; +} + +function updateView(view) { + return sequentialize(getQueue(view), function () { + return updateViewInQueue(view); + })(); +} + +function updateViewInQueue(view) { + // bind the emit function once + var mapResults; + var doc; + + function emit(key, value) { + var output = {id: doc._id, key: normalizeKey(key)}; + // Don't explicitly store the value unless it's defined and non-null. + // This saves on storage space, because often people don't use it. + if (typeof value !== 'undefined' && value !== null) { + output.value = normalizeKey(value); + } + mapResults.push(output); + } + + var mapFun; + // for temp_views one can use emit(doc, emit), see #38 + if (typeof view.mapFun === "function" && view.mapFun.length === 2) { + var origMap = view.mapFun; + mapFun = function (doc) { + return origMap(doc, emit); + }; + } else { + mapFun = evalFunctionWithEval(view.mapFun.toString(), emit); + } + + var currentSeq = view.seq || 0; + + function processChange(docIdsToChangesAndEmits, seq) { + return function () { + return saveKeyValues(view, docIdsToChangesAndEmits, seq); + }; + } + + var queue = new TaskQueue$1(); + // TODO(neojski): https://github.com/daleharvey/pouchdb/issues/1521 + + return new PouchPromise(function (resolve, reject) { + + function complete() { + queue.finish().then(function () { + view.seq = currentSeq; + resolve(); + }); + } + + function processNextBatch() { + view.sourceDB.changes({ + conflicts: true, + include_docs: true, + style: 'all_docs', + since: currentSeq, + limit: CHANGES_BATCH_SIZE$1 + }).on('complete', function (response) { + var results = response.results; + if (!results.length) { + return complete(); + } + var docIdsToChangesAndEmits = {}; + for (var i = 0, l = results.length; i < l; i++) { + var change = results[i]; + if (change.doc._id[0] !== '_') { + mapResults = []; + doc = change.doc; + + if (!doc._deleted) { + tryCode$1(view.sourceDB, mapFun, [doc]); + } + mapResults.sort(sortByKeyThenValue); + + var indexableKeysToKeyValues = {}; + var lastKey; + for (var j = 0, jl = mapResults.length; j < jl; j++) { + var obj = mapResults[j]; + var complexKey = [obj.key, obj.id]; + if (collate(obj.key, lastKey) === 0) { + complexKey.push(j); // dup key+id, so make it unique + } + var indexableKey = toIndexableString(complexKey); + indexableKeysToKeyValues[indexableKey] = obj; + lastKey = obj.key; + } + docIdsToChangesAndEmits[change.doc._id] = { + indexableKeysToKeyValues: indexableKeysToKeyValues, + changes: change.changes + }; + } + currentSeq = change.seq; + } + queue.add(processChange(docIdsToChangesAndEmits, currentSeq)); + if (results.length < CHANGES_BATCH_SIZE$1) { + return complete(); + } + return processNextBatch(); + }).on('error', onError); + /* istanbul ignore next */ + function onError(err) { + reject(err); + } + } + + processNextBatch(); + }); +} + +function reduceView(view, results, options) { + if (options.group_level === 0) { + delete options.group_level; + } + + var shouldGroup = options.group || options.group_level; + + var reduceFun; + if (builtInReduce[view.reduceFun]) { + reduceFun = builtInReduce[view.reduceFun]; + } else { + reduceFun = evalFunctionWithEval(view.reduceFun.toString()); + } + + var groups = []; + var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY : + options.group_level; + results.forEach(function (e) { + var last = groups[groups.length - 1]; + var groupKey = shouldGroup ? e.key : null; + + // only set group_level for array keys + if (shouldGroup && Array.isArray(groupKey)) { + groupKey = groupKey.slice(0, lvl); + } + + if (last && collate(last.groupKey, groupKey) === 0) { + last.keys.push([e.key, e.id]); + last.values.push(e.value); + return; + } + groups.push({ + keys: [[e.key, e.id]], + values: [e.value], + groupKey: groupKey + }); + }); + results = []; + for (var i = 0, len = groups.length; i < len; i++) { + var e = groups[i]; + var reduceTry = tryCode$1(view.sourceDB, reduceFun, + [e.keys, e.values, false]); + if (reduceTry.error && reduceTry.error instanceof BuiltInError) { + // CouchDB returns an error if a built-in errors out + throw reduceTry.error; + } + results.push({ + // CouchDB just sets the value to null if a non-built-in errors out + value: reduceTry.error ? null : reduceTry.output, + key: e.groupKey + }); + } + // no total_rows/offset when reducing + return {rows: sliceResults(results, options.limit, options.skip)}; +} + +function queryView(view, opts) { + return sequentialize(getQueue(view), function () { + return queryViewInQueue(view, opts); + })(); +} + +function queryViewInQueue(view, opts) { + var totalRows; + var shouldReduce = view.reduceFun && opts.reduce !== false; + var skip = opts.skip || 0; + if (typeof opts.keys !== 'undefined' && !opts.keys.length) { + // equivalent query + opts.limit = 0; + delete opts.keys; + } + + function fetchFromView(viewOpts) { + viewOpts.include_docs = true; + return view.db.allDocs(viewOpts).then(function (res) { + totalRows = res.total_rows; + return res.rows.map(function (result) { + + // implicit migration - in older versions of PouchDB, + // we explicitly stored the doc as {id: ..., key: ..., value: ...} + // this is tested in a migration test + /* istanbul ignore next */ + if ('value' in result.doc && typeof result.doc.value === 'object' && + result.doc.value !== null) { + var keys = Object.keys(result.doc.value).sort(); + // this detection method is not perfect, but it's unlikely the user + // emitted a value which was an object with these 3 exact keys + var expectedKeys = ['id', 'key', 'value']; + if (!(keys < expectedKeys || keys > expectedKeys)) { + return result.doc.value; + } + } + + var parsedKeyAndDocId = parseIndexableString(result.doc._id); + return { + key: parsedKeyAndDocId[0], + id: parsedKeyAndDocId[1], + value: ('value' in result.doc ? result.doc.value : null) + }; + }); + }); + } + + function onMapResultsReady(rows) { + var finalResults; + if (shouldReduce) { + finalResults = reduceView(view, rows, opts); + } else { + finalResults = { + total_rows: totalRows, + offset: skip, + rows: rows + }; + } + if (opts.include_docs) { + var docIds = uniq(rows.map(rowToDocId)); + + return view.sourceDB.allDocs({ + keys: docIds, + include_docs: true, + conflicts: opts.conflicts, + attachments: opts.attachments, + binary: opts.binary + }).then(function (allDocsRes) { + var docIdsToDocs = {}; + allDocsRes.rows.forEach(function (row) { + if (row.doc) { + docIdsToDocs['$' + row.id] = row.doc; + } + }); + rows.forEach(function (row) { + var docId = rowToDocId(row); + var doc = docIdsToDocs['$' + docId]; + if (doc) { + row.doc = doc; + } + }); + return finalResults; + }); + } else { + return finalResults; + } + } + + if (typeof opts.keys !== 'undefined') { + var keys = opts.keys; + var fetchPromises = keys.map(function (key) { + var viewOpts = { + startkey : toIndexableString([key]), + endkey : toIndexableString([key, {}]) + }; + return fetchFromView(viewOpts); + }); + return PouchPromise.all(fetchPromises).then(flatten).then(onMapResultsReady); + } else { // normal query, no 'keys' + var viewOpts = { + descending : opts.descending + }; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if (typeof opts.startkey !== 'undefined') { + viewOpts.startkey = opts.descending ? + toIndexableString([opts.startkey, {}]) : + toIndexableString([opts.startkey]); + } + if (typeof opts.endkey !== 'undefined') { + var inclusiveEnd = opts.inclusive_end !== false; + if (opts.descending) { + inclusiveEnd = !inclusiveEnd; + } + + viewOpts.endkey = toIndexableString( + inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]); + } + if (typeof opts.key !== 'undefined') { + var keyStart = toIndexableString([opts.key]); + var keyEnd = toIndexableString([opts.key, {}]); + if (viewOpts.descending) { + viewOpts.endkey = keyStart; + viewOpts.startkey = keyEnd; + } else { + viewOpts.startkey = keyStart; + viewOpts.endkey = keyEnd; + } + } + if (!shouldReduce) { + if (typeof opts.limit === 'number') { + viewOpts.limit = opts.limit; + } + viewOpts.skip = skip; + } + return fetchFromView(viewOpts).then(onMapResultsReady); + } +} + +function httpViewCleanup(db) { + return db.request({ + method: 'POST', + url: '_view_cleanup' + }); +} + +function localViewCleanup(db) { + return db.get('_local/mrviews').then(function (metaDoc) { + var docsToViews = {}; + Object.keys(metaDoc.views).forEach(function (fullViewName) { + var parts = parseViewName(fullViewName); + var designDocName = '_design/' + parts[0]; + var viewName = parts[1]; + docsToViews[designDocName] = docsToViews[designDocName] || {}; + docsToViews[designDocName][viewName] = true; + }); + var opts = { + keys : Object.keys(docsToViews), + include_docs : true + }; + return db.allDocs(opts).then(function (res) { + var viewsToStatus = {}; + res.rows.forEach(function (row) { + var ddocName = row.key.substring(8); + Object.keys(docsToViews[row.key]).forEach(function (viewName) { + var fullViewName = ddocName + '/' + viewName; + /* istanbul ignore if */ + if (!metaDoc.views[fullViewName]) { + // new format, without slashes, to support PouchDB 2.2.0 + // migration test in pouchdb's browser.migration.js verifies this + fullViewName = viewName; + } + var viewDBNames = Object.keys(metaDoc.views[fullViewName]); + // design doc deleted, or view function nonexistent + var statusIsGood = row.doc && row.doc.views && + row.doc.views[viewName]; + viewDBNames.forEach(function (viewDBName) { + viewsToStatus[viewDBName] = + viewsToStatus[viewDBName] || statusIsGood; + }); + }); + }); + var dbsToDelete = Object.keys(viewsToStatus).filter( + function (viewDBName) { return !viewsToStatus[viewDBName]; }); + var destroyPromises = dbsToDelete.map(function (viewDBName) { + return sequentialize(getQueue(viewDBName), function () { + return new db.constructor(viewDBName, db.__opts).destroy(); + })(); + }); + return PouchPromise.all(destroyPromises).then(function () { + return {ok: true}; + }); + }); + }, defaultsTo({ok: true})); +} + +var viewCleanup = callbackify(function () { + var db = this; + if (db.type() === 'http') { + return httpViewCleanup(db); + } + /* istanbul ignore next */ + if (typeof db._viewCleanup === 'function') { + return customViewCleanup(db); + } + return localViewCleanup(db); +}); + +function queryPromised(db, fun, opts) { + if (db.type() === 'http') { + return httpQuery(db, fun, opts); + } + + /* istanbul ignore next */ + if (typeof db._query === 'function') { + return customQuery(db, fun, opts); + } + + if (typeof fun !== 'string') { + // temp_view + checkQueryParseError(opts, fun); + + var createViewOpts = { + db : db, + viewName : 'temp_view/temp_view', + map : fun.map, + reduce : fun.reduce, + temporary : true + }; + tempViewQueue.add(function () { + return createView(createViewOpts).then(function (view) { + function cleanup() { + return view.db.destroy(); + } + return fin(updateView(view).then(function () { + return queryView(view, opts); + }), cleanup); + }); + }); + return tempViewQueue.finish(); + } else { + // persistent view + var fullViewName = fun; + var parts = parseViewName(fullViewName); + var designDocName = parts[0]; + var viewName = parts[1]; + return db.get('_design/' + designDocName).then(function (doc) { + var fun = doc.views && doc.views[viewName]; + + if (!fun || typeof fun.map !== 'string') { + throw new NotFoundError('ddoc ' + designDocName + + ' has no view named ' + viewName); + } + checkQueryParseError(opts, fun); + + var createViewOpts = { + db : db, + viewName : fullViewName, + map : fun.map, + reduce : fun.reduce + }; + return createView(createViewOpts).then(function (view) { + if (opts.stale === 'ok' || opts.stale === 'update_after') { + if (opts.stale === 'update_after') { + process.nextTick(function () { + updateView(view); + }); + } + return queryView(view, opts); + } else { // stale not ok + return updateView(view).then(function () { + return queryView(view, opts); + }); + } + }); + }); + } +} + +var query = function (fun, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts ? coerceOptions(opts) : {}; + + if (typeof fun === 'function') { + fun = {map : fun}; + } + + var db = this; + var promise = PouchPromise.resolve().then(function () { + return queryPromised(db, fun, opts); + }); + promisedCallback(promise, callback); + return promise; +}; + + +var mapreduce = { + query: query, + viewCleanup: viewCleanup +}; + +function isGenOne$1(rev) { + return /^1-/.test(rev); +} + +function fileHasChanged(localDoc, remoteDoc, filename) { + return !localDoc._attachments || + !localDoc._attachments[filename] || + localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest; +} + +function getDocAttachments(db, doc) { + var filenames = Object.keys(doc._attachments); + return PouchPromise.all(filenames.map(function (filename) { + return db.getAttachment(doc._id, filename, {rev: doc._rev}); + })); +} + +function getDocAttachmentsFromTargetOrSource(target, src, doc) { + var doCheckForLocalAttachments = src.type() === 'http' && target.type() !== 'http'; + var filenames = Object.keys(doc._attachments); + + if (!doCheckForLocalAttachments) { + return getDocAttachments(src, doc); + } + + return target.get(doc._id).then(function (localDoc) { + return PouchPromise.all(filenames.map(function (filename) { + if (fileHasChanged(localDoc, doc, filename)) { + return src.getAttachment(doc._id, filename); + } + + return target.getAttachment(localDoc._id, filename); + })); + }).catch(function (error) { + /* istanbul ignore if */ + if (error.status !== 404) { + throw error; + } + + return getDocAttachments(src, doc); + }); +} + +function createBulkGetOpts(diffs) { + var requests = []; + Object.keys(diffs).forEach(function (id) { + var missingRevs = diffs[id].missing; + missingRevs.forEach(function (missingRev) { + requests.push({ + id: id, + rev: missingRev + }); + }); + }); + + return { + docs: requests, + revs: true + }; +} + +// +// Fetch all the documents from the src as described in the "diffs", +// which is a mapping of docs IDs to revisions. If the state ever +// changes to "cancelled", then the returned promise will be rejected. +// Else it will be resolved with a list of fetched documents. +// +function getDocs(src, target, diffs, state) { + diffs = clone(diffs); // we do not need to modify this + + var resultDocs = [], + ok = true; + + function getAllDocs() { + + var bulkGetOpts = createBulkGetOpts(diffs); + + if (!bulkGetOpts.docs.length) { // optimization: skip empty requests + return; + } + + return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) { + /* istanbul ignore if */ + if (state.cancelled) { + throw new Error('cancelled'); + } + return PouchPromise.all(bulkGetResponse.results.map(function (bulkGetInfo) { + return PouchPromise.all(bulkGetInfo.docs.map(function (doc) { + var remoteDoc = doc.ok; + + if (doc.error) { + // when AUTO_COMPACTION is set, docs can be returned which look + // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"} + ok = false; + } + + if (!remoteDoc || !remoteDoc._attachments) { + return remoteDoc; + } + + return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc).then(function (attachments) { + var filenames = Object.keys(remoteDoc._attachments); + attachments.forEach(function (attachment, i) { + var att = remoteDoc._attachments[filenames[i]]; + delete att.stub; + delete att.length; + att.data = attachment; + }); + + return remoteDoc; + }); + })); + })) + + .then(function (results) { + resultDocs = resultDocs.concat(flatten(results).filter(Boolean)); + }); + }); + } + + function hasAttachments(doc) { + return doc._attachments && Object.keys(doc._attachments).length > 0; + } + + function fetchRevisionOneDocs(ids) { + // Optimization: fetch gen-1 docs and attachments in + // a single request using _all_docs + return src.allDocs({ + keys: ids, + include_docs: true + }).then(function (res) { + if (state.cancelled) { + throw new Error('cancelled'); + } + res.rows.forEach(function (row) { + if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) || + hasAttachments(row.doc)) { + // if any of these conditions apply, we need to fetch using get() + return; + } + + // the doc we got back from allDocs() is sufficient + resultDocs.push(row.doc); + delete diffs[row.id]; + }); + }); + } + + function getRevisionOneDocs() { + // filter out the generation 1 docs and get them + // leaving the non-generation one docs to be got otherwise + var ids = Object.keys(diffs).filter(function (id) { + var missing = diffs[id].missing; + return missing.length === 1 && isGenOne$1(missing[0]); + }); + if (ids.length > 0) { + return fetchRevisionOneDocs(ids); + } + } + + function returnResult() { + return { ok:ok, docs:resultDocs }; + } + + return PouchPromise.resolve() + .then(getRevisionOneDocs) + .then(getAllDocs) + .then(returnResult); +} + +var CHECKPOINT_VERSION = 1; +var REPLICATOR = "pouchdb"; +// This is an arbitrary number to limit the +// amount of replication history we save in the checkpoint. +// If we save too much, the checkpoing docs will become very big, +// if we save fewer, we'll run a greater risk of having to +// read all the changes from 0 when checkpoint PUTs fail +// CouchDB 2.0 has a more involved history pruning, +// but let's go for the simple version for now. +var CHECKPOINT_HISTORY_SIZE = 5; +var LOWEST_SEQ = 0; + +function updateCheckpoint(db, id, checkpoint, session, returnValue) { + return db.get(id).catch(function (err) { + if (err.status === 404) { + if (db.type() === 'http') { + explainError( + 404, 'PouchDB is just checking if a remote checkpoint exists.' + ); + } + return { + session_id: session, + _id: id, + history: [], + replicator: REPLICATOR, + version: CHECKPOINT_VERSION + }; + } + throw err; + }).then(function (doc) { + if (returnValue.cancelled) { + return; + } + + // if the checkpoint has not changed, do not update + if (doc.last_seq === checkpoint) { + return; + } + + // Filter out current entry for this replication + doc.history = (doc.history || []).filter(function (item) { + return item.session_id !== session; + }); + + // Add the latest checkpoint to history + doc.history.unshift({ + last_seq: checkpoint, + session_id: session + }); + + // Just take the last pieces in history, to + // avoid really big checkpoint docs. + // see comment on history size above + doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE); + + doc.version = CHECKPOINT_VERSION; + doc.replicator = REPLICATOR; + + doc.session_id = session; + doc.last_seq = checkpoint; + + return db.put(doc).catch(function (err) { + if (err.status === 409) { + // retry; someone is trying to write a checkpoint simultaneously + return updateCheckpoint(db, id, checkpoint, session, returnValue); + } + throw err; + }); + }); +} + +function Checkpointer(src, target, id, returnValue) { + this.src = src; + this.target = target; + this.id = id; + this.returnValue = returnValue; +} + +Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) { + var self = this; + return this.updateTarget(checkpoint, session).then(function () { + return self.updateSource(checkpoint, session); + }); +}; + +Checkpointer.prototype.updateTarget = function (checkpoint, session) { + return updateCheckpoint(this.target, this.id, checkpoint, + session, this.returnValue); +}; + +Checkpointer.prototype.updateSource = function (checkpoint, session) { + var self = this; + if (this.readOnlySource) { + return PouchPromise.resolve(true); + } + return updateCheckpoint(this.src, this.id, checkpoint, + session, this.returnValue) + .catch(function (err) { + if (isForbiddenError(err)) { + self.readOnlySource = true; + return true; + } + throw err; + }); +}; + +var comparisons = { + "undefined": function (targetDoc, sourceDoc) { + // This is the previous comparison function + if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) { + return sourceDoc.last_seq; + } + /* istanbul ignore next */ + return 0; + }, + "1": function (targetDoc, sourceDoc) { + // This is the comparison function ported from CouchDB + return compareReplicationLogs(sourceDoc, targetDoc).last_seq; + } +}; + +Checkpointer.prototype.getCheckpoint = function () { + var self = this; + return self.target.get(self.id).then(function (targetDoc) { + if (self.readOnlySource) { + return PouchPromise.resolve(targetDoc.last_seq); + } + + return self.src.get(self.id).then(function (sourceDoc) { + // Since we can't migrate an old version doc to a new one + // (no session id), we just go with the lowest seq in this case + /* istanbul ignore if */ + if (targetDoc.version !== sourceDoc.version) { + return LOWEST_SEQ; + } + + var version; + if (targetDoc.version) { + version = targetDoc.version.toString(); + } else { + version = "undefined"; + } + + if (version in comparisons) { + return comparisons[version](targetDoc, sourceDoc); + } + /* istanbul ignore next */ + return LOWEST_SEQ; + }, function (err) { + if (err.status === 404 && targetDoc.last_seq) { + return self.src.put({ + _id: self.id, + last_seq: LOWEST_SEQ + }).then(function () { + return LOWEST_SEQ; + }, function (err) { + if (isForbiddenError(err)) { + self.readOnlySource = true; + return targetDoc.last_seq; + } + /* istanbul ignore next */ + return LOWEST_SEQ; + }); + } + throw err; + }); + }).catch(function (err) { + if (err.status !== 404) { + throw err; + } + return LOWEST_SEQ; + }); +}; +// This checkpoint comparison is ported from CouchDBs source +// they come from here: +// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906 + +function compareReplicationLogs(srcDoc, tgtDoc) { + if (srcDoc.session_id === tgtDoc.session_id) { + return { + last_seq: srcDoc.last_seq, + history: srcDoc.history + }; + } + + return compareReplicationHistory(srcDoc.history, tgtDoc.history); +} + +function compareReplicationHistory(sourceHistory, targetHistory) { + // the erlang loop via function arguments is not so easy to repeat in JS + // therefore, doing this as recursion + var S = sourceHistory[0]; + var sourceRest = sourceHistory.slice(1); + var T = targetHistory[0]; + var targetRest = targetHistory.slice(1); + + if (!S || targetHistory.length === 0) { + return { + last_seq: LOWEST_SEQ, + history: [] + }; + } + + var sourceId = S.session_id; + /* istanbul ignore if */ + if (hasSessionId(sourceId, targetHistory)) { + return { + last_seq: S.last_seq, + history: sourceHistory + }; + } + + var targetId = T.session_id; + if (hasSessionId(targetId, sourceRest)) { + return { + last_seq: T.last_seq, + history: targetRest + }; + } + + return compareReplicationHistory(sourceRest, targetRest); +} + +function hasSessionId(sessionId, history) { + var props = history[0]; + var rest = history.slice(1); + + if (!sessionId || history.length === 0) { + return false; + } + + if (sessionId === props.session_id) { + return true; + } + + return hasSessionId(sessionId, rest); +} + +function isForbiddenError(err) { + return typeof err.status === 'number' && Math.floor(err.status / 100) === 4; +} + +var STARTING_BACK_OFF = 0; + +function backOff(opts, returnValue, error, callback) { + if (opts.retry === false) { + returnValue.emit('error', error); + returnValue.removeAllListeners(); + return; + } + if (typeof opts.back_off_function !== 'function') { + opts.back_off_function = defaultBackOff; + } + returnValue.emit('requestError', error); + if (returnValue.state === 'active' || returnValue.state === 'pending') { + returnValue.emit('paused', error); + returnValue.state = 'stopped'; + var backOffSet = function backoffTimeSet() { + opts.current_back_off = STARTING_BACK_OFF; + }; + var removeBackOffSetter = function removeBackOffTimeSet() { + returnValue.removeListener('active', backOffSet); + }; + returnValue.once('paused', removeBackOffSetter); + returnValue.once('active', backOffSet); + } + + opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF; + opts.current_back_off = opts.back_off_function(opts.current_back_off); + setTimeout(callback, opts.current_back_off); +} + +function sortObjectPropertiesByKey(queryParams) { + return Object.keys(queryParams).sort(collate).reduce(function (result, key) { + result[key] = queryParams[key]; + return result; + }, {}); +} + +// Generate a unique id particular to this replication. +// Not guaranteed to align perfectly with CouchDB's rep ids. +function generateReplicationId(src, target, opts) { + var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : ''; + var filterFun = opts.filter ? opts.filter.toString() : ''; + var queryParams = ''; + var filterViewName = ''; + + if (opts.filter && opts.query_params) { + queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params)); + } + + if (opts.filter && opts.filter === '_view') { + filterViewName = opts.view.toString(); + } + + return PouchPromise.all([src.id(), target.id()]).then(function (res) { + var queryData = res[0] + res[1] + filterFun + filterViewName + + queryParams + docIds; + return new PouchPromise(function (resolve) { + binaryMd5(queryData, resolve); + }); + }).then(function (md5sum) { + // can't use straight-up md5 alphabet, because + // the char '/' is interpreted as being for attachments, + // and + is also not url-safe + md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_'); + return '_local/' + md5sum; + }); +} + +function replicate$1(src, target, opts, returnValue, result) { + var batches = []; // list of batches to be processed + var currentBatch; // the batch currently being processed + var pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; // next batch, not yet ready to be processed + var writingCheckpoint = false; // true while checkpoint is being written + var changesCompleted = false; // true when all changes received + var replicationCompleted = false; // true when replication has completed + var last_seq = 0; + var continuous = opts.continuous || opts.live || false; + var batch_size = opts.batch_size || 100; + var batches_limit = opts.batches_limit || 10; + var changesPending = false; // true while src.changes is running + var doc_ids = opts.doc_ids; + var repId; + var checkpointer; + var changedDocs = []; + // Like couchdb, every replication gets a unique session id + var session = uuid(); + + result = result || { + ok: true, + start_time: new Date(), + docs_read: 0, + docs_written: 0, + doc_write_failures: 0, + errors: [] + }; + + var changesOpts = {}; + returnValue.ready(src, target); + + function initCheckpointer() { + if (checkpointer) { + return PouchPromise.resolve(); + } + return generateReplicationId(src, target, opts).then(function (res) { + repId = res; + checkpointer = new Checkpointer(src, target, repId, returnValue); + }); + } + + function writeDocs() { + changedDocs = []; + + if (currentBatch.docs.length === 0) { + return; + } + var docs = currentBatch.docs; + var bulkOpts = {timeout: opts.timeout}; + return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + + // `res` doesn't include full documents (which live in `docs`), so we create a map of + // (id -> error), and check for errors while iterating over `docs` + var errorsById = Object.create(null); + res.forEach(function (res) { + if (res.error) { + errorsById[res.id] = res; + } + }); + + var errorsNo = Object.keys(errorsById).length; + result.doc_write_failures += errorsNo; + result.docs_written += docs.length - errorsNo; + + docs.forEach(function (doc) { + var error = errorsById[doc._id]; + if (error) { + result.errors.push(error); + if (error.name === 'unauthorized' || error.name === 'forbidden') { + returnValue.emit('denied', clone(error)); + } else { + throw error; + } + } else { + changedDocs.push(doc); + } + }); + + }, function (err) { + result.doc_write_failures += docs.length; + throw err; + }); + } + + function finishBatch() { + if (currentBatch.error) { + throw new Error('There was a problem getting docs.'); + } + result.last_seq = last_seq = currentBatch.seq; + var outResult = clone(result); + if (changedDocs.length) { + outResult.docs = changedDocs; + returnValue.emit('change', outResult); + } + writingCheckpoint = true; + return checkpointer.writeCheckpoint(currentBatch.seq, + session).then(function () { + writingCheckpoint = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + currentBatch = undefined; + getChanges(); + }).catch(function (err) { + onCheckpointError(err); + throw err; + }); + } + + function getDiffs() { + var diff = {}; + currentBatch.changes.forEach(function (change) { + // Couchbase Sync Gateway emits these, but we can ignore them + /* istanbul ignore if */ + if (change.id === "_user/") { + return; + } + diff[change.id] = change.changes.map(function (x) { + return x.rev; + }); + }); + return target.revsDiff(diff).then(function (diffs) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + // currentBatch.diffs elements are deleted as the documents are written + currentBatch.diffs = diffs; + }); + } + + function getBatchDocs() { + return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) { + currentBatch.error = !got.ok; + got.docs.forEach(function (doc) { + delete currentBatch.diffs[doc._id]; + result.docs_read++; + currentBatch.docs.push(doc); + }); + }); + } + + function startNextBatch() { + if (returnValue.cancelled || currentBatch) { + return; + } + if (batches.length === 0) { + processPendingBatch(true); + return; + } + currentBatch = batches.shift(); + getDiffs() + .then(getBatchDocs) + .then(writeDocs) + .then(finishBatch) + .then(startNextBatch) + .catch(function (err) { + abortReplication('batch processing terminated with error', err); + }); + } + + + function processPendingBatch(immediate) { + if (pendingBatch.changes.length === 0) { + if (batches.length === 0 && !currentBatch) { + if ((continuous && changesOpts.live) || changesCompleted) { + returnValue.state = 'pending'; + returnValue.emit('paused'); + } + if (changesCompleted) { + completeReplication(); + } + } + return; + } + if ( + immediate || + changesCompleted || + pendingBatch.changes.length >= batch_size + ) { + batches.push(pendingBatch); + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + if (returnValue.state === 'pending' || returnValue.state === 'stopped') { + returnValue.state = 'active'; + returnValue.emit('active'); + } + startNextBatch(); + } + } + + + function abortReplication(reason, err) { + if (replicationCompleted) { + return; + } + if (!err.message) { + err.message = reason; + } + result.ok = false; + result.status = 'aborting'; + batches = []; + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + completeReplication(err); + } + + + function completeReplication(fatalError) { + if (replicationCompleted) { + return; + } + /* istanbul ignore if */ + if (returnValue.cancelled) { + result.status = 'cancelled'; + if (writingCheckpoint) { + return; + } + } + result.status = result.status || 'complete'; + result.end_time = new Date(); + result.last_seq = last_seq; + replicationCompleted = true; + + if (fatalError) { + fatalError.result = result; + + if (fatalError.name === 'unauthorized' || fatalError.name === 'forbidden') { + returnValue.emit('error', fatalError); + returnValue.removeAllListeners(); + } else { + backOff(opts, returnValue, fatalError, function () { + replicate$1(src, target, opts, returnValue); + }); + } + } else { + returnValue.emit('complete', result); + returnValue.removeAllListeners(); + } + } + + + function onChange(change) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + var filter = filterChange(opts)(change); + if (!filter) { + return; + } + pendingBatch.seq = change.seq; + pendingBatch.changes.push(change); + processPendingBatch(batches.length === 0 && changesOpts.live); + } + + + function onChangesComplete(changes) { + changesPending = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + + // if no results were returned then we're done, + // else fetch more + if (changes.results.length > 0) { + changesOpts.since = changes.last_seq; + getChanges(); + processPendingBatch(true); + } else { + + var complete = function () { + if (continuous) { + changesOpts.live = true; + getChanges(); + } else { + changesCompleted = true; + } + processPendingBatch(true); + }; + + // update the checkpoint so we start from the right seq next time + if (!currentBatch && changes.results.length === 0) { + writingCheckpoint = true; + checkpointer.writeCheckpoint(changes.last_seq, + session).then(function () { + writingCheckpoint = false; + result.last_seq = last_seq = changes.last_seq; + complete(); + }) + .catch(onCheckpointError); + } else { + complete(); + } + } + } + + + function onChangesError(err) { + changesPending = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + abortReplication('changes rejected', err); + } + + + function getChanges() { + if (!( + !changesPending && + !changesCompleted && + batches.length < batches_limit + )) { + return; + } + changesPending = true; + function abortChanges() { + changes.cancel(); + } + function removeListener() { + returnValue.removeListener('cancel', abortChanges); + } + + if (returnValue._changes) { // remove old changes() and listeners + returnValue.removeListener('cancel', returnValue._abortChanges); + returnValue._changes.cancel(); + } + returnValue.once('cancel', abortChanges); + + var changes = src.changes(changesOpts) + .on('change', onChange); + changes.then(removeListener, removeListener); + changes.then(onChangesComplete) + .catch(onChangesError); + + if (opts.retry) { + // save for later so we can cancel if necessary + returnValue._changes = changes; + returnValue._abortChanges = abortChanges; + } + } + + + function startChanges() { + initCheckpointer().then(function () { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + return; + } + return checkpointer.getCheckpoint().then(function (checkpoint) { + last_seq = checkpoint; + changesOpts = { + since: last_seq, + limit: batch_size, + batch_size: batch_size, + style: 'all_docs', + doc_ids: doc_ids, + return_docs: true // required so we know when we're done + }; + if (opts.filter) { + if (typeof opts.filter !== 'string') { + // required for the client-side filter in onChange + changesOpts.include_docs = true; + } else { // ddoc filter + changesOpts.filter = opts.filter; + } + } + if ('heartbeat' in opts) { + changesOpts.heartbeat = opts.heartbeat; + } + if ('timeout' in opts) { + changesOpts.timeout = opts.timeout; + } + if (opts.query_params) { + changesOpts.query_params = opts.query_params; + } + if (opts.view) { + changesOpts.view = opts.view; + } + getChanges(); + }); + }).catch(function (err) { + abortReplication('getCheckpoint rejected with ', err); + }); + } + + /* istanbul ignore next */ + function onCheckpointError(err) { + writingCheckpoint = false; + abortReplication('writeCheckpoint completed with error', err); + } + + /* istanbul ignore if */ + if (returnValue.cancelled) { // cancelled immediately + completeReplication(); + return; + } + + if (!returnValue._addedListeners) { + returnValue.once('cancel', completeReplication); + + if (typeof opts.complete === 'function') { + returnValue.once('error', opts.complete); + returnValue.once('complete', function (result) { + opts.complete(null, result); + }); + } + returnValue._addedListeners = true; + } + + if (typeof opts.since === 'undefined') { + startChanges(); + } else { + initCheckpointer().then(function () { + writingCheckpoint = true; + return checkpointer.writeCheckpoint(opts.since, session); + }).then(function () { + writingCheckpoint = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + return; + } + last_seq = opts.since; + startChanges(); + }).catch(onCheckpointError); + } +} + +// We create a basic promise so the caller can cancel the replication possibly +// before we have actually started listening to changes etc +inherits(Replication, EventEmitter); +function Replication() { + EventEmitter.call(this); + this.cancelled = false; + this.state = 'pending'; + var self = this; + var promise = new PouchPromise(function (fulfill, reject) { + self.once('complete', fulfill); + self.once('error', reject); + }); + self.then = function (resolve, reject) { + return promise.then(resolve, reject); + }; + self.catch = function (reject) { + return promise.catch(reject); + }; + // As we allow error handling via "error" event as well, + // put a stub in here so that rejecting never throws UnhandledError. + self.catch(function () {}); +} + +Replication.prototype.cancel = function () { + this.cancelled = true; + this.state = 'cancelled'; + this.emit('cancel'); +}; + +Replication.prototype.ready = function (src, target) { + var self = this; + if (self._readyCalled) { + return; + } + self._readyCalled = true; + + function onDestroy() { + self.cancel(); + } + src.once('destroyed', onDestroy); + target.once('destroyed', onDestroy); + function cleanup() { + src.removeListener('destroyed', onDestroy); + target.removeListener('destroyed', onDestroy); + } + self.once('complete', cleanup); +}; + +function toPouch(db, opts) { + var PouchConstructor = opts.PouchConstructor; + if (typeof db === 'string') { + return new PouchConstructor(db, opts); + } else { + return db; + } +} + +function replicate(src, target, opts, callback) { + + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof opts === 'undefined') { + opts = {}; + } + + if (opts.doc_ids && !Array.isArray(opts.doc_ids)) { + throw createError(BAD_REQUEST, + "`doc_ids` filter parameter is not a list."); + } + + opts.complete = callback; + opts = clone(opts); + opts.continuous = opts.continuous || opts.live; + opts.retry = ('retry' in opts) ? opts.retry : false; + /*jshint validthis:true */ + opts.PouchConstructor = opts.PouchConstructor || this; + var replicateRet = new Replication(opts); + var srcPouch = toPouch(src, opts); + var targetPouch = toPouch(target, opts); + replicate$1(srcPouch, targetPouch, opts, replicateRet); + return replicateRet; +} + +inherits(Sync, EventEmitter); +function sync(src, target, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof opts === 'undefined') { + opts = {}; + } + opts = clone(opts); + /*jshint validthis:true */ + opts.PouchConstructor = opts.PouchConstructor || this; + src = toPouch(src, opts); + target = toPouch(target, opts); + return new Sync(src, target, opts, callback); +} + +function Sync(src, target, opts, callback) { + var self = this; + this.canceled = false; + + var optsPush = opts.push ? extend({}, opts, opts.push) : opts; + var optsPull = opts.pull ? extend({}, opts, opts.pull) : opts; + + this.push = replicate(src, target, optsPush); + this.pull = replicate(target, src, optsPull); + + this.pushPaused = true; + this.pullPaused = true; + + function pullChange(change) { + self.emit('change', { + direction: 'pull', + change: change + }); + } + function pushChange(change) { + self.emit('change', { + direction: 'push', + change: change + }); + } + function pushDenied(doc) { + self.emit('denied', { + direction: 'push', + doc: doc + }); + } + function pullDenied(doc) { + self.emit('denied', { + direction: 'pull', + doc: doc + }); + } + function pushPaused() { + self.pushPaused = true; + /* istanbul ignore if */ + if (self.pullPaused) { + self.emit('paused'); + } + } + function pullPaused() { + self.pullPaused = true; + /* istanbul ignore if */ + if (self.pushPaused) { + self.emit('paused'); + } + } + function pushActive() { + self.pushPaused = false; + /* istanbul ignore if */ + if (self.pullPaused) { + self.emit('active', { + direction: 'push' + }); + } + } + function pullActive() { + self.pullPaused = false; + /* istanbul ignore if */ + if (self.pushPaused) { + self.emit('active', { + direction: 'pull' + }); + } + } + + var removed = {}; + + function removeAll(type) { // type is 'push' or 'pull' + return function (event, func) { + var isChange = event === 'change' && + (func === pullChange || func === pushChange); + var isDenied = event === 'denied' && + (func === pullDenied || func === pushDenied); + var isPaused = event === 'paused' && + (func === pullPaused || func === pushPaused); + var isActive = event === 'active' && + (func === pullActive || func === pushActive); + + if (isChange || isDenied || isPaused || isActive) { + if (!(event in removed)) { + removed[event] = {}; + } + removed[event][type] = true; + if (Object.keys(removed[event]).length === 2) { + // both push and pull have asked to be removed + self.removeAllListeners(event); + } + } + }; + } + + if (opts.live) { + this.push.on('complete', self.pull.cancel.bind(self.pull)); + this.pull.on('complete', self.push.cancel.bind(self.push)); + } + + this.on('newListener', function (event) { + if (event === 'change') { + self.pull.on('change', pullChange); + self.push.on('change', pushChange); + } else if (event === 'denied') { + self.pull.on('denied', pullDenied); + self.push.on('denied', pushDenied); + } else if (event === 'active') { + self.pull.on('active', pullActive); + self.push.on('active', pushActive); + } else if (event === 'paused') { + self.pull.on('paused', pullPaused); + self.push.on('paused', pushPaused); + } + }); + + this.on('removeListener', function (event) { + if (event === 'change') { + self.pull.removeListener('change', pullChange); + self.push.removeListener('change', pushChange); + } else if (event === 'denied') { + self.pull.removeListener('denied', pullDenied); + self.push.removeListener('denied', pushDenied); + } else if (event === 'active') { + self.pull.removeListener('active', pullActive); + self.push.removeListener('active', pushActive); + } else if (event === 'paused') { + self.pull.removeListener('paused', pullPaused); + self.push.removeListener('paused', pushPaused); + } + }); + + this.pull.on('removeListener', removeAll('pull')); + this.push.on('removeListener', removeAll('push')); + + var promise = PouchPromise.all([ + this.push, + this.pull + ]).then(function (resp) { + var out = { + push: resp[0], + pull: resp[1] + }; + self.emit('complete', out); + if (callback) { + callback(null, out); + } + self.removeAllListeners(); + return out; + }, function (err) { + self.cancel(); + if (callback) { + // if there's a callback, then the callback can receive + // the error event + callback(err); + } else { + // if there's no callback, then we're safe to emit an error + // event, which would otherwise throw an unhandled error + // due to 'error' being a special event in EventEmitters + self.emit('error', err); + } + self.removeAllListeners(); + if (callback) { + // no sense throwing if we're already emitting an 'error' event + throw err; + } + }); + + this.then = function (success, err) { + return promise.then(success, err); + }; + + this.catch = function (err) { + return promise.catch(err); + }; +} + +Sync.prototype.cancel = function () { + if (!this.canceled) { + this.canceled = true; + this.push.cancel(); + this.pull.cancel(); + } +}; + +function replication(PouchDB) { + PouchDB.replicate = replicate; + PouchDB.sync = sync; + + Object.defineProperty(PouchDB.prototype, 'replicate', { + get: function () { + var self = this; + return { + from: function (other, opts, callback) { + return self.constructor.replicate(other, self, opts, callback); + }, + to: function (other, opts, callback) { + return self.constructor.replicate(self, other, opts, callback); + } + }; + } + }); + + PouchDB.prototype.sync = function (dbName, opts, callback) { + return this.constructor.sync(this, dbName, opts, callback); + }; +} + +PouchDB.plugin(IDBPouch) + .plugin(WebSqlPouch) + .plugin(HttpPouch$1) + .plugin(mapreduce) + .plugin(replication); + +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. + +export default PouchDB; \ No newline at end of file diff --git a/lib/pouchdb/lib/index-browser.js b/lib/pouchdb/lib/index-browser.js index 30a08ea0..dda9cfad 100644 --- a/lib/pouchdb/lib/index-browser.js +++ b/lib/pouchdb/lib/index-browser.js @@ -2829,7 +2829,7 @@ PouchDB.defaults = function (defaultOpts) { }; // managed automatically by set-version.js -var version = "6.0.4"; +var version = "6.0.6"; PouchDB.version = version; @@ -7882,7 +7882,7 @@ function HttpPouch(opts, callback) { // Update/create the document ajax$$(opts, { method: 'PUT', - url: genDBUrl(host, encodeURIComponent(doc._id)), + url: genDBUrl(host, encodeDocId(doc._id)), body: doc }, function (err, result) { if (err) { @@ -8708,13 +8708,90 @@ function createView(opts) { return promiseForView; } -function evalfunc(func, emit, sum, log, isArray, toJSON) { +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} + +inherits(QueryParseError, Error); + +function NotFoundError(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError); + } catch (e) {} +} + +inherits(NotFoundError, Error); + +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} + +inherits(BuiltInError, Error); + +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} + +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} + +var log$2 = guardedConsole.bind(null, 'log'); +var isArray = Array.isArray; +var toJSON = JSON.parse; + +function evalFunctionWithEval(func, emit) { return scopedEval( "return (" + func.replace(/;\s*$/, "") + ");", { emit: emit, sum: sum, - log: log, + log: log$2, isArray: isArray, toJSON: toJSON } @@ -8792,8 +8869,6 @@ var persistentQueues = {}; var tempViewQueue = new TaskQueue$1(); var CHANGES_BATCH_SIZE$1 = 50; -var log$2 = guardedConsole.bind(null, 'log'); - function parseViewName(name) { // can be either 'ddocname/viewname' or just 'viewname' // (where the ddoc name is the same) @@ -8877,43 +8952,6 @@ function postprocessAttachments(opts) { }; } -function createBuiltInError(name) { - var message = 'builtin ' + name + - ' function requires map values to be numbers' + - ' or number arrays'; - return new BuiltInError(message); -} - -function sum(values) { - var result = 0; - for (var i = 0, len = values.length; i < len; i++) { - var num = values[i]; - if (typeof num !== 'number') { - if (Array.isArray(num)) { - // lists of numbers are also allowed, sum them separately - result = typeof result === 'number' ? [result] : result; - for (var j = 0, jLen = num.length; j < jLen; j++) { - var jNum = num[j]; - if (typeof jNum !== 'number') { - throw createBuiltInError('_sum'); - } else if (typeof result[j] === 'undefined') { - result.push(jNum); - } else { - result[j] += jNum; - } - } - } else { // not array/number - throw createBuiltInError('_sum'); - } - } else if (typeof result === 'number') { - result += num; - } else { // add number to array - result[0] += num; - } - } - return result; -} - var builtInReduce = { _sum: function (keys, values) { return sum(values); @@ -9268,8 +9306,7 @@ function updateViewInQueue(view) { return origMap(doc, emit); }; } else { - mapFun = evalfunc(view.mapFun.toString(), emit, sum, log$2, Array.isArray, - JSON.parse); + mapFun = evalFunctionWithEval(view.mapFun.toString(), emit); } var currentSeq = view.seq || 0; @@ -9362,8 +9399,7 @@ function reduceView(view, results, options) { if (builtInReduce[view.reduceFun]) { reduceFun = builtInReduce[view.reduceFun]; } else { - reduceFun = evalfunc( - view.reduceFun.toString(), null, sum, log$2, Array.isArray, JSON.parse); + reduceFun = evalFunctionWithEval(view.reduceFun.toString()); } var groups = []; @@ -9710,41 +9746,6 @@ var query = function (fun, opts, callback) { return promise; }; -function QueryParseError(message) { - this.status = 400; - this.name = 'query_parse_error'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, QueryParseError); - } catch (e) {} -} - -inherits(QueryParseError, Error); - -function NotFoundError(message) { - this.status = 404; - this.name = 'not_found'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, NotFoundError); - } catch (e) {} -} - -inherits(NotFoundError, Error); - -function BuiltInError(message) { - this.status = 500; - this.name = 'invalid_value'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, BuiltInError); - } catch (e) {} -} - -inherits(BuiltInError, Error); var mapreduce = { query: query, @@ -10998,4 +10999,8 @@ PouchDB.plugin(IDBPouch) .plugin(mapreduce) .plugin(replication); +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. + module.exports = PouchDB; \ No newline at end of file diff --git a/lib/pouchdb/lib/index.es.js b/lib/pouchdb/lib/index.es.js new file mode 100644 index 00000000..9875553c --- /dev/null +++ b/lib/pouchdb/lib/index.es.js @@ -0,0 +1,9254 @@ +import { extend } from 'js-extend'; +import debug from 'debug'; +import inherits from 'inherits'; +import lie from 'lie'; +import events, { EventEmitter } from 'events'; +import getArguments from 'argsarray'; +import vm from 'vm'; +import levelup from 'levelup'; +import ltgt from 'ltgt'; +import Codec from 'level-codec'; +import ReadableStreamCore from 'readable-stream'; +import { obj } from 'through2'; +import Deque from 'double-ended-queue'; +import crypto from 'crypto'; +import vuvuzela from 'vuvuzela'; +import fs from 'fs'; +import path from 'path'; +import LevelWriteStream from 'level-write-stream'; +import PromisePool from 'es6-promise-pool'; +import scopedEval from 'scope-eval'; + +/* istanbul ignore next */ +var PouchPromise = typeof Promise === 'function' ? Promise : lie; + +// based on https://github.com/montagejs/collections +function mangle(key) { + return '$' + key; +} +function unmangle(key) { + return key.substring(1); +} +function _Map() { + this.store = {}; +} +_Map.prototype.get = function (key) { + var mangled = mangle(key); + return this.store[mangled]; +}; +_Map.prototype.set = function (key, value) { + var mangled = mangle(key); + this.store[mangled] = value; + return true; +}; +_Map.prototype.has = function (key) { + var mangled = mangle(key); + return mangled in this.store; +}; +_Map.prototype.delete = function (key) { + var mangled = mangle(key); + var res = mangled in this.store; + delete this.store[mangled]; + return res; +}; +_Map.prototype.forEach = function (cb) { + var keys = Object.keys(this.store); + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + var value = this.store[key]; + key = unmangle(key); + cb(value, key); + } +}; + +function _Set(array) { + this.store = new _Map(); + + // init with an array + if (array && Array.isArray(array)) { + for (var i = 0, len = array.length; i < len; i++) { + this.add(array[i]); + } + } +} +_Set.prototype.add = function (key) { + return this.store.set(key, true); +}; +_Set.prototype.has = function (key) { + return this.store.has(key); +}; + +function isBinaryObject(object) { + return object instanceof Buffer; +} + +function cloneBinaryObject(object) { + var copy = new Buffer(object.length); + object.copy(copy); + return copy; +} + +// most of this is borrowed from lodash.isPlainObject: +// https://github.com/fis-components/lodash.isplainobject/ +// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js + +var funcToString = Function.prototype.toString; +var objectCtorString = funcToString.call(Object); + +function isPlainObject(value) { + var proto = Object.getPrototypeOf(value); + /* istanbul ignore if */ + if (proto === null) { // not sure when this happens, but I guess it can + return true; + } + var Ctor = proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} + +function clone(object) { + var newObject; + var i; + var len; + + if (!object || typeof object !== 'object') { + return object; + } + + if (Array.isArray(object)) { + newObject = []; + for (i = 0, len = object.length; i < len; i++) { + newObject[i] = clone(object[i]); + } + return newObject; + } + + // special case: to avoid inconsistencies between IndexedDB + // and other backends, we automatically stringify Dates + if (object instanceof Date) { + return object.toISOString(); + } + + if (isBinaryObject(object)) { + return cloneBinaryObject(object); + } + + if (!isPlainObject(object)) { + return object; // don't clone objects like Workers + } + + newObject = {}; + for (i in object) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(object, i)) { + var value = clone(object[i]); + if (typeof value !== 'undefined') { + newObject[i] = value; + } + } + } + return newObject; +} + +function once(fun) { + var called = false; + return getArguments(function (args) { + /* istanbul ignore if */ + if (called) { + // this is a smoke test and should never actually happen + throw new Error('once called more than once'); + } else { + called = true; + fun.apply(this, args); + } + }); +} + +function toPromise(func) { + //create the function we will be returning + return getArguments(function (args) { + // Clone arguments + args = clone(args); + var self = this; + var tempCB = + (typeof args[args.length - 1] === 'function') ? args.pop() : false; + // if the last argument is a function, assume its a callback + var usedCB; + if (tempCB) { + // if it was a callback, create a new callback which calls it, + // but do so async so we don't trap any errors + usedCB = function (err, resp) { + process.nextTick(function () { + tempCB(err, resp); + }); + }; + } + var promise = new PouchPromise(function (fulfill, reject) { + var resp; + try { + var callback = once(function (err, mesg) { + if (err) { + reject(err); + } else { + fulfill(mesg); + } + }); + // create a callback for this invocation + // apply the function in the orig context + args.push(callback); + resp = func.apply(self, args); + if (resp && typeof resp.then === 'function') { + fulfill(resp); + } + } catch (e) { + reject(e); + } + }); + // if there is a callback, call it back + if (usedCB) { + promise.then(function (result) { + usedCB(null, result); + }, usedCB); + } + return promise; + }); +} + +var log = debug('pouchdb:api'); + +function adapterFun(name, callback) { + function logApiCall(self, name, args) { + /* istanbul ignore if */ + if (log.enabled) { + var logArgs = [self.name, name]; + for (var i = 0; i < args.length - 1; i++) { + logArgs.push(args[i]); + } + log.apply(null, logArgs); + + // override the callback itself to log the response + var origCallback = args[args.length - 1]; + args[args.length - 1] = function (err, res) { + var responseArgs = [self.name, name]; + responseArgs = responseArgs.concat( + err ? ['error', err] : ['success', res] + ); + log.apply(null, responseArgs); + origCallback(err, res); + }; + } + } + + return toPromise(getArguments(function (args) { + if (this._closed) { + return PouchPromise.reject(new Error('database is closed')); + } + if (this._destroyed) { + return PouchPromise.reject(new Error('database is destroyed')); + } + var self = this; + logApiCall(self, name, args); + if (!this.taskqueue.isReady) { + return new PouchPromise(function (fulfill, reject) { + self.taskqueue.addTask(function (failed) { + if (failed) { + reject(failed); + } else { + fulfill(self[name].apply(self, args)); + } + }); + }); + } + return callback.apply(this, args); + })); +} + +// like underscore/lodash _.pick() +function pick(obj, arr) { + var res = {}; + for (var i = 0, len = arr.length; i < len; i++) { + var prop = arr[i]; + if (prop in obj) { + res[prop] = obj[prop]; + } + } + return res; +} + +// Most browsers throttle concurrent requests at 6, so it's silly +// to shim _bulk_get by trying to launch potentially hundreds of requests +// and then letting the majority time out. We can handle this ourselves. +var MAX_NUM_CONCURRENT_REQUESTS = 6; + +function identityFunction(x) { + return x; +} + +function formatResultForOpenRevsGet(result) { + return [{ + ok: result + }]; +} + +// shim for P/CouchDB adapters that don't directly implement _bulk_get +function bulkGet(db, opts, callback) { + var requests = opts.docs; + + // consolidate into one request per doc if possible + var requestsById = {}; + requests.forEach(function (request) { + if (request.id in requestsById) { + requestsById[request.id].push(request); + } else { + requestsById[request.id] = [request]; + } + }); + + var numDocs = Object.keys(requestsById).length; + var numDone = 0; + var perDocResults = new Array(numDocs); + + function collapseResultsAndFinish() { + var results = []; + perDocResults.forEach(function (res) { + res.docs.forEach(function (info) { + results.push({ + id: res.id, + docs: [info] + }); + }); + }); + callback(null, {results: results}); + } + + function checkDone() { + if (++numDone === numDocs) { + collapseResultsAndFinish(); + } + } + + function gotResult(docIndex, id, docs) { + perDocResults[docIndex] = {id: id, docs: docs}; + checkDone(); + } + + var allRequests = Object.keys(requestsById); + + var i = 0; + + function nextBatch() { + + if (i >= allRequests.length) { + return; + } + + var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length); + var batch = allRequests.slice(i, upTo); + processBatch(batch, i); + i += batch.length; + } + + function processBatch(batch, offset) { + batch.forEach(function (docId, j) { + var docIdx = offset + j; + var docRequests = requestsById[docId]; + + // just use the first request as the "template" + // TODO: The _bulk_get API allows for more subtle use cases than this, + // but for now it is unlikely that there will be a mix of different + // "atts_since" or "attachments" in the same request, since it's just + // replicate.js that is using this for the moment. + // Also, atts_since is aspirational, since we don't support it yet. + var docOpts = pick(docRequests[0], ['atts_since', 'attachments']); + docOpts.open_revs = docRequests.map(function (request) { + // rev is optional, open_revs disallowed + return request.rev; + }); + + // remove falsey / undefined revisions + docOpts.open_revs = docOpts.open_revs.filter(identityFunction); + + var formatResult = identityFunction; + + if (docOpts.open_revs.length === 0) { + delete docOpts.open_revs; + + // when fetching only the "winning" leaf, + // transform the result so it looks like an open_revs + // request + formatResult = formatResultForOpenRevsGet; + } + + // globally-supplied options + ['revs', 'attachments', 'binary', 'ajax'].forEach(function (param) { + if (param in opts) { + docOpts[param] = opts[param]; + } + }); + db.get(docId, docOpts, function (err, res) { + var result; + /* istanbul ignore if */ + if (err) { + result = [{error: err}]; + } else { + result = formatResult(res); + } + gotResult(docIdx, docId, result); + nextBatch(); + }); + }); + } + + nextBatch(); + +} + +// in Node of course this is false +function isChromeApp() { + return false; +} + +// in Node of course this is false +function hasLocalStorage() { + return false; +} + +inherits(Changes$1, EventEmitter); + +/* istanbul ignore next */ +function attachBrowserEvents(self) { + if (isChromeApp()) { + chrome.storage.onChanged.addListener(function (e) { + // make sure it's event addressed to us + if (e.db_name != null) { + //object only has oldValue, newValue members + self.emit(e.dbName.newValue); + } + }); + } else if (hasLocalStorage()) { + if (typeof addEventListener !== 'undefined') { + addEventListener("storage", function (e) { + self.emit(e.key); + }); + } else { // old IE + window.attachEvent("storage", function (e) { + self.emit(e.key); + }); + } + } +} + +function Changes$1() { + EventEmitter.call(this); + this._listeners = {}; + + attachBrowserEvents(this); +} +Changes$1.prototype.addListener = function (dbName, id, db, opts) { + /* istanbul ignore if */ + if (this._listeners[id]) { + return; + } + var self = this; + var inprogress = false; + function eventFunction() { + /* istanbul ignore if */ + if (!self._listeners[id]) { + return; + } + if (inprogress) { + inprogress = 'waiting'; + return; + } + inprogress = true; + var changesOpts = pick(opts, [ + 'style', 'include_docs', 'attachments', 'conflicts', 'filter', + 'doc_ids', 'view', 'since', 'query_params', 'binary' + ]); + + /* istanbul ignore next */ + function onError() { + inprogress = false; + } + + db.changes(changesOpts).on('change', function (c) { + if (c.seq > opts.since && !opts.cancelled) { + opts.since = c.seq; + opts.onChange(c); + } + }).on('complete', function () { + if (inprogress === 'waiting') { + setTimeout(function (){ + eventFunction(); + },0); + } + inprogress = false; + }).on('error', onError); + } + this._listeners[id] = eventFunction; + this.on(dbName, eventFunction); +}; + +Changes$1.prototype.removeListener = function (dbName, id) { + /* istanbul ignore if */ + if (!(id in this._listeners)) { + return; + } + EventEmitter.prototype.removeListener.call(this, dbName, + this._listeners[id]); + delete this._listeners[id]; +}; + + +/* istanbul ignore next */ +Changes$1.prototype.notifyLocalWindows = function (dbName) { + //do a useless change on a storage thing + //in order to get other windows's listeners to activate + if (isChromeApp()) { + chrome.storage.local.set({dbName: dbName}); + } else if (hasLocalStorage()) { + localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; + } +}; + +Changes$1.prototype.notify = function (dbName) { + this.emit(dbName); + this.notifyLocalWindows(dbName); +}; + +function guardedConsole(method) { + /* istanbul ignore else */ + if (console !== 'undefined' && method in console) { + var args = Array.prototype.slice.call(arguments, 1); + console[method].apply(console, args); + } +} + +function randomNumber(min, max) { + var maxTimeout = 600000; // Hard-coded default of 10 minutes + min = parseInt(min, 10) || 0; + max = parseInt(max, 10); + if (max !== max || max <= min) { + max = (min || 1) << 1; //doubling + } else { + max = max + 1; + } + // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout + if(max > maxTimeout) { + min = maxTimeout >> 1; // divide by two + max = maxTimeout; + } + var ratio = Math.random(); + var range = max - min; + + return ~~(range * ratio + min); // ~~ coerces to an int, but fast. +} + +function defaultBackOff(min) { + var max = 0; + if (!min) { + max = 2000; + } + return randomNumber(min, max); +} + +// We assume Node users don't need to see this warning +var res = function () {}; + +inherits(PouchError, Error); + +function PouchError(opts) { + Error.call(this, opts.reason); + this.status = opts.status; + this.name = opts.error; + this.message = opts.reason; + this.error = true; +} + +PouchError.prototype.toString = function () { + return JSON.stringify({ + status: this.status, + name: this.name, + message: this.message, + reason: this.reason + }); +}; + +var UNAUTHORIZED = new PouchError({ + status: 401, + error: 'unauthorized', + reason: "Name or password is incorrect." +}); + +var MISSING_BULK_DOCS = new PouchError({ + status: 400, + error: 'bad_request', + reason: "Missing JSON list of 'docs'" +}); + +var MISSING_DOC = new PouchError({ + status: 404, + error: 'not_found', + reason: 'missing' +}); + +var REV_CONFLICT = new PouchError({ + status: 409, + error: 'conflict', + reason: 'Document update conflict' +}); + +var INVALID_ID = new PouchError({ + status: 400, + error: 'bad_request', + reason: '_id field must contain a string' +}); + +var MISSING_ID = new PouchError({ + status: 412, + error: 'missing_id', + reason: '_id is required for puts' +}); + +var RESERVED_ID = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Only reserved document ids may start with underscore.' +}); + +var NOT_OPEN = new PouchError({ + status: 412, + error: 'precondition_failed', + reason: 'Database not open' +}); + +var UNKNOWN_ERROR = new PouchError({ + status: 500, + error: 'unknown_error', + reason: 'Database encountered an unknown error' +}); + +var BAD_ARG = new PouchError({ + status: 500, + error: 'badarg', + reason: 'Some query argument is invalid' +}); + +var INVALID_REQUEST = new PouchError({ + status: 400, + error: 'invalid_request', + reason: 'Request was invalid' +}); + +var QUERY_PARSE_ERROR = new PouchError({ + status: 400, + error: 'query_parse_error', + reason: 'Some query parameter is invalid' +}); + +var DOC_VALIDATION = new PouchError({ + status: 500, + error: 'doc_validation', + reason: 'Bad special document member' +}); + +var BAD_REQUEST = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Something wrong with the request' +}); + +var NOT_AN_OBJECT = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Document must be a JSON object' +}); + +var DB_MISSING = new PouchError({ + status: 404, + error: 'not_found', + reason: 'Database not found' +}); + +var IDB_ERROR = new PouchError({ + status: 500, + error: 'indexed_db_went_bad', + reason: 'unknown' +}); + +var WSQ_ERROR = new PouchError({ + status: 500, + error: 'web_sql_went_bad', + reason: 'unknown' +}); + +var LDB_ERROR = new PouchError({ + status: 500, + error: 'levelDB_went_went_bad', + reason: 'unknown' +}); + +var FORBIDDEN = new PouchError({ + status: 403, + error: 'forbidden', + reason: 'Forbidden by design doc validate_doc_update function' +}); + +var INVALID_REV = new PouchError({ + status: 400, + error: 'bad_request', + reason: 'Invalid rev format' +}); + +var FILE_EXISTS = new PouchError({ + status: 412, + error: 'file_exists', + reason: 'The database could not be created, the file already exists.' +}); + +var MISSING_STUB = new PouchError({ + status: 412, + error: 'missing_stub' +}); + +var INVALID_URL = new PouchError({ + status: 413, + error: 'invalid_url', + reason: 'Provided URL is invalid' +}); + +function createError(error, reason) { + function CustomPouchError(reason) { + // inherit error properties from our parent error manually + // so as to allow proper JSON parsing. + /* jshint ignore:start */ + for (var p in error) { + if (typeof error[p] !== 'function') { + this[p] = error[p]; + } + } + /* jshint ignore:end */ + if (reason !== undefined) { + this.reason = reason; + } + } + CustomPouchError.prototype = PouchError.prototype; + return new CustomPouchError(reason); +} + +function generateErrorFromResponse(err) { + + if (typeof err !== 'object') { + var data = err; + err = UNKNOWN_ERROR; + err.data = data; + } + + if ('error' in err && err.error === 'conflict') { + err.name = 'conflict'; + err.status = 409; + } + + if (!('name' in err)) { + err.name = err.error || 'unknown'; + } + + if (!('status' in err)) { + err.status = 500; + } + + if (!('message' in err)) { + err.message = err.message || err.reason; + } + + return err; +} + +function tryFilter(filter, doc, req) { + try { + return !filter(doc, req); + } catch (err) { + var msg = 'Filter function threw: ' + err.toString(); + return createError(BAD_REQUEST, msg); + } +} + +function filterChange(opts) { + var req = {}; + var hasFilter = opts.filter && typeof opts.filter === 'function'; + req.query = opts.query_params; + + return function filter(change) { + if (!change.doc) { + // CSG sends events on the changes feed that don't have documents, + // this hack makes a whole lot of existing code robust. + change.doc = {}; + } + + var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); + + if (typeof filterReturn === 'object') { + return filterReturn; + } + + if (filterReturn) { + return false; + } + + if (!opts.include_docs) { + delete change.doc; + } else if (!opts.attachments) { + for (var att in change.doc._attachments) { + /* istanbul ignore else */ + if (change.doc._attachments.hasOwnProperty(att)) { + change.doc._attachments[att].stub = true; + } + } + } + return true; + }; +} + +function flatten(arrs) { + var res = []; + for (var i = 0, len = arrs.length; i < len; i++) { + res = res.concat(arrs[i]); + } + return res; +} + +// shim for Function.prototype.name, +// for browsers that don't support it like IE + +/* istanbul ignore next */ +function f() {} + +var hasName = f.name; +var res$1; + +// We dont run coverage in IE +/* istanbul ignore else */ +if (hasName) { + res$1 = function (fun) { + return fun.name; + }; +} else { + res$1 = function (fun) { + return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; + }; +} + +var functionName = res$1; + +// Determine id an ID is valid +// - invalid IDs begin with an underescore that does not begin '_design' or +// '_local' +// - any other string value is a valid id +// Returns the specific error object for each case +function invalidIdError(id) { + var err; + if (!id) { + err = createError(MISSING_ID); + } else if (typeof id !== 'string') { + err = createError(INVALID_ID); + } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { + err = createError(RESERVED_ID); + } + if (err) { + throw err; + } +} + +function listenerCount(ee, type) { + return 'listenerCount' in ee ? ee.listenerCount(type) : + EventEmitter.listenerCount(ee, type); +} + +function parseDesignDocFunctionName(s) { + if (!s) { + return null; + } + var parts = s.split('/'); + if (parts.length === 2) { + return parts; + } + if (parts.length === 1) { + return [s, s]; + } + return null; +} + +function normalizeDesignDocFunctionName(s) { + var normalized = parseDesignDocFunctionName(s); + return normalized ? normalized.join('/') : null; +} + +// originally parseUri 1.2.2, now patched by us +// (c) Steven Levithan +// MIT License +var keys = ["source", "protocol", "authority", "userInfo", "user", "password", + "host", "port", "relative", "path", "directory", "file", "query", "anchor"]; +var qName ="queryKey"; +var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g; + +// use the "loose" parser +/* jshint maxlen: false */ +var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + +function parseUri(str) { + var m = parser.exec(str); + var uri = {}; + var i = 14; + + while (i--) { + var key = keys[i]; + var value = m[i] || ""; + var encoded = ['user', 'password'].indexOf(key) !== -1; + uri[key] = encoded ? decodeURIComponent(value) : value; + } + + uri[qName] = {}; + uri[keys[12]].replace(qParser, function ($0, $1, $2) { + if ($1) { + uri[qName][$1] = $2; + } + }); + + return uri; +} + +// this is essentially the "update sugar" function from daleharvey/pouchdb#1388 +// the diffFun tells us what delta to apply to the doc. it either returns +// the doc, or false if it doesn't need to do an update after all +function upsert(db, docId, diffFun) { + return new PouchPromise(function (fulfill, reject) { + db.get(docId, function (err, doc) { + if (err) { + /* istanbul ignore next */ + if (err.status !== 404) { + return reject(err); + } + doc = {}; + } + + // the user might change the _rev, so save it for posterity + var docRev = doc._rev; + var newDoc = diffFun(doc); + + if (!newDoc) { + // if the diffFun returns falsy, we short-circuit as + // an optimization + return fulfill({updated: false, rev: docRev}); + } + + // users aren't allowed to modify these values, + // so reset them here + newDoc._id = docId; + newDoc._rev = docRev; + fulfill(tryAndPut(db, newDoc, diffFun)); + }); + }); +} + +function tryAndPut(db, doc, diffFun) { + return db.put(doc).then(function (res) { + return { + updated: true, + rev: res.rev + }; + }, function (err) { + /* istanbul ignore next */ + if (err.status !== 409) { + throw err; + } + return upsert(db, doc._id, diffFun); + }); +} + +// BEGIN Math.uuid.js + +/*! +Math.uuid.js (v1.4) +http://www.broofa.com +mailto:robert@broofa.com + +Copyright (c) 2010 Robert Kieffer +Dual licensed under the MIT and GPL licenses. +*/ + +/* + * Generate a random uuid. + * + * USAGE: Math.uuid(length, radix) + * length - the desired number of characters + * radix - the number of allowable values for each character. + * + * EXAMPLES: + * // No arguments - returns RFC4122, version 4 ID + * >>> Math.uuid() + * "92329D39-6F5C-4520-ABFC-AAB64544E172" + * + * // One argument - returns ID of the specified length + * >>> Math.uuid(15) // 15 character ID (default base=62) + * "VcydxgltxrVZSTV" + * + * // Two arguments - returns ID of the specified length, and radix. + * // (Radix must be <= 62) + * >>> Math.uuid(8, 2) // 8 character ID (base=2) + * "01001010" + * >>> Math.uuid(8, 10) // 8 character ID (base=10) + * "47473046" + * >>> Math.uuid(8, 16) // 8 character ID (base=16) + * "098F4D35" + */ +var chars = ( + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + + 'abcdefghijklmnopqrstuvwxyz' +).split(''); +function getValue(radix) { + return 0 | Math.random() * radix; +} +function uuid(len, radix) { + radix = radix || chars.length; + var out = ''; + var i = -1; + + if (len) { + // Compact form + while (++i < len) { + out += chars[getValue(radix)]; + } + return out; + } + // rfc4122, version 4 form + // Fill in random data. At i==19 set the high bits of clock sequence as + // per rfc4122, sec. 4.1.5 + while (++i < 36) { + switch (i) { + case 8: + case 13: + case 18: + case 23: + out += '-'; + break; + case 19: + out += chars[(getValue(16) & 0x3) | 0x8]; + break; + default: + out += chars[getValue(16)]; + } + } + + return out; +} + +// We fetch all leafs of the revision tree, and sort them based on tree length +// and whether they were deleted, undeleted documents with the longest revision +// tree (most edits) win +// The final sort algorithm is slightly documented in a sidebar here: +// http://guide.couchdb.org/draft/conflicts.html +function winningRev(metadata) { + var winningId; + var winningPos; + var winningDeleted; + var toVisit = metadata.rev_tree.slice(); + var node; + while ((node = toVisit.pop())) { + var tree = node.ids; + var branches = tree[2]; + var pos = node.pos; + if (branches.length) { // non-leaf + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i]}); + } + continue; + } + var deleted = !!tree[1].deleted; + var id = tree[0]; + // sort by deleted, then pos, then id + if (!winningId || (winningDeleted !== deleted ? winningDeleted : + winningPos !== pos ? winningPos < pos : winningId < id)) { + winningId = id; + winningPos = pos; + winningDeleted = deleted; + } + } + + return winningPos + '-' + winningId; +} + +// Pretty much all below can be combined into a higher order function to +// traverse revisions +// The return value from the callback will be passed as context to all +// children of that node +function traverseRevTree(revs, callback) { + var toVisit = revs.slice(); + + var node; + while ((node = toVisit.pop())) { + var pos = node.pos; + var tree = node.ids; + var branches = tree[2]; + var newCtx = + callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx}); + } + } +} + +function sortByPos(a, b) { + return a.pos - b.pos; +} + +function collectLeaves(revs) { + var leaves = []; + traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) { + if (isLeaf) { + leaves.push({rev: pos + "-" + id, pos: pos, opts: opts}); + } + }); + leaves.sort(sortByPos).reverse(); + for (var i = 0, len = leaves.length; i < len; i++) { + delete leaves[i].pos; + } + return leaves; +} + +// returns revs of all conflicts that is leaves such that +// 1. are not deleted and +// 2. are different than winning revision +function collectConflicts(metadata) { + var win = winningRev(metadata); + var leaves = collectLeaves(metadata.rev_tree); + var conflicts = []; + for (var i = 0, len = leaves.length; i < len; i++) { + var leaf = leaves[i]; + if (leaf.rev !== win && !leaf.opts.deleted) { + conflicts.push(leaf.rev); + } + } + return conflicts; +} + +// compact a tree by marking its non-leafs as missing, +// and return a list of revs to delete +function compactTree(metadata) { + var revs = []; + traverseRevTree(metadata.rev_tree, function (isLeaf, pos, + revHash, ctx, opts) { + if (opts.status === 'available' && !isLeaf) { + revs.push(pos + '-' + revHash); + opts.status = 'missing'; + } + }); + return revs; +} + +// build up a list of all the paths to the leafs in this revision tree +function rootToLeaf(revs) { + var paths = []; + var toVisit = revs.slice(); + var node; + while ((node = toVisit.pop())) { + var pos = node.pos; + var tree = node.ids; + var id = tree[0]; + var opts = tree[1]; + var branches = tree[2]; + var isLeaf = branches.length === 0; + + var history = node.history ? node.history.slice() : []; + history.push({id: id, opts: opts}); + if (isLeaf) { + paths.push({pos: (pos + 1 - history.length), ids: history}); + } + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: pos + 1, ids: branches[i], history: history}); + } + } + return paths.reverse(); +} + +// for a better overview of what this is doing, read: +// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl +// +// But for a quick intro, CouchDB uses a revision tree to store a documents +// history, A -> B -> C, when a document has conflicts, that is a branch in the +// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format +// +// KeyTree = [Path ... ] +// Path = {pos: position_from_root, ids: Tree} +// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []] + +function sortByPos$1(a, b) { + return a.pos - b.pos; +} + +// classic binary search +function binarySearch(arr, item, comparator) { + var low = 0; + var high = arr.length; + var mid; + while (low < high) { + mid = (low + high) >>> 1; + if (comparator(arr[mid], item) < 0) { + low = mid + 1; + } else { + high = mid; + } + } + return low; +} + +// assuming the arr is sorted, insert the item in the proper place +function insertSorted(arr, item, comparator) { + var idx = binarySearch(arr, item, comparator); + arr.splice(idx, 0, item); +} + +// Turn a path as a flat array into a tree with a single branch. +// If any should be stemmed from the beginning of the array, that's passed +// in as the second argument +function pathToTree(path, numStemmed) { + var root; + var leaf; + for (var i = numStemmed, len = path.length; i < len; i++) { + var node = path[i]; + var currentLeaf = [node.id, node.opts, []]; + if (leaf) { + leaf[2].push(currentLeaf); + leaf = currentLeaf; + } else { + root = leaf = currentLeaf; + } + } + return root; +} + +// compare the IDs of two trees +function compareTree(a, b) { + return a[0] < b[0] ? -1 : 1; +} + +// Merge two trees together +// The roots of tree1 and tree2 must be the same revision +function mergeTree(in_tree1, in_tree2) { + var queue = [{tree1: in_tree1, tree2: in_tree2}]; + var conflicts = false; + while (queue.length > 0) { + var item = queue.pop(); + var tree1 = item.tree1; + var tree2 = item.tree2; + + if (tree1[1].status || tree2[1].status) { + tree1[1].status = + (tree1[1].status === 'available' || + tree2[1].status === 'available') ? 'available' : 'missing'; + } + + for (var i = 0; i < tree2[2].length; i++) { + if (!tree1[2][0]) { + conflicts = 'new_leaf'; + tree1[2][0] = tree2[2][i]; + continue; + } + + var merged = false; + for (var j = 0; j < tree1[2].length; j++) { + if (tree1[2][j][0] === tree2[2][i][0]) { + queue.push({tree1: tree1[2][j], tree2: tree2[2][i]}); + merged = true; + } + } + if (!merged) { + conflicts = 'new_branch'; + insertSorted(tree1[2], tree2[2][i], compareTree); + } + } + } + return {conflicts: conflicts, tree: in_tree1}; +} + +function doMerge(tree, path, dontExpand) { + var restree = []; + var conflicts = false; + var merged = false; + var res; + + if (!tree.length) { + return {tree: [path], conflicts: 'new_leaf'}; + } + + for (var i = 0, len = tree.length; i < len; i++) { + var branch = tree[i]; + if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { + // Paths start at the same position and have the same root, so they need + // merged + res = mergeTree(branch.ids, path.ids); + restree.push({pos: branch.pos, ids: res.tree}); + conflicts = conflicts || res.conflicts; + merged = true; + } else if (dontExpand !== true) { + // The paths start at a different position, take the earliest path and + // traverse up until it as at the same point from root as the path we + // want to merge. If the keys match we return the longer path with the + // other merged After stemming we dont want to expand the trees + + var t1 = branch.pos < path.pos ? branch : path; + var t2 = branch.pos < path.pos ? path : branch; + var diff = t2.pos - t1.pos; + + var candidateParents = []; + + var trees = []; + trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null}); + while (trees.length > 0) { + var item = trees.pop(); + if (item.diff === 0) { + if (item.ids[0] === t2.ids[0]) { + candidateParents.push(item); + } + continue; + } + var elements = item.ids[2]; + for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { + trees.push({ + ids: elements[j], + diff: item.diff - 1, + parent: item.ids, + parentIdx: j + }); + } + } + + var el = candidateParents[0]; + + if (!el) { + restree.push(branch); + } else { + res = mergeTree(el.ids, t2.ids); + el.parent[2][el.parentIdx] = res.tree; + restree.push({pos: t1.pos, ids: t1.ids}); + conflicts = conflicts || res.conflicts; + merged = true; + } + } else { + restree.push(branch); + } + } + + // We didnt find + if (!merged) { + restree.push(path); + } + + restree.sort(sortByPos$1); + + return { + tree: restree, + conflicts: conflicts || 'internal_node' + }; +} + +// To ensure we dont grow the revision tree infinitely, we stem old revisions +function stem(tree, depth) { + // First we break out the tree into a complete list of root to leaf paths + var paths = rootToLeaf(tree); + var maybeStem = {}; + + var result; + for (var i = 0, len = paths.length; i < len; i++) { + // Then for each path, we cut off the start of the path based on the + // `depth` to stem to, and generate a new set of flat trees + var path = paths[i]; + var stemmed = path.ids; + var numStemmed = Math.max(0, stemmed.length - depth); + var stemmedNode = { + pos: path.pos + numStemmed, + ids: pathToTree(stemmed, numStemmed) + }; + + for (var s = 0; s < numStemmed; s++) { + var rev = (path.pos + s) + '-' + stemmed[s].id; + maybeStem[rev] = true; + } + + // Then we remerge all those flat trees together, ensuring that we dont + // connect trees that would go beyond the depth limit + if (result) { + result = doMerge(result, stemmedNode, true).tree; + } else { + result = [stemmedNode]; + } + } + + traverseRevTree(result, function (isLeaf, pos, revHash) { + // some revisions may have been removed in a branch but not in another + delete maybeStem[pos + '-' + revHash]; + }); + + return { + tree: result, + revs: Object.keys(maybeStem) + }; +} + +function merge(tree, path, depth) { + var newTree = doMerge(tree, path); + var stemmed = stem(newTree.tree, depth); + return { + tree: stemmed.tree, + stemmedRevs: stemmed.revs, + conflicts: newTree.conflicts + }; +} + +// return true if a rev exists in the rev tree, false otherwise +function revExists(revs, rev) { + var toVisit = revs.slice(); + var splitRev = rev.split('-'); + var targetPos = parseInt(splitRev[0], 10); + var targetId = splitRev[1]; + + var node; + while ((node = toVisit.pop())) { + if (node.pos === targetPos && node.ids[0] === targetId) { + return true; + } + var branches = node.ids[2]; + for (var i = 0, len = branches.length; i < len; i++) { + toVisit.push({pos: node.pos + 1, ids: branches[i]}); + } + } + return false; +} + +function getTrees(node) { + return node.ids; +} + +// check if a specific revision of a doc has been deleted +// - metadata: the metadata object from the doc store +// - rev: (optional) the revision to check. defaults to winning revision +function isDeleted(metadata, rev) { + if (!rev) { + rev = winningRev(metadata); + } + var id = rev.substring(rev.indexOf('-') + 1); + var toVisit = metadata.rev_tree.map(getTrees); + + var tree; + while ((tree = toVisit.pop())) { + if (tree[0] === id) { + return !!tree[1].deleted; + } + toVisit = toVisit.concat(tree[2]); + } +} + +function isLocalId(id) { + return (/^_local/).test(id); +} + +function evalFilter(input) { + var code = '(function() {\n"use strict";\nreturn ' + input + '\n})()'; + + return vm.runInNewContext(code); +} + +function evalView(input) { + var code = [ + '"use strict";', + 'var emitted = false;', + 'var emit = function (a, b) {', + ' emitted = true;', + '};', + 'var view = ' + input + ';', + 'view(doc);', + 'if (emitted) {', + ' return true;', + '}' + ].join('\n'); + + return vm.runInNewContext('(function(doc) {\n' + code + '\n})'); +} + +inherits(Changes, EventEmitter); + +function tryCatchInChangeListener(self, change) { + // isolate try/catches to avoid V8 deoptimizations + try { + self.emit('change', change); + } catch (e) { + guardedConsole('error', 'Error in .on("change", function):', e); + } +} + +function Changes(db, opts, callback) { + EventEmitter.call(this); + var self = this; + this.db = db; + opts = opts ? clone(opts) : {}; + var complete = opts.complete = once(function (err, resp) { + if (err) { + if (listenerCount(self, 'error') > 0) { + self.emit('error', err); + } + } else { + self.emit('complete', resp); + } + self.removeAllListeners(); + db.removeListener('destroyed', onDestroy); + }); + if (callback) { + self.on('complete', function (resp) { + callback(null, resp); + }); + self.on('error', callback); + } + function onDestroy() { + self.cancel(); + } + db.once('destroyed', onDestroy); + + opts.onChange = function (change) { + /* istanbul ignore if */ + if (opts.isCancelled) { + return; + } + tryCatchInChangeListener(self, change); + }; + + var promise = new PouchPromise(function (fulfill, reject) { + opts.complete = function (err, res) { + if (err) { + reject(err); + } else { + fulfill(res); + } + }; + }); + self.once('cancel', function () { + db.removeListener('destroyed', onDestroy); + opts.complete(null, {status: 'cancelled'}); + }); + this.then = promise.then.bind(promise); + this['catch'] = promise['catch'].bind(promise); + this.then(function (result) { + complete(null, result); + }, complete); + + + + if (!db.taskqueue.isReady) { + db.taskqueue.addTask(function (failed) { + if (failed) { + opts.complete(failed); + } else if (self.isCancelled) { + self.emit('cancel'); + } else { + self.doChanges(opts); + } + }); + } else { + self.doChanges(opts); + } +} +Changes.prototype.cancel = function () { + this.isCancelled = true; + if (this.db.taskqueue.isReady) { + this.emit('cancel'); + } +}; +function processChange(doc, metadata, opts) { + var changeList = [{rev: doc._rev}]; + if (opts.style === 'all_docs') { + changeList = collectLeaves(metadata.rev_tree) + .map(function (x) { return {rev: x.rev}; }); + } + var change = { + id: metadata.id, + changes: changeList, + doc: doc + }; + + if (isDeleted(metadata, doc._rev)) { + change.deleted = true; + } + if (opts.conflicts) { + change.doc._conflicts = collectConflicts(metadata); + if (!change.doc._conflicts.length) { + delete change.doc._conflicts; + } + } + return change; +} + +Changes.prototype.doChanges = function (opts) { + var self = this; + var callback = opts.complete; + + opts = clone(opts); + if ('live' in opts && !('continuous' in opts)) { + opts.continuous = opts.live; + } + opts.processChange = processChange; + + if (opts.since === 'latest') { + opts.since = 'now'; + } + if (!opts.since) { + opts.since = 0; + } + if (opts.since === 'now') { + this.db.info().then(function (info) { + /* istanbul ignore if */ + if (self.isCancelled) { + callback(null, {status: 'cancelled'}); + return; + } + opts.since = info.update_seq; + self.doChanges(opts); + }, callback); + return; + } + + + if (opts.view && !opts.filter) { + opts.filter = '_view'; + } + + if (opts.filter && typeof opts.filter === 'string') { + if (opts.filter === '_view') { + opts.view = normalizeDesignDocFunctionName(opts.view); + } else { + opts.filter = normalizeDesignDocFunctionName(opts.filter); + } + + if (this.db.type() !== 'http' && !opts.doc_ids) { + return this.filterChanges(opts); + } + } + + if (!('descending' in opts)) { + opts.descending = false; + } + + // 0 and 1 should return 1 document + opts.limit = opts.limit === 0 ? 1 : opts.limit; + opts.complete = callback; + var newPromise = this.db._changes(opts); + /* istanbul ignore else */ + if (newPromise && typeof newPromise.cancel === 'function') { + var cancel = self.cancel; + self.cancel = getArguments(function (args) { + newPromise.cancel(); + cancel.apply(this, args); + }); + } +}; + +Changes.prototype.filterChanges = function (opts) { + var self = this; + var callback = opts.complete; + if (opts.filter === '_view') { + if (!opts.view || typeof opts.view !== 'string') { + var err = createError(BAD_REQUEST, + '`view` filter parameter not found or invalid.'); + return callback(err); + } + // fetch a view from a design doc, make it behave like a filter + var viewName = parseDesignDocFunctionName(opts.view); + this.db.get('_design/' + viewName[0], function (err, ddoc) { + /* istanbul ignore if */ + if (self.isCancelled) { + return callback(null, {status: 'cancelled'}); + } + /* istanbul ignore next */ + if (err) { + return callback(generateErrorFromResponse(err)); + } + var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] && + ddoc.views[viewName[1]].map; + if (!mapFun) { + return callback(createError(MISSING_DOC, + (ddoc.views ? 'missing json key: ' + viewName[1] : + 'missing json key: views'))); + } + opts.filter = evalView(mapFun); + self.doChanges(opts); + }); + } else { + // fetch a filter from a design doc + var filterName = parseDesignDocFunctionName(opts.filter); + if (!filterName) { + return self.doChanges(opts); + } + this.db.get('_design/' + filterName[0], function (err, ddoc) { + /* istanbul ignore if */ + if (self.isCancelled) { + return callback(null, {status: 'cancelled'}); + } + /* istanbul ignore next */ + if (err) { + return callback(generateErrorFromResponse(err)); + } + var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]]; + if (!filterFun) { + return callback(createError(MISSING_DOC, + ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1] + : 'missing json key: filters'))); + } + opts.filter = evalFilter(filterFun); + self.doChanges(opts); + }); + } +}; + +/* + * A generic pouch adapter + */ + +function compare(left, right) { + return left < right ? -1 : left > right ? 1 : 0; +} + +// returns first element of arr satisfying callback predicate +function arrayFirst(arr, callback) { + for (var i = 0; i < arr.length; i++) { + if (callback(arr[i], i) === true) { + return arr[i]; + } + } +} + +// Wrapper for functions that call the bulkdocs api with a single doc, +// if the first result is an error, return an error +function yankError(callback) { + return function (err, results) { + if (err || (results[0] && results[0].error)) { + callback(err || results[0]); + } else { + callback(null, results.length ? results[0] : results); + } + }; +} + +// clean docs given to us by the user +function cleanDocs(docs) { + for (var i = 0; i < docs.length; i++) { + var doc = docs[i]; + if (doc._deleted) { + delete doc._attachments; // ignore atts for deleted docs + } else if (doc._attachments) { + // filter out extraneous keys from _attachments + var atts = Object.keys(doc._attachments); + for (var j = 0; j < atts.length; j++) { + var att = atts[j]; + doc._attachments[att] = pick(doc._attachments[att], + ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']); + } + } + } +} + +// compare two docs, first by _id then by _rev +function compareByIdThenRev(a, b) { + var idCompare = compare(a._id, b._id); + if (idCompare !== 0) { + return idCompare; + } + var aStart = a._revisions ? a._revisions.start : 0; + var bStart = b._revisions ? b._revisions.start : 0; + return compare(aStart, bStart); +} + +// for every node in a revision tree computes its distance from the closest +// leaf +function computeHeight(revs) { + var height = {}; + var edges = []; + traverseRevTree(revs, function (isLeaf, pos, id, prnt) { + var rev = pos + "-" + id; + if (isLeaf) { + height[rev] = 0; + } + if (prnt !== undefined) { + edges.push({from: prnt, to: rev}); + } + return rev; + }); + + edges.reverse(); + edges.forEach(function (edge) { + if (height[edge.from] === undefined) { + height[edge.from] = 1 + height[edge.to]; + } else { + height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]); + } + }); + return height; +} + +function allDocsKeysQuery(api, opts, callback) { + var keys = ('limit' in opts) ? + opts.keys.slice(opts.skip, opts.limit + opts.skip) : + (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys; + if (opts.descending) { + keys.reverse(); + } + if (!keys.length) { + return api._allDocs({limit: 0}, callback); + } + var finalResults = { + offset: opts.skip + }; + return PouchPromise.all(keys.map(function (key) { + var subOpts = extend({key: key, deleted: 'ok'}, opts); + ['limit', 'skip', 'keys'].forEach(function (optKey) { + delete subOpts[optKey]; + }); + return new PouchPromise(function (resolve, reject) { + api._allDocs(subOpts, function (err, res) { + /* istanbul ignore if */ + if (err) { + return reject(err); + } + finalResults.total_rows = res.total_rows; + resolve(res.rows[0] || {key: key, error: 'not_found'}); + }); + }); + })).then(function (results) { + finalResults.rows = results; + return finalResults; + }); +} + +// all compaction is done in a queue, to avoid attaching +// too many listeners at once +function doNextCompaction(self) { + var task = self._compactionQueue[0]; + var opts = task.opts; + var callback = task.callback; + self.get('_local/compaction').catch(function () { + return false; + }).then(function (doc) { + if (doc && doc.last_seq) { + opts.last_seq = doc.last_seq; + } + self._compact(opts, function (err, res) { + /* istanbul ignore if */ + if (err) { + callback(err); + } else { + callback(null, res); + } + process.nextTick(function () { + self._compactionQueue.shift(); + if (self._compactionQueue.length) { + doNextCompaction(self); + } + }); + }); + }); +} + +function attachmentNameError(name) { + if (name.charAt(0) === '_') { + return name + 'is not a valid attachment name, attachment ' + + 'names cannot start with \'_\''; + } + return false; +} + +inherits(AbstractPouchDB, EventEmitter); + +function AbstractPouchDB() { + EventEmitter.call(this); +} + +AbstractPouchDB.prototype.post = + adapterFun('post', function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof doc !== 'object' || Array.isArray(doc)) { + return callback(createError(NOT_AN_OBJECT)); + } + this.bulkDocs({docs: [doc]}, opts, yankError(callback)); +}); + +AbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof doc !== 'object' || Array.isArray(doc)) { + return cb(createError(NOT_AN_OBJECT)); + } + invalidIdError(doc._id); + if (isLocalId(doc._id) && typeof this._putLocal === 'function') { + if (doc._deleted) { + return this._removeLocal(doc, cb); + } else { + return this._putLocal(doc, cb); + } + } + if (typeof this._put === 'function' && opts.new_edits !== false) { + this._put(doc, opts, cb); + } else { + this.bulkDocs({docs: [doc]}, opts, yankError(cb)); + } +}); + +AbstractPouchDB.prototype.putAttachment = + adapterFun('putAttachment', function (docId, attachmentId, rev, + blob, type) { + var api = this; + if (typeof type === 'function') { + type = blob; + blob = rev; + rev = null; + } + // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267 + /* istanbul ignore if */ + if (typeof type === 'undefined') { + type = blob; + blob = rev; + rev = null; + } + + function createAttachment(doc) { + var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0; + doc._attachments = doc._attachments || {}; + doc._attachments[attachmentId] = { + content_type: type, + data: blob, + revpos: ++prevrevpos + }; + return api.put(doc); + } + + return api.get(docId).then(function (doc) { + if (doc._rev !== rev) { + throw createError(REV_CONFLICT); + } + + return createAttachment(doc); + }, function (err) { + // create new doc + /* istanbul ignore else */ + if (err.reason === MISSING_DOC.message) { + return createAttachment({_id: docId}); + } else { + throw err; + } + }); +}); + +AbstractPouchDB.prototype.removeAttachment = + adapterFun('removeAttachment', function (docId, attachmentId, rev, + callback) { + var self = this; + self.get(docId, function (err, obj) { + /* istanbul ignore if */ + if (err) { + callback(err); + return; + } + if (obj._rev !== rev) { + callback(createError(REV_CONFLICT)); + return; + } + /* istanbul ignore if */ + if (!obj._attachments) { + return callback(); + } + delete obj._attachments[attachmentId]; + if (Object.keys(obj._attachments).length === 0) { + delete obj._attachments; + } + self.put(obj, callback); + }); +}); + +AbstractPouchDB.prototype.remove = + adapterFun('remove', function (docOrId, optsOrRev, opts, callback) { + var doc; + if (typeof optsOrRev === 'string') { + // id, rev, opts, callback style + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + } else { + // doc, opts, callback style + doc = docOrId; + if (typeof optsOrRev === 'function') { + callback = optsOrRev; + opts = {}; + } else { + callback = opts; + opts = optsOrRev; + } + } + opts = opts || {}; + opts.was_delete = true; + var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)}; + newDoc._deleted = true; + if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') { + return this._removeLocal(doc, callback); + } + this.bulkDocs({docs: [newDoc]}, opts, yankError(callback)); +}); + +AbstractPouchDB.prototype.revsDiff = + adapterFun('revsDiff', function (req, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var ids = Object.keys(req); + + if (!ids.length) { + return callback(null, {}); + } + + var count = 0; + var missing = new _Map(); + + function addToMissing(id, revId) { + if (!missing.has(id)) { + missing.set(id, {missing: []}); + } + missing.get(id).missing.push(revId); + } + + function processDoc(id, rev_tree) { + // Is this fast enough? Maybe we should switch to a set simulated by a map + var missingForId = req[id].slice(0); + traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx, + opts) { + var rev = pos + '-' + revHash; + var idx = missingForId.indexOf(rev); + if (idx === -1) { + return; + } + + missingForId.splice(idx, 1); + /* istanbul ignore if */ + if (opts.status !== 'available') { + addToMissing(id, rev); + } + }); + + // Traversing the tree is synchronous, so now `missingForId` contains + // revisions that were not found in the tree + missingForId.forEach(function (rev) { + addToMissing(id, rev); + }); + } + + ids.map(function (id) { + this._getRevisionTree(id, function (err, rev_tree) { + if (err && err.status === 404 && err.message === 'missing') { + missing.set(id, {missing: req[id]}); + } else if (err) { + /* istanbul ignore next */ + return callback(err); + } else { + processDoc(id, rev_tree); + } + + if (++count === ids.length) { + // convert LazyMap to object + var missingObj = {}; + missing.forEach(function (value, key) { + missingObj[key] = value; + }); + return callback(null, missingObj); + } + }); + }, this); +}); + +// _bulk_get API for faster replication, as described in +// https://github.com/apache/couchdb-chttpd/pull/33 +// At the "abstract" level, it will just run multiple get()s in +// parallel, because this isn't much of a performance cost +// for local databases (except the cost of multiple transactions, which is +// small). The http adapter overrides this in order +// to do a more efficient single HTTP request. +AbstractPouchDB.prototype.bulkGet = + adapterFun('bulkGet', function (opts, callback) { + bulkGet(this, opts, callback); +}); + +// compact one document and fire callback +// by compacting we mean removing all revisions which +// are further from the leaf in revision tree than max_height +AbstractPouchDB.prototype.compactDocument = + adapterFun('compactDocument', function (docId, maxHeight, callback) { + var self = this; + this._getRevisionTree(docId, function (err, revTree) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + var height = computeHeight(revTree); + var candidates = []; + var revs = []; + Object.keys(height).forEach(function (rev) { + if (height[rev] > maxHeight) { + candidates.push(rev); + } + }); + + traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) { + var rev = pos + '-' + revHash; + if (opts.status === 'available' && candidates.indexOf(rev) !== -1) { + revs.push(rev); + } + }); + self._doCompaction(docId, revs, callback); + }); +}); + +// compact the whole database using single document +// compaction +AbstractPouchDB.prototype.compact = + adapterFun('compact', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + var self = this; + opts = opts || {}; + + self._compactionQueue = self._compactionQueue || []; + self._compactionQueue.push({opts: opts, callback: callback}); + if (self._compactionQueue.length === 1) { + doNextCompaction(self); + } +}); +AbstractPouchDB.prototype._compact = function (opts, callback) { + var self = this; + var changesOpts = { + return_docs: false, + last_seq: opts.last_seq || 0 + }; + var promises = []; + + function onChange(row) { + promises.push(self.compactDocument(row.id, 0)); + } + function onComplete(resp) { + var lastSeq = resp.last_seq; + PouchPromise.all(promises).then(function () { + return upsert(self, '_local/compaction', function deltaFunc(doc) { + if (!doc.last_seq || doc.last_seq < lastSeq) { + doc.last_seq = lastSeq; + return doc; + } + return false; // somebody else got here first, don't update + }); + }).then(function () { + callback(null, {ok: true}); + }).catch(callback); + } + self.changes(changesOpts) + .on('change', onChange) + .on('complete', onComplete) + .on('error', callback); +}; + +/* Begin api wrappers. Specific functionality to storage belongs in the + _[method] */ +AbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + if (typeof id !== 'string') { + return cb(createError(INVALID_ID)); + } + if (isLocalId(id) && typeof this._getLocal === 'function') { + return this._getLocal(id, cb); + } + var leaves = [], self = this; + + function finishOpenRevs() { + var result = []; + var count = leaves.length; + /* istanbul ignore if */ + if (!count) { + return cb(null, result); + } + // order with open_revs is unspecified + leaves.forEach(function (leaf) { + self.get(id, { + rev: leaf, + revs: opts.revs, + attachments: opts.attachments + }, function (err, doc) { + if (!err) { + result.push({ok: doc}); + } else { + result.push({missing: leaf}); + } + count--; + if (!count) { + cb(null, result); + } + }); + }); + } + + if (opts.open_revs) { + if (opts.open_revs === "all") { + this._getRevisionTree(id, function (err, rev_tree) { + if (err) { + return cb(err); + } + leaves = collectLeaves(rev_tree).map(function (leaf) { + return leaf.rev; + }); + finishOpenRevs(); + }); + } else { + if (Array.isArray(opts.open_revs)) { + leaves = opts.open_revs; + for (var i = 0; i < leaves.length; i++) { + var l = leaves[i]; + // looks like it's the only thing couchdb checks + if (!(typeof (l) === "string" && /^\d+-/.test(l))) { + return cb(createError(INVALID_REV)); + } + } + finishOpenRevs(); + } else { + return cb(createError(UNKNOWN_ERROR, 'function_clause')); + } + } + return; // open_revs does not like other options + } + + return this._get(id, opts, function (err, result) { + if (err) { + return cb(err); + } + + var doc = result.doc; + var metadata = result.metadata; + var ctx = result.ctx; + + if (opts.conflicts) { + var conflicts = collectConflicts(metadata); + if (conflicts.length) { + doc._conflicts = conflicts; + } + } + + if (isDeleted(metadata, doc._rev)) { + doc._deleted = true; + } + + if (opts.revs || opts.revs_info) { + var paths = rootToLeaf(metadata.rev_tree); + var path = arrayFirst(paths, function (arr) { + return arr.ids.map(function (x) { return x.id; }) + .indexOf(doc._rev.split('-')[1]) !== -1; + }); + + var indexOfRev = path.ids.map(function (x) {return x.id; }) + .indexOf(doc._rev.split('-')[1]) + 1; + var howMany = path.ids.length - indexOfRev; + path.ids.splice(indexOfRev, howMany); + path.ids.reverse(); + + if (opts.revs) { + doc._revisions = { + start: (path.pos + path.ids.length) - 1, + ids: path.ids.map(function (rev) { + return rev.id; + }) + }; + } + if (opts.revs_info) { + var pos = path.pos + path.ids.length; + doc._revs_info = path.ids.map(function (rev) { + pos--; + return { + rev: pos + '-' + rev.id, + status: rev.opts.status + }; + }); + } + } + + if (opts.attachments && doc._attachments) { + var attachments = doc._attachments; + var count = Object.keys(attachments).length; + if (count === 0) { + return cb(null, doc); + } + Object.keys(attachments).forEach(function (key) { + this._getAttachment(doc._id, key, attachments[key], { + // Previously the revision handling was done in adapter.js + // getAttachment, however since idb-next doesnt we need to + // pass the rev through + rev: doc._rev, + binary: opts.binary, + ctx: ctx + }, function (err, data) { + var att = doc._attachments[key]; + att.data = data; + delete att.stub; + delete att.length; + if (!--count) { + cb(null, doc); + } + }); + }, self); + } else { + if (doc._attachments) { + for (var key in doc._attachments) { + /* istanbul ignore else */ + if (doc._attachments.hasOwnProperty(key)) { + doc._attachments[key].stub = true; + } + } + } + cb(null, doc); + } + }); +}); + +// TODO: I dont like this, it forces an extra read for every +// attachment read and enforces a confusing api between +// adapter.js and the adapter implementation +AbstractPouchDB.prototype.getAttachment = + adapterFun('getAttachment', function (docId, attachmentId, opts, callback) { + var self = this; + if (opts instanceof Function) { + callback = opts; + opts = {}; + } + this._get(docId, opts, function (err, res) { + if (err) { + return callback(err); + } + if (res.doc._attachments && res.doc._attachments[attachmentId]) { + opts.ctx = res.ctx; + opts.binary = true; + self._getAttachment(docId, attachmentId, + res.doc._attachments[attachmentId], opts, callback); + } else { + return callback(createError(MISSING_DOC)); + } + }); +}); + +AbstractPouchDB.prototype.allDocs = + adapterFun('allDocs', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if ('keys' in opts) { + if (!Array.isArray(opts.keys)) { + return callback(new TypeError('options.keys must be an array')); + } + var incompatibleOpt = + ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) { + return incompatibleOpt in opts; + })[0]; + if (incompatibleOpt) { + callback(createError(QUERY_PARSE_ERROR, + 'Query parameter `' + incompatibleOpt + + '` is not compatible with multi-get' + )); + return; + } + if (this.type() !== 'http') { + return allDocsKeysQuery(this, opts, callback); + } + } + + return this._allDocs(opts, callback); +}); + +AbstractPouchDB.prototype.changes = function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return new Changes(this, opts, callback); +}; + +AbstractPouchDB.prototype.close = adapterFun('close', function (callback) { + this._closed = true; + return this._close(callback); +}); + +AbstractPouchDB.prototype.info = adapterFun('info', function (callback) { + var self = this; + this._info(function (err, info) { + if (err) { + return callback(err); + } + // assume we know better than the adapter, unless it informs us + info.db_name = info.db_name || self.name; + info.auto_compaction = !!(self.auto_compaction && self.type() !== 'http'); + info.adapter = self.type(); + callback(null, info); + }); +}); + +AbstractPouchDB.prototype.id = adapterFun('id', function (callback) { + return this._id(callback); +}); + +/* istanbul ignore next */ +AbstractPouchDB.prototype.type = function () { + return (typeof this._type === 'function') ? this._type() : this.adapter; +}; + +AbstractPouchDB.prototype.bulkDocs = + adapterFun('bulkDocs', function (req, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + opts = opts || {}; + + if (Array.isArray(req)) { + req = { + docs: req + }; + } + + if (!req || !req.docs || !Array.isArray(req.docs)) { + return callback(createError(MISSING_BULK_DOCS)); + } + + for (var i = 0; i < req.docs.length; ++i) { + if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) { + return callback(createError(NOT_AN_OBJECT)); + } + } + + var attachmentError; + req.docs.forEach(function (doc) { + if (doc._attachments) { + Object.keys(doc._attachments).forEach(function (name) { + attachmentError = attachmentError || attachmentNameError(name); + }); + } + }); + + if (attachmentError) { + return callback(createError(BAD_REQUEST, attachmentError)); + } + + if (!('new_edits' in opts)) { + if ('new_edits' in req) { + opts.new_edits = req.new_edits; + } else { + opts.new_edits = true; + } + } + + if (!opts.new_edits && this.type() !== 'http') { + // ensure revisions of the same doc are sorted, so that + // the local adapter processes them correctly (#2935) + req.docs.sort(compareByIdThenRev); + } + + cleanDocs(req.docs); + + return this._bulkDocs(req, opts, function (err, res) { + if (err) { + return callback(err); + } + if (!opts.new_edits) { + // this is what couch does when new_edits is false + res = res.filter(function (x) { + return x.error; + }); + } + callback(null, res); + }); +}); + +AbstractPouchDB.prototype.registerDependentDatabase = + adapterFun('registerDependentDatabase', function (dependentDb, + callback) { + var depDB = new this.constructor(dependentDb, this.__opts); + + function diffFun(doc) { + doc.dependentDbs = doc.dependentDbs || {}; + if (doc.dependentDbs[dependentDb]) { + return false; // no update required + } + doc.dependentDbs[dependentDb] = true; + return doc; + } + upsert(this, '_local/_pouch_dependentDbs', diffFun) + .then(function () { + callback(null, {db: depDB}); + }).catch(callback); +}); + +AbstractPouchDB.prototype.destroy = + adapterFun('destroy', function (opts, callback) { + + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + var self = this; + var usePrefix = 'use_prefix' in self ? self.use_prefix : true; + + function destroyDb() { + // call destroy method of the particular adaptor + self._destroy(opts, function (err, resp) { + if (err) { + return callback(err); + } + self._destroyed = true; + self.emit('destroyed'); + callback(null, resp || { 'ok': true }); + }); + } + + if (self.type() === 'http') { + // no need to check for dependent DBs if it's a remote DB + return destroyDb(); + } + + self.get('_local/_pouch_dependentDbs', function (err, localDoc) { + if (err) { + /* istanbul ignore if */ + if (err.status !== 404) { + return callback(err); + } else { // no dependencies + return destroyDb(); + } + } + var dependentDbs = localDoc.dependentDbs; + var PouchDB = self.constructor; + var deletedMap = Object.keys(dependentDbs).map(function (name) { + // use_prefix is only false in the browser + /* istanbul ignore next */ + var trueName = usePrefix ? + name.replace(new RegExp('^' + PouchDB.prefix), '') : name; + return new PouchDB(trueName, self.__opts).destroy(); + }); + PouchPromise.all(deletedMap).then(destroyDb, callback); + }); +}); + +function TaskQueue() { + this.isReady = false; + this.failed = false; + this.queue = []; +} + +TaskQueue.prototype.execute = function () { + var fun; + if (this.failed) { + while ((fun = this.queue.shift())) { + fun(this.failed); + } + } else { + while ((fun = this.queue.shift())) { + fun(); + } + } +}; + +TaskQueue.prototype.fail = function (err) { + this.failed = err; + this.execute(); +}; + +TaskQueue.prototype.ready = function (db) { + this.isReady = true; + this.db = db; + this.execute(); +}; + +TaskQueue.prototype.addTask = function (fun) { + this.queue.push(fun); + if (this.failed) { + this.execute(); + } +}; + +function parseAdapter(name, opts) { + var match = name.match(/([a-z\-]*):\/\/(.*)/); + if (match) { + // the http adapter expects the fully qualified name + name = /http(s?)/.test(match[1]) ? match[1] + '://' + match[2] : match[2]; + return {name: name, adapter: match[1]}; + } + + // check for browsers that have been upgraded from websql-only to websql+idb + var skipIdb = 'idb' in PouchDB.adapters && 'websql' in PouchDB.adapters && + hasLocalStorage() && + localStorage['_pouch__websqldb_' + PouchDB.prefix + name]; + + var adapterName; + + if (opts.adapter) { + adapterName = opts.adapter; + } else if (typeof opts !== 'undefined' && opts.db) { + adapterName = 'leveldb'; + } else { // automatically determine adapter + for (var i = 0; i < PouchDB.preferredAdapters.length; ++i) { + adapterName = PouchDB.preferredAdapters[i]; + /* istanbul ignore if */ + if (skipIdb && adapterName === 'idb') { + // log it, because this can be confusing during development + guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' + + ' avoid data loss, because it was already opened with WebSQL.'); + continue; // keep using websql to avoid user data loss + } + break; + } + } + + var adapter = PouchDB.adapters[adapterName]; + + // if adapter is invalid, then an error will be thrown later + var usePrefix = (adapter && 'use_prefix' in adapter) ? + adapter.use_prefix : true; + + return { + name: usePrefix ? (PouchDB.prefix + name) : name, + adapter: adapterName + }; +} + +// OK, so here's the deal. Consider this code: +// var db1 = new PouchDB('foo'); +// var db2 = new PouchDB('foo'); +// db1.destroy(); +// ^ these two both need to emit 'destroyed' events, +// as well as the PouchDB constructor itself. +// So we have one db object (whichever one got destroy() called on it) +// responsible for emitting the initial event, which then gets emitted +// by the constructor, which then broadcasts it to any other dbs +// that may have been created with the same name. +function prepareForDestruction(self) { + + var destructionListeners = self.constructor._destructionListeners; + + function onDestroyed() { + self.constructor.emit('destroyed', self.name); + } + + function onConstructorDestroyed() { + self.removeListener('destroyed', onDestroyed); + self.emit('destroyed', self); + } + + self.once('destroyed', onDestroyed); + + // in setup.js, the constructor is primed to listen for destroy events + if (!destructionListeners.has(self.name)) { + destructionListeners.set(self.name, []); + } + destructionListeners.get(self.name).push(onConstructorDestroyed); +} + +inherits(PouchDB, AbstractPouchDB); +function PouchDB(name, opts) { + // In Node our test suite only tests this for PouchAlt unfortunately + /* istanbul ignore if */ + if (!(this instanceof PouchDB)) { + return new PouchDB(name, opts); + } + + var self = this; + opts = opts || {}; + + if (name && typeof name === 'object') { + opts = name; + name = opts.name; + delete opts.name; + } + + this.__opts = opts = clone(opts); + + self.auto_compaction = opts.auto_compaction; + self.prefix = PouchDB.prefix; + + if (typeof name !== 'string') { + throw new Error('Missing/invalid DB name'); + } + + var prefixedName = (opts.prefix || '') + name; + var backend = parseAdapter(prefixedName, opts); + + opts.name = backend.name; + opts.adapter = opts.adapter || backend.adapter; + + self.name = name; + self._adapter = opts.adapter; + debug('pouchdb:adapter')('Picked adapter: ' + opts.adapter); + + if (!PouchDB.adapters[opts.adapter] || + !PouchDB.adapters[opts.adapter].valid()) { + throw new Error('Invalid Adapter: ' + opts.adapter); + } + + AbstractPouchDB.call(self); + self.taskqueue = new TaskQueue(); + + self.adapter = opts.adapter; + + PouchDB.adapters[opts.adapter].call(self, opts, function (err) { + if (err) { + return self.taskqueue.fail(err); + } + prepareForDestruction(self); + + self.emit('created', self); + PouchDB.emit('created', self.name); + self.taskqueue.ready(self); + }); + +} + +PouchDB.debug = debug; + +PouchDB.adapters = {}; +PouchDB.preferredAdapters = []; + +PouchDB.prefix = '_pouch_'; + +var eventEmitter = new EventEmitter(); + +function setUpEventEmitter(Pouch) { + Object.keys(EventEmitter.prototype).forEach(function (key) { + if (typeof EventEmitter.prototype[key] === 'function') { + Pouch[key] = eventEmitter[key].bind(eventEmitter); + } + }); + + // these are created in constructor.js, and allow us to notify each DB with + // the same name that it was destroyed, via the constructor object + var destructListeners = Pouch._destructionListeners = new _Map(); + Pouch.on('destroyed', function onConstructorDestroyed(name) { + destructListeners.get(name).forEach(function (callback) { + callback(); + }); + destructListeners.delete(name); + }); +} + +setUpEventEmitter(PouchDB); + +PouchDB.adapter = function (id, obj, addToPreferredAdapters) { + /* istanbul ignore else */ + if (obj.valid()) { + PouchDB.adapters[id] = obj; + if (addToPreferredAdapters) { + PouchDB.preferredAdapters.push(id); + } + } +}; + +PouchDB.plugin = function (obj) { + if (typeof obj === 'function') { // function style for plugins + obj(PouchDB); + } else if (typeof obj !== 'object' || Object.keys(obj).length === 0){ + throw new Error('Invalid plugin: object passed in is empty or not an object'); + } else { + Object.keys(obj).forEach(function (id) { // object style for plugins + PouchDB.prototype[id] = obj[id]; + }); + } + return PouchDB; +}; + +PouchDB.defaults = function (defaultOpts) { + function PouchAlt(name, opts) { + if (!(this instanceof PouchAlt)) { + return new PouchAlt(name, opts); + } + + opts = opts || {}; + + if (name && typeof name === 'object') { + opts = name; + name = opts.name; + delete opts.name; + } + + opts = extend({}, defaultOpts, opts); + PouchDB.call(this, name, opts); + } + + inherits(PouchAlt, PouchDB); + + PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice(); + Object.keys(PouchDB).forEach(function (key) { + if (!(key in PouchAlt)) { + PouchAlt[key] = PouchDB[key]; + } + }); + + return PouchAlt; +}; + +// managed automatically by set-version.js +var version = "6.0.6"; + +PouchDB.version = version; + +function isFunction(f) { + return 'function' === typeof f; +} + +function getPrefix(db) { + if (isFunction(db.prefix)) { + return db.prefix(); + } + return db; +} + +function clone$1(_obj) { + var obj = {}; + for(var k in _obj) { + obj[k] = _obj[k]; + } + return obj; +} + +function nut(db, precodec, codec) { + function encodePrefix(prefix, key, opts1, opts2) { + return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]); + } + + function addEncodings(op, prefix) { + if(prefix && prefix.options) { + op.keyEncoding = + op.keyEncoding || prefix.options.keyEncoding; + op.valueEncoding = + op.valueEncoding || prefix.options.valueEncoding; + } + return op; + } + + db.open(function () { /* no-op */}); + + return { + apply: function (ops, opts, cb) { + opts = opts || {}; + + var batch = []; + var i = -1; + var len = ops.length; + + while (++i < len) { + var op = ops[i]; + addEncodings(op, op.prefix); + op.prefix = getPrefix(op.prefix); + batch.push({ + key: encodePrefix(op.prefix, op.key, opts, op), + value: op.type !== 'del' && codec.encodeValue(op.value, opts, op), + type: op.type + }); + } + db.db.batch(batch, opts, cb); + }, + get: function (key, prefix, opts, cb) { + opts.asBuffer = codec.valueAsBuffer(opts); + return db.db.get( + encodePrefix(prefix, key, opts), + opts, + function (err, value) { + if (err) { + cb(err); + } else { + cb(null, codec.decodeValue(value, opts)); + } + } + ); + }, + createDecoder: function (opts) { + return function (key, value) { + return { + key: codec.decodeKey(precodec.decode(key)[1], opts), + value: codec.decodeValue(value, opts) + }; + }; + }, + isClosed: function isClosed() { + return db.isClosed(); + }, + close: function close(cb) { + return db.close(cb); + }, + iterator: function (_opts) { + var opts = clone$1(_opts || {}); + var prefix = _opts.prefix || []; + + function encodeKey(key) { + return encodePrefix(prefix, key, opts, {}); + } + + ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound); + + // if these legacy values are in the options, remove them + + opts.prefix = null; + + //************************************************ + //hard coded defaults, for now... + //TODO: pull defaults and encoding out of levelup. + opts.keyAsBuffer = opts.valueAsBuffer = false; + //************************************************ + + + //this is vital, otherwise limit: undefined will + //create an empty stream. + /* istanbul ignore next */ + if ('number' !== typeof opts.limit) { + opts.limit = -1; + } + + opts.keyAsBuffer = precodec.buffer; + opts.valueAsBuffer = codec.valueAsBuffer(opts); + + function wrapIterator(iterator) { + return { + next: function (cb) { + return iterator.next(cb); + }, + end: function (cb) { + iterator.end(cb); + } + }; + } + + return wrapIterator(db.db.iterator(opts)); + } + }; +} + +function NotFoundError() { + Error.call(this); +} + +inherits(NotFoundError, Error); + +NotFoundError.prototype.name = 'NotFoundError'; + +var EventEmitter$1 = events.EventEmitter; +var version$1 = "6.5.4"; + +var NOT_FOUND_ERROR = new NotFoundError(); + +var sublevel = function (nut, prefix, createStream, options) { + var emitter = new EventEmitter$1(); + emitter.sublevels = {}; + emitter.options = options; + + emitter.version = version$1; + + emitter.methods = {}; + prefix = prefix || []; + + function mergeOpts(opts) { + var o = {}; + var k; + if (options) { + for (k in options) { + if (typeof options[k] !== 'undefined') { + o[k] = options[k]; + } + } + } + if (opts) { + for (k in opts) { + if (typeof opts[k] !== 'undefined') { + o[k] = opts[k]; + } + } + } + return o; + } + + emitter.put = function (key, value, opts, cb) { + if ('function' === typeof opts) { + cb = opts; + opts = {}; + } + + nut.apply([{ + key: key, value: value, + prefix: prefix.slice(), type: 'put' + }], mergeOpts(opts), function (err) { + /* istanbul ignore next */ + if (err) { + return cb(err); + } + emitter.emit('put', key, value); + cb(null); + }); + }; + + emitter.prefix = function () { + return prefix.slice(); + }; + + emitter.batch = function (ops, opts, cb) { + if ('function' === typeof opts) { + cb = opts; + opts = {}; + } + + ops = ops.map(function (op) { + return { + key: op.key, + value: op.value, + prefix: op.prefix || prefix, + keyEncoding: op.keyEncoding, // * + valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel) + type: op.type + }; + }); + + nut.apply(ops, mergeOpts(opts), function (err) { + /* istanbul ignore next */ + if (err) { + return cb(err); + } + emitter.emit('batch', ops); + cb(null); + }); + }; + + emitter.get = function (key, opts, cb) { + /* istanbul ignore else */ + if ('function' === typeof opts) { + cb = opts; + opts = {}; + } + nut.get(key, prefix, mergeOpts(opts), function (err, value) { + if (err) { + cb(NOT_FOUND_ERROR); + } else { + cb(null, value); + } + }); + }; + + emitter.sublevel = function (name, opts) { + return emitter.sublevels[name] = + emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts)); + }; + + emitter.readStream = emitter.createReadStream = function (opts) { + opts = mergeOpts(opts); + opts.prefix = prefix; + var stream; + var it = nut.iterator(opts); + + stream = createStream(opts, nut.createDecoder(opts)); + stream.setIterator(it); + + return stream; + }; + + emitter.close = function (cb) { + nut.close(cb); + }; + + emitter.isOpen = nut.isOpen; + emitter.isClosed = nut.isClosed; + + return emitter; +}; + +/* Copyright (c) 2012-2014 LevelUP contributors + * See list at + * MIT License + */ + +// NOTE: we are fixed to readable-stream@1.0.x for now +// for pure Streams2 across Node versions +var Readable = ReadableStreamCore.Readable; + +function ReadStream(options, makeData) { + if (!(this instanceof ReadStream)) { + return new ReadStream(options, makeData); + } + + Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + + // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref + + this._waiting = false; + this._options = options; + this._makeData = makeData; +} + +inherits(ReadStream, Readable); + +ReadStream.prototype.setIterator = function (it) { + this._iterator = it; + /* istanbul ignore if */ + if (this._destroyed) { + return it.end(function () {}); + } + /* istanbul ignore if */ + if (this._waiting) { + this._waiting = false; + return this._read(); + } + return this; +}; + +ReadStream.prototype._read = function read() { + var self = this; + /* istanbul ignore if */ + if (self._destroyed) { + return; + } + /* istanbul ignore if */ + if (!self._iterator) { + return this._waiting = true; + } + + self._iterator.next(function (err, key, value) { + if (err || (key === undefined && value === undefined)) { + if (!err && !self._destroyed) { + self.push(null); + } + return self._cleanup(err); + } + + + value = self._makeData(key, value); + if (!self._destroyed) { + self.push(value); + } + }); +}; + +ReadStream.prototype._cleanup = function (err) { + if (this._destroyed) { + return; + } + + this._destroyed = true; + + var self = this; + /* istanbul ignore if */ + if (err) { + self.emit('error', err); + } + + /* istanbul ignore else */ + if (self._iterator) { + self._iterator.end(function () { + self._iterator = null; + self.emit('close'); + }); + } else { + self.emit('close'); + } +}; + +ReadStream.prototype.destroy = function () { + this._cleanup(); +}; + +var precodec = { + encode: function (decodedKey) { + return '\xff' + decodedKey[0] + '\xff' + decodedKey[1]; + }, + decode: function (encodedKeyAsBuffer) { + var str = encodedKeyAsBuffer.toString(); + var idx = str.indexOf('\xff', 1); + return [str.substring(1, idx), str.substring(idx + 1)]; + }, + lowerBound: '\x00', + upperBound: '\xff' +}; + +var codec = new Codec(); + +function sublevelPouch(db) { + return sublevel(nut(db, precodec, codec), [], ReadStream, db.options); +} + +function toObject(array) { + return array.reduce(function (obj, item) { + obj[item] = true; + return obj; + }, {}); +} +// List of top level reserved words for doc +var reservedWords = toObject([ + '_id', + '_rev', + '_attachments', + '_deleted', + '_revisions', + '_revs_info', + '_conflicts', + '_deleted_conflicts', + '_local_seq', + '_rev_tree', + //replication documents + '_replication_id', + '_replication_state', + '_replication_state_time', + '_replication_state_reason', + '_replication_stats', + // Specific to Couchbase Sync Gateway + '_removed' +]); + +// List of reserved words that should end up the document +var dataWords = toObject([ + '_attachments', + //replication documents + '_replication_id', + '_replication_state', + '_replication_state_time', + '_replication_state_reason', + '_replication_stats' +]); + +function parseRevisionInfo(rev) { + if (!/^\d+\-./.test(rev)) { + return createError(INVALID_REV); + } + var idx = rev.indexOf('-'); + var left = rev.substring(0, idx); + var right = rev.substring(idx + 1); + return { + prefix: parseInt(left, 10), + id: right + }; +} + +function makeRevTreeFromRevisions(revisions, opts) { + var pos = revisions.start - revisions.ids.length + 1; + + var revisionIds = revisions.ids; + var ids = [revisionIds[0], opts, []]; + + for (var i = 1, len = revisionIds.length; i < len; i++) { + ids = [revisionIds[i], {status: 'missing'}, [ids]]; + } + + return [{ + pos: pos, + ids: ids + }]; +} + +// Preprocess documents, parse their revisions, assign an id and a +// revision for new writes that are missing them, etc +function parseDoc(doc, newEdits) { + + var nRevNum; + var newRevId; + var revInfo; + var opts = {status: 'available'}; + if (doc._deleted) { + opts.deleted = true; + } + + if (newEdits) { + if (!doc._id) { + doc._id = uuid(); + } + newRevId = uuid(32, 16).toLowerCase(); + if (doc._rev) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + doc._rev_tree = [{ + pos: revInfo.prefix, + ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]] + }]; + nRevNum = revInfo.prefix + 1; + } else { + doc._rev_tree = [{ + pos: 1, + ids : [newRevId, opts, []] + }]; + nRevNum = 1; + } + } else { + if (doc._revisions) { + doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); + nRevNum = doc._revisions.start; + newRevId = doc._revisions.ids[0]; + } + if (!doc._rev_tree) { + revInfo = parseRevisionInfo(doc._rev); + if (revInfo.error) { + return revInfo; + } + nRevNum = revInfo.prefix; + newRevId = revInfo.id; + doc._rev_tree = [{ + pos: nRevNum, + ids: [newRevId, opts, []] + }]; + } + } + + invalidIdError(doc._id); + + doc._rev = nRevNum + '-' + newRevId; + + var result = {metadata : {}, data : {}}; + for (var key in doc) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(doc, key)) { + var specialKey = key[0] === '_'; + if (specialKey && !reservedWords[key]) { + var error = createError(DOC_VALIDATION, key); + error.message = DOC_VALIDATION.message + ': ' + key; + throw error; + } else if (specialKey && !dataWords[key]) { + result.metadata[key.slice(1)] = doc[key]; + } else { + result.data[key] = doc[key]; + } + } + } + return result; +} + +function atob(str) { + var base64 = new Buffer(str, 'base64'); + // Node.js will just skip the characters it can't decode instead of + // throwing an exception + if (base64.toString('base64') !== str) { + throw new Error("attachment is not a valid base64 string"); + } + return base64.toString('binary'); +} + +function btoa(str) { + return new Buffer(str, 'binary').toString('base64'); +} + +function typedBuffer(binString, buffType, type) { + // buffType is either 'binary' or 'base64' + var buff = new Buffer(binString, buffType); + buff.type = type; // non-standard, but used for consistency with the browser + return buff; +} + +function b64ToBluffer(b64, type) { + return typedBuffer(b64, 'base64', type); +} + +function binStringToBluffer(binString, type) { + return typedBuffer(binString, 'binary', type); +} + +function blobToBase64(blobOrBuffer, callback) { + callback(blobOrBuffer.toString('base64')); +} + +function binaryMd5(data, callback) { + var base64 = crypto.createHash('md5').update(data, 'binary').digest('base64'); + callback(base64); +} + +function stringMd5(string) { + return crypto.createHash('md5').update(string, 'binary').digest('hex'); +} + +function updateDoc(revLimit, prev, docInfo, results, + i, cb, writeDoc, newEdits) { + + if (revExists(prev.rev_tree, docInfo.metadata.rev)) { + results[i] = docInfo; + return cb(); + } + + // sometimes this is pre-calculated. historically not always + var previousWinningRev = prev.winningRev || winningRev(prev); + var previouslyDeleted = 'deleted' in prev ? prev.deleted : + isDeleted(prev, previousWinningRev); + var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted : + isDeleted(docInfo.metadata); + var isRoot = /^1-/.test(docInfo.metadata.rev); + + if (previouslyDeleted && !deleted && newEdits && isRoot) { + var newDoc = docInfo.data; + newDoc._rev = previousWinningRev; + newDoc._id = docInfo.metadata.id; + docInfo = parseDoc(newDoc, newEdits); + } + + var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); + + var inConflict = newEdits && (((previouslyDeleted && deleted) || + (!previouslyDeleted && merged.conflicts !== 'new_leaf') || + (previouslyDeleted && !deleted && merged.conflicts === 'new_branch'))); + + if (inConflict) { + var err = createError(REV_CONFLICT); + results[i] = err; + return cb(); + } + + var newRev = docInfo.metadata.rev; + docInfo.metadata.rev_tree = merged.tree; + docInfo.stemmedRevs = merged.stemmedRevs || []; + /* istanbul ignore else */ + if (prev.rev_map) { + docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb + } + + // recalculate + var winningRev$$ = winningRev(docInfo.metadata); + var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$); + + // calculate the total number of documents that were added/removed, + // from the perspective of total_rows/doc_count + var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 : + previouslyDeleted < winningRevIsDeleted ? -1 : 1; + + var newRevIsDeleted; + if (newRev === winningRev$$) { + // if the new rev is the same as the winning rev, we can reuse that value + newRevIsDeleted = winningRevIsDeleted; + } else { + // if they're not the same, then we need to recalculate + newRevIsDeleted = isDeleted(docInfo.metadata, newRev); + } + + writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted, + true, delta, i, cb); +} + +function rootIsMissing(docInfo) { + return docInfo.metadata.rev_tree[0].ids[1].status === 'missing'; +} + +function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, + writeDoc, opts, overallCallback) { + + // Default to 1000 locally + revLimit = revLimit || 1000; + + function insertDoc(docInfo, resultsIdx, callback) { + // Cant insert new deleted documents + var winningRev$$ = winningRev(docInfo.metadata); + var deleted = isDeleted(docInfo.metadata, winningRev$$); + if ('was_delete' in opts && deleted) { + results[resultsIdx] = createError(MISSING_DOC, 'deleted'); + return callback(); + } + + // 4712 - detect whether a new document was inserted with a _rev + var inConflict = newEdits && rootIsMissing(docInfo); + + if (inConflict) { + var err = createError(REV_CONFLICT); + results[resultsIdx] = err; + return callback(); + } + + var delta = deleted ? 0 : 1; + + writeDoc(docInfo, winningRev$$, deleted, deleted, false, + delta, resultsIdx, callback); + } + + var newEdits = opts.new_edits; + var idsToDocs = new _Map(); + + var docsDone = 0; + var docsToDo = docInfos.length; + + function checkAllDocsDone() { + if (++docsDone === docsToDo && overallCallback) { + overallCallback(); + } + } + + docInfos.forEach(function (currentDoc, resultsIdx) { + + if (currentDoc._id && isLocalId(currentDoc._id)) { + var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal'; + api[fun](currentDoc, {ctx: tx}, function (err, res) { + results[resultsIdx] = err || res; + checkAllDocsDone(); + }); + return; + } + + var id = currentDoc.metadata.id; + if (idsToDocs.has(id)) { + docsToDo--; // duplicate + idsToDocs.get(id).push([currentDoc, resultsIdx]); + } else { + idsToDocs.set(id, [[currentDoc, resultsIdx]]); + } + }); + + // in the case of new_edits, the user can provide multiple docs + // with the same id. these need to be processed sequentially + idsToDocs.forEach(function (docs, id) { + var numDone = 0; + + function docWritten() { + if (++numDone < docs.length) { + nextDoc(); + } else { + checkAllDocsDone(); + } + } + function nextDoc() { + var value = docs[numDone]; + var currentDoc = value[0]; + var resultsIdx = value[1]; + + if (fetchedDocs.has(id)) { + updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results, + resultsIdx, docWritten, writeDoc, newEdits); + } else { + // Ensure stemming applies to new writes as well + var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); + currentDoc.metadata.rev_tree = merged.tree; + currentDoc.stemmedRevs = merged.stemmedRevs || []; + insertDoc(currentDoc, resultsIdx, docWritten); + } + } + nextDoc(); + }); +} + +function slowJsonParse(str) { + try { + return JSON.parse(str); + } catch (e) { + /* istanbul ignore next */ + return vuvuzela.parse(str); + } +} + +function safeJsonParse(str) { + // try/catch is deoptimized in V8, leading to slower + // times than we'd like to have. Most documents are _not_ + // huge, and do not require a slower code path just to parse them. + // We can be pretty sure that a document under 50000 characters + // will not be so deeply nested as to throw a stack overflow error + // (depends on the engine and available memory, though, so this is + // just a hunch). 50000 was chosen based on the average length + // of this string in our test suite, to try to find a number that covers + // most of our test cases (26 over this size, 26378 under it). + if (str.length < 50000) { + return JSON.parse(str); + } + return slowJsonParse(str); +} + +function safeJsonStringify(json) { + try { + return JSON.stringify(json); + } catch (e) { + /* istanbul ignore next */ + return vuvuzela.stringify(json); + } +} + +function readAsBlobOrBuffer(storedObject, type) { + // In Node, we've stored a buffer + storedObject.type = type; // non-standard, but used for consistency + return storedObject; +} + +// in Node, we store the buffer directly +function prepareAttachmentForStorage(attData, cb) { + cb(attData); +} + +function createEmptyBlobOrBuffer(type) { + return typedBuffer('', 'binary', type); +} + +// similar to an idb or websql transaction object +// designed to be passed around. basically just caches +// things in-memory and then does a big batch() operation +// when you're done + +function getCacheFor(transaction, store) { + var prefix = store.prefix()[0]; + var cache = transaction._cache; + var subCache = cache.get(prefix); + if (!subCache) { + subCache = new _Map(); + cache.set(prefix, subCache); + } + return subCache; +} + +function LevelTransaction() { + this._batch = []; + this._cache = new _Map(); +} + +LevelTransaction.prototype.get = function (store, key, callback) { + var cache = getCacheFor(this, store); + var exists = cache.get(key); + if (exists) { + return process.nextTick(function () { + callback(null, exists); + }); + } else if (exists === null) { // deleted marker + /* istanbul ignore next */ + return process.nextTick(function () { + callback({name: 'NotFoundError'}); + }); + } + store.get(key, function (err, res) { + if (err) { + /* istanbul ignore else */ + if (err.name === 'NotFoundError') { + cache.set(key, null); + } + return callback(err); + } + cache.set(key, res); + callback(null, res); + }); +}; + +LevelTransaction.prototype.batch = function (batch) { + for (var i = 0, len = batch.length; i < len; i++) { + var operation = batch[i]; + + var cache = getCacheFor(this, operation.prefix); + + if (operation.type === 'put') { + cache.set(operation.key, operation.value); + } else { + cache.set(operation.key, null); + } + } + this._batch = this._batch.concat(batch); +}; + +LevelTransaction.prototype.execute = function (db, callback) { + + var keys = new _Set(); + var uniqBatches = []; + + // remove duplicates; last one wins + for (var i = this._batch.length - 1; i >= 0; i--) { + var operation = this._batch[i]; + var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key; + if (keys.has(lookupKey)) { + continue; + } + keys.add(lookupKey); + uniqBatches.push(operation); + } + + db.batch(uniqBatches, callback); +}; + +var DOC_STORE = 'document-store'; +var BY_SEQ_STORE = 'by-sequence'; +var ATTACHMENT_STORE = 'attach-store'; +var BINARY_STORE = 'attach-binary-store'; +var LOCAL_STORE = 'local-store'; +var META_STORE = 'meta-store'; + +// leveldb barks if we try to open a db multiple times +// so we cache opened connections here for initstore() +var dbStores = new _Map(); + +// store the value of update_seq in the by-sequence store the key name will +// never conflict, since the keys in the by-sequence store are integers +var UPDATE_SEQ_KEY = '_local_last_update_seq'; +var DOC_COUNT_KEY = '_local_doc_count'; +var UUID_KEY = '_local_uuid'; + +var MD5_PREFIX = 'md5-'; + +var safeJsonEncoding = { + encode: safeJsonStringify, + decode: safeJsonParse, + buffer: false, + type: 'cheap-json' +}; + +var levelChanges = new Changes$1(); + +// winningRev and deleted are performance-killers, but +// in newer versions of PouchDB, they are cached on the metadata +function getWinningRev(metadata) { + return 'winningRev' in metadata ? + metadata.winningRev : winningRev(metadata); +} + +function getIsDeleted(metadata, winningRev) { + return 'deleted' in metadata ? + metadata.deleted : isDeleted(metadata, winningRev); +} + +function fetchAttachment(att, stores, opts) { + var type = att.content_type; + return new PouchPromise(function (resolve, reject) { + stores.binaryStore.get(att.digest, function (err, buffer) { + var data; + if (err) { + /* istanbul ignore if */ + if (err.name !== 'NotFoundError') { + return reject(err); + } else { + // empty + if (!opts.binary) { + data = ''; + } else { + data = binStringToBluffer('', type); + } + } + } else { // non-empty + if (opts.binary) { + data = readAsBlobOrBuffer(buffer, type); + } else { + data = buffer.toString('base64'); + } + } + delete att.stub; + delete att.length; + att.data = data; + resolve(); + }); + }); +} + +function fetchAttachments(results, stores, opts) { + var atts = []; + results.forEach(function (row) { + if (!(row.doc && row.doc._attachments)) { + return; + } + var attNames = Object.keys(row.doc._attachments); + attNames.forEach(function (attName) { + var att = row.doc._attachments[attName]; + if (!('data' in att)) { + atts.push(att); + } + }); + }); + + return PouchPromise.all(atts.map(function (att) { + return fetchAttachment(att, stores, opts); + })); +} + +function LevelPouch$1(opts, callback) { + opts = clone(opts); + var api = this; + var instanceId; + var stores = {}; + var revLimit = opts.revs_limit; + var db; + var name = opts.name; + // TODO: this is undocumented and unused probably + /* istanbul ignore else */ + if (typeof opts.createIfMissing === 'undefined') { + opts.createIfMissing = true; + } + + var leveldown = opts.db; + + var dbStore; + var leveldownName = functionName(leveldown); + if (dbStores.has(leveldownName)) { + dbStore = dbStores.get(leveldownName); + } else { + dbStore = new _Map(); + dbStores.set(leveldownName, dbStore); + } + if (dbStore.has(name)) { + db = dbStore.get(name); + afterDBCreated(); + } else { + dbStore.set(name, sublevelPouch(levelup(name, opts, function (err) { + /* istanbul ignore if */ + if (err) { + dbStore.delete(name); + return callback(err); + } + db = dbStore.get(name); + db._docCount = -1; + db._queue = new Deque(); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationOne(name, db, afterDBCreated); + } else { + afterDBCreated(); + } + }))); + } + + function afterDBCreated() { + stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding}); + stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'}); + stores.attachmentStore = + db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'}); + stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); + stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); + stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationTwo(db, stores, afterLastMigration); + } else { + afterLastMigration(); + } + } + + function afterLastMigration() { + stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { + if (typeof db._updateSeq === 'undefined') { + db._updateSeq = value || 0; + } + stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { + db._docCount = !err ? value : 0; + stores.metaStore.get(UUID_KEY, function (err, value) { + instanceId = !err ? value : uuid(); + stores.metaStore.put(UUID_KEY, instanceId, function () { + process.nextTick(function () { + callback(null, api); + }); + }); + }); + }); + }); + } + + function countDocs(callback) { + /* istanbul ignore if */ + if (db.isClosed()) { + return callback(new Error('database is closed')); + } + return callback(null, db._docCount); // use cached value + } + + api.type = function () { + return 'leveldb'; + }; + + api._id = function (callback) { + callback(null, instanceId); + }; + + api._info = function (callback) { + var res = { + doc_count: db._docCount, + update_seq: db._updateSeq, + backend_adapter: functionName(leveldown) + }; + return process.nextTick(function () { + callback(null, res); + }); + }; + + function tryCode(fun, args) { + try { + fun.apply(null, args); + } catch (err) { + args[args.length - 1](err); + } + } + + function executeNext() { + var firstTask = db._queue.peekFront(); + + if (firstTask.type === 'read') { + runReadOperation(firstTask); + } else { // write, only do one at a time + runWriteOperation(firstTask); + } + } + + function runReadOperation(firstTask) { + // do multiple reads at once simultaneously, because it's safe + + var readTasks = [firstTask]; + var i = 1; + var nextTask = db._queue.get(i); + while (typeof nextTask !== 'undefined' && nextTask.type === 'read') { + readTasks.push(nextTask); + i++; + nextTask = db._queue.get(i); + } + + var numDone = 0; + + readTasks.forEach(function (readTask) { + var args = readTask.args; + var callback = args[args.length - 1]; + args[args.length - 1] = getArguments(function (cbArgs) { + callback.apply(null, cbArgs); + if (++numDone === readTasks.length) { + process.nextTick(function () { + // all read tasks have finished + readTasks.forEach(function () { + db._queue.shift(); + }); + if (db._queue.length) { + executeNext(); + } + }); + } + }); + tryCode(readTask.fun, args); + }); + } + + function runWriteOperation(firstTask) { + var args = firstTask.args; + var callback = args[args.length - 1]; + args[args.length - 1] = getArguments(function (cbArgs) { + callback.apply(null, cbArgs); + process.nextTick(function () { + db._queue.shift(); + if (db._queue.length) { + executeNext(); + } + }); + }); + tryCode(firstTask.fun, args); + } + + // all read/write operations to the database are done in a queue, + // similar to how websql/idb works. this avoids problems such + // as e.g. compaction needing to have a lock on the database while + // it updates stuff. in the future we can revisit this. + function writeLock(fun) { + return getArguments(function (args) { + db._queue.push({ + fun: fun, + args: args, + type: 'write' + }); + + if (db._queue.length === 1) { + process.nextTick(executeNext); + } + }); + } + + // same as the writelock, but multiple can run at once + function readLock(fun) { + return getArguments(function (args) { + db._queue.push({ + fun: fun, + args: args, + type: 'read' + }); + + if (db._queue.length === 1) { + process.nextTick(executeNext); + } + }); + } + + function formatSeq(n) { + return ('0000000000000000' + n).slice(-16); + } + + function parseSeq(s) { + return parseInt(s, 10); + } + + api._get = readLock(function (id, opts, callback) { + opts = clone(opts); + + stores.docStore.get(id, function (err, metadata) { + + if (err || !metadata) { + return callback(createError(MISSING_DOC, 'missing')); + } + + var rev = getWinningRev(metadata); + var deleted = getIsDeleted(metadata, rev); + if (deleted && !opts.rev) { + return callback(createError(MISSING_DOC, "deleted")); + } + + rev = opts.rev ? opts.rev : rev; + + var seq = metadata.rev_map[rev]; + + stores.bySeqStore.get(formatSeq(seq), function (err, doc) { + if (!doc) { + return callback(createError(MISSING_DOC)); + } + /* istanbul ignore if */ + if ('_id' in doc && doc._id !== metadata.id) { + // this failing implies something very wrong + return callback(new Error('wrong doc returned')); + } + doc._id = metadata.id; + if ('_rev' in doc) { + /* istanbul ignore if */ + if (doc._rev !== rev) { + // this failing implies something very wrong + return callback(new Error('wrong doc returned')); + } + } else { + // we didn't always store this + doc._rev = rev; + } + return callback(null, {doc: doc, metadata: metadata}); + }); + }); + }); + + // not technically part of the spec, but if putAttachment has its own + // method... + api._getAttachment = function (docId, attachId, attachment, opts, callback) { + var digest = attachment.digest; + var type = attachment.content_type; + + stores.binaryStore.get(digest, function (err, attach) { + if (err) { + /* istanbul ignore if */ + if (err.name !== 'NotFoundError') { + return callback(err); + } + // Empty attachment + return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : ''); + } + + if (opts.binary) { + callback(null, readAsBlobOrBuffer(attach, type)); + } else { + callback(null, attach.toString('base64')); + } + }); + }; + + api._bulkDocs = writeLock(function (req, opts, callback) { + var newEdits = opts.new_edits; + var results = new Array(req.docs.length); + var fetchedDocs = new _Map(); + var stemmedRevs = new _Map(); + + var txn = new LevelTransaction(); + var docCountDelta = 0; + var newUpdateSeq = db._updateSeq; + + // parse the docs and give each a sequence number + var userDocs = req.docs; + var docInfos = userDocs.map(function (doc) { + if (doc._id && isLocalId(doc._id)) { + return doc; + } + var newDoc = parseDoc(doc, newEdits); + + if (newDoc.metadata && !newDoc.metadata.rev_map) { + newDoc.metadata.rev_map = {}; + } + + return newDoc; + }); + var infoErrors = docInfos.filter(function (doc) { + return doc.error; + }); + + if (infoErrors.length) { + return callback(infoErrors[0]); + } + + // verify any stub attachments as a precondition test + + function verifyAttachment(digest, callback) { + txn.get(stores.attachmentStore, digest, function (levelErr) { + if (levelErr) { + var err = createError(MISSING_STUB, + 'unknown stub attachment with digest ' + + digest); + callback(err); + } else { + callback(); + } + }); + } + + function verifyAttachments(finish) { + var digests = []; + userDocs.forEach(function (doc) { + if (doc && doc._attachments) { + Object.keys(doc._attachments).forEach(function (filename) { + var att = doc._attachments[filename]; + if (att.stub) { + digests.push(att.digest); + } + }); + } + }); + if (!digests.length) { + return finish(); + } + var numDone = 0; + var err; + + digests.forEach(function (digest) { + verifyAttachment(digest, function (attErr) { + if (attErr && !err) { + err = attErr; + } + + if (++numDone === digests.length) { + finish(err); + } + }); + }); + } + + function fetchExistingDocs(finish) { + var numDone = 0; + var overallErr; + function checkDone() { + if (++numDone === userDocs.length) { + return finish(overallErr); + } + } + + userDocs.forEach(function (doc) { + if (doc._id && isLocalId(doc._id)) { + // skip local docs + return checkDone(); + } + txn.get(stores.docStore, doc._id, function (err, info) { + if (err) { + /* istanbul ignore if */ + if (err.name !== 'NotFoundError') { + overallErr = err; + } + } else { + fetchedDocs.set(doc._id, info); + } + checkDone(); + }); + }); + } + + function compact(revsMap, callback) { + var promise = PouchPromise.resolve(); + revsMap.forEach(function (revs, docId) { + // TODO: parallelize, for now need to be sequential to + // pass orphaned attachment tests + promise = promise.then(function () { + return new PouchPromise(function (resolve, reject) { + api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) { + /* istanbul ignore if */ + if (err) { + return reject(err); + } + resolve(); + }); + }); + }); + }); + + promise.then(function () { + callback(); + }, callback); + } + + function autoCompact(callback) { + var revsMap = new _Map(); + fetchedDocs.forEach(function (metadata, docId) { + revsMap.set(docId, compactTree(metadata)); + }); + compact(revsMap, callback); + } + + function finish() { + compact(stemmedRevs, function (error) { + /* istanbul ignore if */ + if (error) { + complete(error); + } + if (api.auto_compaction) { + return autoCompact(complete); + } + complete(); + }); + } + + function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, + isUpdate, delta, resultsIdx, callback2) { + docCountDelta += delta; + + var err = null; + var recv = 0; + + docInfo.metadata.winningRev = winningRev; + docInfo.metadata.deleted = winningRevIsDeleted; + + docInfo.data._id = docInfo.metadata.id; + docInfo.data._rev = docInfo.metadata.rev; + + if (newRevIsDeleted) { + docInfo.data._deleted = true; + } + + if (docInfo.stemmedRevs.length) { + stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs); + } + + var attachments = docInfo.data._attachments ? + Object.keys(docInfo.data._attachments) : + []; + + function attachmentSaved(attachmentErr) { + recv++; + if (!err) { + /* istanbul ignore if */ + if (attachmentErr) { + err = attachmentErr; + callback2(err); + } else if (recv === attachments.length) { + finish(); + } + } + } + + function onMD5Load(doc, key, data, attachmentSaved) { + return function (result) { + saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved); + }; + } + + function doMD5(doc, key, attachmentSaved) { + return function (data) { + binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved)); + }; + } + + for (var i = 0; i < attachments.length; i++) { + var key = attachments[i]; + var att = docInfo.data._attachments[key]; + + if (att.stub) { + // still need to update the refs mapping + var id = docInfo.data._id; + var rev = docInfo.data._rev; + saveAttachmentRefs(id, rev, att.digest, attachmentSaved); + continue; + } + var data; + if (typeof att.data === 'string') { + // input is assumed to be a base64 string + try { + data = atob(att.data); + } catch (e) { + callback(createError(BAD_ARG, + 'Attachment is not a valid base64 string')); + return; + } + doMD5(docInfo, key, attachmentSaved)(data); + } else { + prepareAttachmentForStorage(att.data, + doMD5(docInfo, key, attachmentSaved)); + } + } + + function finish() { + var seq = docInfo.metadata.rev_map[docInfo.metadata.rev]; + /* istanbul ignore if */ + if (seq) { + // check that there aren't any existing revisions with the same + // revision id, else we shouldn't do anything + return callback2(); + } + seq = ++newUpdateSeq; + docInfo.metadata.rev_map[docInfo.metadata.rev] = + docInfo.metadata.seq = seq; + var seqKey = formatSeq(seq); + var batch = [{ + key: seqKey, + value: docInfo.data, + prefix: stores.bySeqStore, + type: 'put' + }, { + key: docInfo.metadata.id, + value: docInfo.metadata, + prefix: stores.docStore, + type: 'put' + }]; + txn.batch(batch); + results[resultsIdx] = { + ok: true, + id: docInfo.metadata.id, + rev: winningRev + }; + fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); + callback2(); + } + + if (!attachments.length) { + finish(); + } + } + + // attachments are queued per-digest, otherwise the refs could be + // overwritten by concurrent writes in the same bulkDocs session + var attachmentQueues = {}; + + function saveAttachmentRefs(id, rev, digest, callback) { + + function fetchAtt() { + return new PouchPromise(function (resolve, reject) { + txn.get(stores.attachmentStore, digest, function (err, oldAtt) { + /* istanbul ignore if */ + if (err && err.name !== 'NotFoundError') { + return reject(err); + } + resolve(oldAtt); + }); + }); + } + + function saveAtt(oldAtt) { + var ref = [id, rev].join('@'); + var newAtt = {}; + + if (oldAtt) { + if (oldAtt.refs) { + // only update references if this attachment already has them + // since we cannot migrate old style attachments here without + // doing a full db scan for references + newAtt.refs = oldAtt.refs; + newAtt.refs[ref] = true; + } + } else { + newAtt.refs = {}; + newAtt.refs[ref] = true; + } + + return new PouchPromise(function (resolve) { + txn.batch([{ + type: 'put', + prefix: stores.attachmentStore, + key: digest, + value: newAtt + }]); + resolve(!oldAtt); + }); + } + + // put attachments in a per-digest queue, to avoid two docs with the same + // attachment overwriting each other + var queue = attachmentQueues[digest] || PouchPromise.resolve(); + attachmentQueues[digest] = queue.then(function () { + return fetchAtt().then(saveAtt).then(function (isNewAttachment) { + callback(null, isNewAttachment); + }, callback); + }); + } + + function saveAttachment(docInfo, digest, key, data, callback) { + var att = docInfo.data._attachments[key]; + delete att.data; + att.digest = digest; + att.length = data.length; + var id = docInfo.metadata.id; + var rev = docInfo.metadata.rev; + att.revpos = parseInt(rev, 10); + + saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + // do not try to store empty attachments + if (data.length === 0) { + return callback(err); + } + if (!isNewAttachment) { + // small optimization - don't bother writing it again + return callback(err); + } + txn.batch([{ + type: 'put', + prefix: stores.binaryStore, + key: digest, + value: new Buffer(data, 'binary') + }]); + callback(); + }); + } + + function complete(err) { + /* istanbul ignore if */ + if (err) { + return process.nextTick(function () { + callback(err); + }); + } + txn.batch([ + { + prefix: stores.metaStore, + type: 'put', + key: UPDATE_SEQ_KEY, + value: newUpdateSeq + }, + { + prefix: stores.metaStore, + type: 'put', + key: DOC_COUNT_KEY, + value: db._docCount + docCountDelta + } + ]); + txn.execute(db, function (err) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + db._docCount += docCountDelta; + db._updateSeq = newUpdateSeq; + levelChanges.notify(name); + process.nextTick(function () { + callback(null, results); + }); + }); + } + + if (!docInfos.length) { + return callback(null, []); + } + + verifyAttachments(function (err) { + if (err) { + return callback(err); + } + fetchExistingDocs(function (err) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + processDocs(revLimit, docInfos, api, fetchedDocs, txn, results, + writeDoc, opts, finish); + }); + }); + }); + api._allDocs = readLock(function (opts, callback) { + opts = clone(opts); + countDocs(function (err, docCount) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + var readstreamOpts = {}; + var skip = opts.skip || 0; + if (opts.startkey) { + readstreamOpts.gte = opts.startkey; + } + if (opts.endkey) { + readstreamOpts.lte = opts.endkey; + } + if (opts.key) { + readstreamOpts.gte = readstreamOpts.lte = opts.key; + } + if (opts.descending) { + readstreamOpts.reverse = true; + // switch start and ends + var tmp = readstreamOpts.lte; + readstreamOpts.lte = readstreamOpts.gte; + readstreamOpts.gte = tmp; + } + var limit; + if (typeof opts.limit === 'number') { + limit = opts.limit; + } + if (limit === 0 || + ('start' in readstreamOpts && 'end' in readstreamOpts && + readstreamOpts.start > readstreamOpts.end)) { + // should return 0 results when start is greater than end. + // normally level would "fix" this for us by reversing the order, + // so short-circuit instead + return callback(null, { + total_rows: docCount, + offset: opts.skip, + rows: [] + }); + } + var results = []; + var docstream = stores.docStore.readStream(readstreamOpts); + + var throughStream = obj(function (entry, _, next) { + var metadata = entry.value; + // winningRev and deleted are performance-killers, but + // in newer versions of PouchDB, they are cached on the metadata + var winningRev = getWinningRev(metadata); + var deleted = getIsDeleted(metadata, winningRev); + if (!deleted) { + if (skip-- > 0) { + next(); + return; + } else if (typeof limit === 'number' && limit-- <= 0) { + docstream.unpipe(); + docstream.destroy(); + next(); + return; + } + } else if (opts.deleted !== 'ok') { + next(); + return; + } + function allDocsInner(data) { + var doc = { + id: metadata.id, + key: metadata.id, + value: { + rev: winningRev + } + }; + if (opts.include_docs) { + doc.doc = data; + doc.doc._rev = doc.value.rev; + if (opts.conflicts) { + doc.doc._conflicts = collectConflicts(metadata); + } + for (var att in doc.doc._attachments) { + if (doc.doc._attachments.hasOwnProperty(att)) { + doc.doc._attachments[att].stub = true; + } + } + } + if (opts.inclusive_end === false && metadata.id === opts.endkey) { + return next(); + } else if (deleted) { + if (opts.deleted === 'ok') { + doc.value.deleted = true; + doc.doc = null; + } else { + /* istanbul ignore next */ + return next(); + } + } + results.push(doc); + next(); + } + if (opts.include_docs) { + var seq = metadata.rev_map[winningRev]; + stores.bySeqStore.get(formatSeq(seq), function (err, data) { + allDocsInner(data); + }); + } + else { + allDocsInner(); + } + }, function (next) { + PouchPromise.resolve().then(function () { + if (opts.include_docs && opts.attachments) { + return fetchAttachments(results, stores, opts); + } + }).then(function () { + callback(null, { + total_rows: docCount, + offset: opts.skip, + rows: results + }); + }, callback); + next(); + }).on('unpipe', function () { + throughStream.end(); + }); + + docstream.on('error', callback); + + docstream.pipe(throughStream); + }); + }); + + api._changes = function (opts) { + opts = clone(opts); + + if (opts.continuous) { + var id = name + ':' + uuid(); + levelChanges.addListener(name, id, api, opts); + levelChanges.notify(name); + return { + cancel: function () { + levelChanges.removeListener(name, id); + } + }; + } + + var descending = opts.descending; + var results = []; + var lastSeq = opts.since || 0; + var called = 0; + var streamOpts = { + reverse: descending + }; + var limit; + if ('limit' in opts && opts.limit > 0) { + limit = opts.limit; + } + if (!streamOpts.reverse) { + streamOpts.start = formatSeq(opts.since || 0); + } + + var docIds = opts.doc_ids && new _Set(opts.doc_ids); + var filter = filterChange(opts); + var docIdsToMetadata = new _Map(); + + var returnDocs; + if ('return_docs' in opts) { + returnDocs = opts.return_docs; + } else if ('returnDocs' in opts) { + // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release + returnDocs = opts.returnDocs; + } else { + returnDocs = true; + } + + function complete() { + opts.done = true; + if (returnDocs && opts.limit) { + /* istanbul ignore if */ + if (opts.limit < results.length) { + results.length = opts.limit; + } + } + changeStream.unpipe(throughStream); + changeStream.destroy(); + if (!opts.continuous && !opts.cancelled) { + if (opts.include_docs && opts.attachments) { + fetchAttachments(results, stores, opts).then(function () { + opts.complete(null, {results: results, last_seq: lastSeq}); + }); + } else { + opts.complete(null, {results: results, last_seq: lastSeq}); + } + } + } + var changeStream = stores.bySeqStore.readStream(streamOpts); + var throughStream = obj(function (data, _, next) { + if (limit && called >= limit) { + complete(); + return next(); + } + if (opts.cancelled || opts.done) { + return next(); + } + + var seq = parseSeq(data.key); + var doc = data.value; + + if (seq === opts.since && !descending) { + // couchdb ignores `since` if descending=true + return next(); + } + + if (docIds && !docIds.has(doc._id)) { + return next(); + } + + var metadata; + + function onGetMetadata(metadata) { + var winningRev = getWinningRev(metadata); + + function onGetWinningDoc(winningDoc) { + + var change = opts.processChange(winningDoc, metadata, opts); + change.seq = metadata.seq; + + var filtered = filter(change); + if (typeof filtered === 'object') { + return opts.complete(filtered); + } + + if (filtered) { + called++; + + if (opts.attachments && opts.include_docs) { + // fetch attachment immediately for the benefit + // of live listeners + fetchAttachments([change], stores, opts).then(function () { + opts.onChange(change); + }); + } else { + opts.onChange(change); + } + + if (returnDocs) { + results.push(change); + } + } + next(); + } + + if (metadata.seq !== seq) { + // some other seq is later + return next(); + } + + lastSeq = seq; + + if (winningRev === doc._rev) { + return onGetWinningDoc(doc); + } + + // fetch the winner + + var winningSeq = metadata.rev_map[winningRev]; + + stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) { + onGetWinningDoc(doc); + }); + } + + metadata = docIdsToMetadata.get(doc._id); + if (metadata) { // cached + return onGetMetadata(metadata); + } + // metadata not cached, have to go fetch it + stores.docStore.get(doc._id, function (err, metadata) { + /* istanbul ignore if */ + if (opts.cancelled || opts.done || db.isClosed() || + isLocalId(metadata.id)) { + return next(); + } + docIdsToMetadata.set(doc._id, metadata); + onGetMetadata(metadata); + }); + }, function (next) { + if (opts.cancelled) { + return next(); + } + if (returnDocs && opts.limit) { + /* istanbul ignore if */ + if (opts.limit < results.length) { + results.length = opts.limit; + } + } + + next(); + }).on('unpipe', function () { + throughStream.end(); + complete(); + }); + changeStream.pipe(throughStream); + return { + cancel: function () { + opts.cancelled = true; + complete(); + } + }; + }; + + api._close = function (callback) { + /* istanbul ignore if */ + if (db.isClosed()) { + return callback(createError(NOT_OPEN)); + } + db.close(function (err) { + /* istanbul ignore if */ + if (err) { + callback(err); + } else { + dbStore.delete(name); + callback(); + } + }); + }; + + api._getRevisionTree = function (docId, callback) { + stores.docStore.get(docId, function (err, metadata) { + if (err) { + callback(createError(MISSING_DOC)); + } else { + callback(null, metadata.rev_tree); + } + }); + }; + + api._doCompaction = writeLock(function (docId, revs, opts, callback) { + api._doCompactionNoLock(docId, revs, opts, callback); + }); + + // the NoLock version is for use by bulkDocs + api._doCompactionNoLock = function (docId, revs, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + if (!revs.length) { + return callback(); + } + var txn = opts.ctx || new LevelTransaction(); + + txn.get(stores.docStore, docId, function (err, metadata) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + var seqs = revs.map(function (rev) { + var seq = metadata.rev_map[rev]; + delete metadata.rev_map[rev]; + return seq; + }); + traverseRevTree(metadata.rev_tree, function (isLeaf, pos, + revHash, ctx, opts) { + var rev = pos + '-' + revHash; + if (revs.indexOf(rev) !== -1) { + opts.status = 'missing'; + } + }); + + var batch = []; + batch.push({ + key: metadata.id, + value: metadata, + type: 'put', + prefix: stores.docStore + }); + + var digestMap = {}; + var numDone = 0; + var overallErr; + function checkDone(err) { + /* istanbul ignore if */ + if (err) { + overallErr = err; + } + if (++numDone === revs.length) { // done + /* istanbul ignore if */ + if (overallErr) { + return callback(overallErr); + } + deleteOrphanedAttachments(); + } + } + + function finish(err) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + txn.batch(batch); + if (opts.ctx) { + // don't execute immediately + return callback(); + } + txn.execute(db, callback); + } + + function deleteOrphanedAttachments() { + var possiblyOrphanedAttachments = Object.keys(digestMap); + if (!possiblyOrphanedAttachments.length) { + return finish(); + } + var numDone = 0; + var overallErr; + function checkDone(err) { + /* istanbul ignore if */ + if (err) { + overallErr = err; + } + if (++numDone === possiblyOrphanedAttachments.length) { + finish(overallErr); + } + } + var refsToDelete = new _Map(); + revs.forEach(function (rev) { + refsToDelete.set(docId + '@' + rev, true); + }); + possiblyOrphanedAttachments.forEach(function (digest) { + txn.get(stores.attachmentStore, digest, function (err, attData) { + /* istanbul ignore if */ + if (err) { + if (err.name === 'NotFoundError') { + return checkDone(); + } else { + return checkDone(err); + } + } + var refs = Object.keys(attData.refs || {}).filter(function (ref) { + return !refsToDelete.has(ref); + }); + var newRefs = {}; + refs.forEach(function (ref) { + newRefs[ref] = true; + }); + if (refs.length) { // not orphaned + batch.push({ + key: digest, + type: 'put', + value: {refs: newRefs}, + prefix: stores.attachmentStore + }); + } else { // orphaned, can safely delete + batch = batch.concat([{ + key: digest, + type: 'del', + prefix: stores.attachmentStore + }, { + key: digest, + type: 'del', + prefix: stores.binaryStore + }]); + } + checkDone(); + }); + }); + } + + seqs.forEach(function (seq) { + batch.push({ + key: formatSeq(seq), + type: 'del', + prefix: stores.bySeqStore + }); + txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) { + /* istanbul ignore if */ + if (err) { + if (err.name === 'NotFoundError') { + return checkDone(); + } else { + return checkDone(err); + } + } + var atts = Object.keys(doc._attachments || {}); + atts.forEach(function (attName) { + var digest = doc._attachments[attName].digest; + digestMap[digest] = true; + }); + checkDone(); + }); + }); + }); + }; + + api._getLocal = function (id, callback) { + stores.localStore.get(id, function (err, doc) { + if (err) { + callback(createError(MISSING_DOC)); + } else { + callback(null, doc); + } + }); + }; + + api._putLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (opts.ctx) { + api._putLocalNoLock(doc, opts, callback); + } else { + api._putLocalWithLock(doc, opts, callback); + } + }; + + api._putLocalWithLock = writeLock(function (doc, opts, callback) { + api._putLocalNoLock(doc, opts, callback); + }); + + // the NoLock version is for use by bulkDocs + api._putLocalNoLock = function (doc, opts, callback) { + delete doc._revisions; // ignore this, trust the rev + var oldRev = doc._rev; + var id = doc._id; + + var txn = opts.ctx || new LevelTransaction(); + + txn.get(stores.localStore, id, function (err, resp) { + if (err && oldRev) { + return callback(createError(REV_CONFLICT)); + } + if (resp && resp._rev !== oldRev) { + return callback(createError(REV_CONFLICT)); + } + doc._rev = + oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1'; + var batch = [ + { + type: 'put', + prefix: stores.localStore, + key: id, + value: doc + } + ]; + + txn.batch(batch); + var ret = {ok: true, id: doc._id, rev: doc._rev}; + + if (opts.ctx) { + // don't execute immediately + return callback(null, ret); + } + txn.execute(db, function (err) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + callback(null, ret); + }); + }); + }; + + api._removeLocal = function (doc, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (opts.ctx) { + api._removeLocalNoLock(doc, opts, callback); + } else { + api._removeLocalWithLock(doc, opts, callback); + } + }; + + api._removeLocalWithLock = writeLock(function (doc, opts, callback) { + api._removeLocalNoLock(doc, opts, callback); + }); + + // the NoLock version is for use by bulkDocs + api._removeLocalNoLock = function (doc, opts, callback) { + var txn = opts.ctx || new LevelTransaction(); + txn.get(stores.localStore, doc._id, function (err, resp) { + if (err) { + /* istanbul ignore if */ + if (err.name !== 'NotFoundError') { + return callback(err); + } else { + return callback(createError(MISSING_DOC)); + } + } + if (resp._rev !== doc._rev) { + return callback(createError(REV_CONFLICT)); + } + txn.batch([{ + prefix: stores.localStore, + type: 'del', + key: doc._id + }]); + var ret = {ok: true, id: doc._id, rev: '0-0'}; + if (opts.ctx) { + // don't execute immediately + return callback(null, ret); + } + txn.execute(db, function (err) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + callback(null, ret); + }); + }); + }; + + // close and delete open leveldb stores + api._destroy = function (opts, callback) { + var dbStore; + var leveldownName = functionName(leveldown); + /* istanbul ignore else */ + if (dbStores.has(leveldownName)) { + dbStore = dbStores.get(leveldownName); + } else { + return callDestroy(name, callback); + } + + /* istanbul ignore else */ + if (dbStore.has(name)) { + levelChanges.removeAllListeners(name); + + dbStore.get(name).close(function () { + dbStore.delete(name); + callDestroy(name, callback); + }); + } else { + callDestroy(name, callback); + } + }; + function callDestroy(name, cb) { + leveldown.destroy(name, cb); + } +} + +// require leveldown. provide verbose output on error as it is the default +// nodejs adapter, which we do not provide for the user +/* istanbul ignore next */ +var requireLeveldown = function () { + try { + return require('leveldown'); + } catch (err) { + /* eslint no-ex-assign: 0*/ + err = err || 'leveldown import error'; + if (err.code === 'MODULE_NOT_FOUND') { + // handle leveldown not installed case + return new Error([ + 'the \'leveldown\' package is not available. install it, or,', + 'specify another storage backend using the \'db\' option' + ].join(' ')); + } else if (err.message && err.message.match('Module version mismatch')) { + // handle common user enviornment error + return new Error([ + err.message, + 'This generally implies that leveldown was built with a different', + 'version of node than that which is running now. You may try', + 'fully removing and reinstalling PouchDB or leveldown to resolve.' + ].join(' ')); + } + // handle general internal nodejs require error + return new Error(err.toString() + ': unable to import leveldown'); + } +}; + +var stores = [ + 'document-store', + 'by-sequence', + 'attach-store', + 'attach-binary-store' +]; +function formatSeq(n) { + return ('0000000000000000' + n).slice(-16); +} +var UPDATE_SEQ_KEY$1 = '_local_last_update_seq'; +var DOC_COUNT_KEY$1 = '_local_doc_count'; +var UUID_KEY$1 = '_local_uuid'; + +var doMigrationOne = function (name, db, callback) { + // local require to prevent crashing if leveldown isn't installed. + var leveldown = require("leveldown"); + + var base = path.resolve(name); + function move(store, index, cb) { + var storePath = path.join(base, store); + var opts; + if (index === 3) { + opts = { + valueEncoding: 'binary' + }; + } else { + opts = { + valueEncoding: 'json' + }; + } + var sub = db.sublevel(store, opts); + var orig = levelup(storePath, opts); + var from = orig.createReadStream(); + var writeStream = new LevelWriteStream(sub); + var to = writeStream(); + from.on('end', function () { + orig.close(function (err) { + cb(err, storePath); + }); + }); + from.pipe(to); + } + fs.unlink(base + '.uuid', function (err) { + if (err) { + return callback(); + } + var todo = 4; + var done = []; + stores.forEach(function (store, i) { + move(store, i, function (err, storePath) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + done.push(storePath); + if (!(--todo)) { + done.forEach(function (item) { + leveldown.destroy(item, function () { + if (++todo === done.length) { + fs.rmdir(base, callback); + } + }); + }); + } + }); + }); + }); +}; +var doMigrationTwo = function (db, stores, callback) { + var batches = []; + stores.bySeqStore.get(UUID_KEY$1, function (err, value) { + if (err) { + // no uuid key, so don't need to migrate; + return callback(); + } + batches.push({ + key: UUID_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: UUID_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + stores.bySeqStore.get(DOC_COUNT_KEY$1, function (err, value) { + if (value) { + // if no doc count key, + // just skip + // we can live with this + batches.push({ + key: DOC_COUNT_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: DOC_COUNT_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + } + stores.bySeqStore.get(UPDATE_SEQ_KEY$1, function (err, value) { + if (value) { + // if no UPDATE_SEQ_KEY + // just skip + // we've gone to far to stop. + batches.push({ + key: UPDATE_SEQ_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: UPDATE_SEQ_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + } + var deletedSeqs = {}; + stores.docStore.createReadStream({ + startKey: '_', + endKey: '_\xFF' + }).pipe(obj(function (ch, _, next) { + if (!isLocalId(ch.key)) { + return next(); + } + batches.push({ + key: ch.key, + prefix: stores.docStore, + type: 'del' + }); + var winner = winningRev(ch.value); + Object.keys(ch.value.rev_map).forEach(function (key) { + if (key !== 'winner') { + this.push(formatSeq(ch.value.rev_map[key])); + } + }, this); + var winningSeq = ch.value.rev_map[winner]; + stores.bySeqStore.get(formatSeq(winningSeq), function (err, value) { + if (!err) { + batches.push({ + key: ch.key, + value: value, + prefix: stores.localStore, + type: 'put', + valueEncoding: 'json' + }); + } + next(); + }); + + })).pipe(obj(function (seq, _, next) { + /* istanbul ignore if */ + if (deletedSeqs[seq]) { + return next(); + } + deletedSeqs[seq] = true; + stores.bySeqStore.get(seq, function (err, resp) { + /* istanbul ignore if */ + if (err || !isLocalId(resp._id)) { + return next(); + } + batches.push({ + key: seq, + prefix: stores.bySeqStore, + type: 'del' + }); + next(); + }); + }, function () { + db.batch(batches, callback); + })); + }); + }); + }); + +}; + +var migrate = { + doMigrationOne: doMigrationOne, + doMigrationTwo: doMigrationTwo +}; + +function LevelDownPouch(opts, callback) { + + // Users can pass in their own leveldown alternative here, in which case + // it overrides the default one. (This is in addition to the custom builds.) + var leveldown = opts.db; + + /* istanbul ignore else */ + if (!leveldown) { + leveldown = requireLeveldown(); + + /* istanbul ignore if */ + if (leveldown instanceof Error) { + return callback(leveldown); + } + } + + var _opts = extend({ + db: leveldown, + migrate: migrate + }, opts); + + LevelPouch$1.call(this, _opts, callback); +} + +// overrides for normal LevelDB behavior on Node +LevelDownPouch.valid = function () { + return true; +}; +LevelDownPouch.use_prefix = false; + +function LevelPouch (PouchDB) { + PouchDB.adapter('leveldb', LevelDownPouch, true); +} + +// May seem redundant, but this is to allow switching with +// request-browser.js. +var request = require('request'); + +// non-standard, but we do this to mimic blobs in the browser +function applyTypeToBuffer(buffer, resp) { + buffer.type = resp.headers['content-type']; +} + +function defaultBody() { + return new Buffer('', 'binary'); +} + +function ajaxCore(options, callback) { + + options = clone(options); + + var defaultOptions = { + method : "GET", + headers: {}, + json: true, + processData: true, + timeout: 10000, + cache: false + }; + + options = extend(defaultOptions, options); + + function onSuccess(obj, resp, cb) { + if (!options.binary && options.json && typeof obj === 'string') { + /* istanbul ignore next */ + try { + obj = JSON.parse(obj); + } catch (e) { + // Probably a malformed JSON from server + return cb(e); + } + } + if (Array.isArray(obj)) { + obj = obj.map(function (v) { + if (v.error || v.missing) { + return generateErrorFromResponse(v); + } else { + return v; + } + }); + } + if (options.binary) { + applyTypeToBuffer(obj, resp); + } + cb(null, obj, resp); + } + + if (options.json) { + if (!options.binary) { + options.headers.Accept = 'application/json'; + } + options.headers['Content-Type'] = options.headers['Content-Type'] || + 'application/json'; + } + + if (options.binary) { + options.encoding = null; + options.json = false; + } + + if (!options.processData) { + options.json = false; + } + + return request(options, function (err, response, body) { + + if (err) { + return callback(generateErrorFromResponse(err)); + } + + var error; + var content_type = response.headers && response.headers['content-type']; + var data = body || defaultBody(); + + // CouchDB doesn't always return the right content-type for JSON data, so + // we check for ^{ and }$ (ignoring leading/trailing whitespace) + if (!options.binary && (options.json || !options.processData) && + typeof data !== 'object' && + (/json/.test(content_type) || + (/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) { + try { + data = JSON.parse(data.toString()); + } catch (e) {} + } + + if (response.statusCode >= 200 && response.statusCode < 300) { + onSuccess(data, response, callback); + } else { + error = generateErrorFromResponse(data); + error.status = response.statusCode; + callback(error); + } + }); +} + +function ajax(opts, callback) { + // do nothing; all the action is in prerequest-browser.js + return ajaxCore(opts, callback); +} + +var CHANGES_BATCH_SIZE = 25; +var MAX_SIMULTANEOUS_REVS = 50; + +var supportsBulkGetMap = {}; + +var log$1 = debug('pouchdb:http'); + +function readAttachmentsAsBlobOrBuffer(row) { + var atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function (filename) { + var att = atts[filename]; + att.data = b64ToBluffer(att.data, att.content_type); + }); +} + +function encodeDocId(id) { + if (/^_design/.test(id)) { + return '_design/' + encodeURIComponent(id.slice(8)); + } + if (/^_local/.test(id)) { + return '_local/' + encodeURIComponent(id.slice(7)); + } + return encodeURIComponent(id); +} + +function preprocessAttachments$1(doc) { + if (!doc._attachments || !Object.keys(doc._attachments)) { + return PouchPromise.resolve(); + } + + return PouchPromise.all(Object.keys(doc._attachments).map(function (key) { + var attachment = doc._attachments[key]; + if (attachment.data && typeof attachment.data !== 'string') { + return new PouchPromise(function (resolve) { + blobToBase64(attachment.data, resolve); + }).then(function (b64) { + attachment.data = b64; + }); + } + })); +} + +function hasUrlPrefix(opts) { + if (!opts.prefix) { + return false; + } + + var protocol = parseUri(opts.prefix).protocol; + + return protocol === 'http' || protocol === 'https'; +} + +// Get all the information you possibly can about the URI given by name and +// return it as a suitable object. +function getHost(name, opts) { + + // encode db name if opts.prefix is a url (#5574) + if (hasUrlPrefix(opts)) { + var dbName = opts.name.substr(opts.prefix.length); + name = opts.prefix + encodeURIComponent(dbName); + } + + // Prase the URI into all its little bits + var uri = parseUri(name); + + // Store the user and password as a separate auth object + if (uri.user || uri.password) { + uri.auth = {username: uri.user, password: uri.password}; + } + + // Split the path part of the URI into parts using '/' as the delimiter + // after removing any leading '/' and any trailing '/' + var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/'); + + // Store the first part as the database name and remove it from the parts + // array + uri.db = parts.pop(); + // Prevent double encoding of URI component + if (uri.db.indexOf('%') === -1) { + uri.db = encodeURIComponent(uri.db); + } + + // Restore the path by joining all the remaining parts (all the parts + // except for the database name) with '/'s + uri.path = parts.join('/'); + + return uri; +} + +// Generate a URL with the host data given by opts and the given path +function genDBUrl(opts, path) { + return genUrl(opts, opts.db + '/' + path); +} + +// Generate a URL with the host data given by opts and the given path +function genUrl(opts, path) { + // If the host already has a path, then we need to have a path delimiter + // Otherwise, the path delimiter is the empty string + var pathDel = !opts.path ? '' : '/'; + + // If the host already has a path, then we need to have a path delimiter + // Otherwise, the path delimiter is the empty string + return opts.protocol + '://' + opts.host + + (opts.port ? (':' + opts.port) : '') + + '/' + opts.path + pathDel + path; +} + +function paramsToStr(params) { + return '?' + Object.keys(params).map(function (k) { + return k + '=' + encodeURIComponent(params[k]); + }).join('&'); +} + +// Implements the PouchDB API for dealing with CouchDB instances over HTTP +function HttpPouch(opts, callback) { + + // The functions that will be publicly available for HttpPouch + var api = this; + + var host = getHost(opts.name, opts); + var dbUrl = genDBUrl(host, ''); + + opts = clone(opts); + var ajaxOpts = opts.ajax || {}; + + if (opts.auth || host.auth) { + var nAuth = opts.auth || host.auth; + var str = nAuth.username + ':' + nAuth.password; + var token = btoa(unescape(encodeURIComponent(str))); + ajaxOpts.headers = ajaxOpts.headers || {}; + ajaxOpts.headers.Authorization = 'Basic ' + token; + } + + // Not strictly necessary, but we do this because numerous tests + // rely on swapping ajax in and out. + api._ajax = ajax; + + function ajax$$(userOpts, options, callback) { + var reqAjax = userOpts.ajax || {}; + var reqOpts = extend(clone(ajaxOpts), reqAjax, options); + log$1(reqOpts.method + ' ' + reqOpts.url); + return api._ajax(reqOpts, callback); + } + + function ajaxPromise(userOpts, opts) { + return new PouchPromise(function (resolve, reject) { + ajax$$(userOpts, opts, function (err, res$$) { + /* istanbul ignore if */ + if (err) { + return reject(err); + } + resolve(res$$); + }); + }); + } + + function adapterFun$$(name, fun) { + return adapterFun(name, getArguments(function (args) { + setup().then(function () { + return fun.apply(this, args); + }).catch(function (e) { + var callback = args.pop(); + callback(e); + }); + })); + } + + var setupPromise; + + function setup() { + // TODO: Remove `skipSetup` in favor of `skip_setup` in a future release + if (opts.skipSetup || opts.skip_setup) { + return PouchPromise.resolve(); + } + + // If there is a setup in process or previous successful setup + // done then we will use that + // If previous setups have been rejected we will try again + if (setupPromise) { + return setupPromise; + } + + var checkExists = {method: 'GET', url: dbUrl}; + setupPromise = ajaxPromise({}, checkExists).catch(function (err) { + if (err && err.status && err.status === 404) { + // Doesnt exist, create it + res(404, 'PouchDB is just detecting if the remote exists.'); + return ajaxPromise({}, {method: 'PUT', url: dbUrl}); + } else { + return PouchPromise.reject(err); + } + }).catch(function (err) { + // If we try to create a database that already exists, skipped in + // istanbul since its catching a race condition. + /* istanbul ignore if */ + if (err && err.status && err.status === 412) { + return true; + } + return PouchPromise.reject(err); + }); + + setupPromise.catch(function () { + setupPromise = null; + }); + + return setupPromise; + } + + setTimeout(function () { + callback(null, api); + }); + + api.type = function () { + return 'http'; + }; + + api.id = adapterFun$$('id', function (callback) { + ajax$$({}, {method: 'GET', url: genUrl(host, '')}, function (err, result) { + var uuid = (result && result.uuid) ? + (result.uuid + host.db) : genDBUrl(host, ''); + callback(null, uuid); + }); + }); + + api.request = adapterFun$$('request', function (options, callback) { + options.url = genDBUrl(host, options.url); + ajax$$({}, options, callback); + }); + + // Sends a POST request to the host calling the couchdb _compact function + // version: The version of CouchDB it is running + api.compact = adapterFun$$('compact', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + ajax$$(opts, { + url: genDBUrl(host, '_compact'), + method: 'POST' + }, function () { + function ping() { + api.info(function (err, res$$) { + if (res$$ && !res$$.compact_running) { + callback(null, {ok: true}); + } else { + setTimeout(ping, opts.interval || 200); + } + }); + } + // Ping the http if it's finished compaction + ping(); + }); + }); + + api.bulkGet = adapterFun('bulkGet', function (opts, callback) { + var self = this; + + function doBulkGet(cb) { + var params = {}; + if (opts.revs) { + params.revs = true; + } + if (opts.attachments) { + /* istanbul ignore next */ + params.attachments = true; + } + ajax$$({}, { + url: genDBUrl(host, '_bulk_get' + paramsToStr(params)), + method: 'POST', + body: { docs: opts.docs} + }, cb); + } + + function doBulkGetShim() { + // avoid "url too long error" by splitting up into multiple requests + var batchSize = MAX_SIMULTANEOUS_REVS; + var numBatches = Math.ceil(opts.docs.length / batchSize); + var numDone = 0; + var results = new Array(numBatches); + + function onResult(batchNum) { + return function (err, res$$) { + // err is impossible because shim returns a list of errs in that case + results[batchNum] = res$$.results; + if (++numDone === numBatches) { + callback(null, {results: flatten(results)}); + } + }; + } + + for (var i = 0; i < numBatches; i++) { + var subOpts = pick(opts, ['revs', 'attachments']); + subOpts.ajax = ajaxOpts; + subOpts.docs = opts.docs.slice(i * batchSize, + Math.min(opts.docs.length, (i + 1) * batchSize)); + bulkGet(self, subOpts, onResult(i)); + } + } + + // mark the whole database as either supporting or not supporting _bulk_get + var dbUrl = genUrl(host, ''); + var supportsBulkGet = supportsBulkGetMap[dbUrl]; + + if (typeof supportsBulkGet !== 'boolean') { + // check if this database supports _bulk_get + doBulkGet(function (err, res$$) { + /* istanbul ignore else */ + if (err) { + var status = Math.floor(err.status / 100); + /* istanbul ignore else */ + if (status === 4 || status === 5) { // 40x or 50x + supportsBulkGetMap[dbUrl] = false; + res( + err.status, + 'PouchDB is just detecting if the remote ' + + 'supports the _bulk_get API.' + ); + doBulkGetShim(); + } else { + callback(err); + } + } else { + supportsBulkGetMap[dbUrl] = true; + callback(null, res$$); + } + }); + } else if (supportsBulkGet) { + /* istanbul ignore next */ + doBulkGet(callback); + } else { + doBulkGetShim(); + } + }); + + // Calls GET on the host, which gets back a JSON string containing + // couchdb: A welcome string + // version: The version of CouchDB it is running + api._info = function (callback) { + setup().then(function () { + ajax$$({}, { + method: 'GET', + url: genDBUrl(host, '') + }, function (err, res$$) { + /* istanbul ignore next */ + if (err) { + return callback(err); + } + res$$.host = genDBUrl(host, ''); + callback(null, res$$); + }); + }).catch(callback); + }; + + // Get the document with the given id from the database given by host. + // The id could be solely the _id in the database, or it may be a + // _design/ID or _local/ID path + api.get = adapterFun$$('get', function (id, opts, callback) { + // If no options were given, set the callback to the second parameter + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + + // List of parameters to add to the GET request + var params = {}; + + if (opts.revs) { + params.revs = true; + } + + if (opts.revs_info) { + params.revs_info = true; + } + + if (opts.open_revs) { + if (opts.open_revs !== "all") { + opts.open_revs = JSON.stringify(opts.open_revs); + } + params.open_revs = opts.open_revs; + } + + if (opts.rev) { + params.rev = opts.rev; + } + + if (opts.conflicts) { + params.conflicts = opts.conflicts; + } + + id = encodeDocId(id); + + // Set the options for the ajax call + var options = { + method: 'GET', + url: genDBUrl(host, id + paramsToStr(params)) + }; + + function fetchAttachments(doc) { + var atts = doc._attachments; + var filenames = atts && Object.keys(atts); + if (!atts || !filenames.length) { + return; + } + // we fetch these manually in separate XHRs, because + // Sync Gateway would normally send it back as multipart/mixed, + // which we cannot parse. Also, this is more efficient than + // receiving attachments as base64-encoded strings. + function fetch() { + + if (!filenames.length) { + return null; + } + + var filename = filenames.pop(); + var att = atts[filename]; + var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) + + '?rev=' + doc._rev; + return ajaxPromise(opts, { + method: 'GET', + url: genDBUrl(host, path), + binary: true + }).then(function (blob) { + if (opts.binary) { + return blob; + } + return new PouchPromise(function (resolve) { + blobToBase64(blob, resolve); + }); + }).then(function (data) { + delete att.stub; + delete att.length; + att.data = data; + }); + } + + // This limits the number of parallel xhr requests to 5 any time + // to avoid issues with maximum browser request limits + return new PromisePool(fetch, 5, {promise: PouchPromise}).start(); + } + + function fetchAllAttachments(docOrDocs) { + if (Array.isArray(docOrDocs)) { + return PouchPromise.all(docOrDocs.map(function (doc) { + if (doc.ok) { + return fetchAttachments(doc.ok); + } + })); + } + return fetchAttachments(docOrDocs); + } + + ajaxPromise(opts, options).then(function (res$$) { + return PouchPromise.resolve().then(function () { + if (opts.attachments) { + return fetchAllAttachments(res$$); + } + }).then(function () { + callback(null, res$$); + }); + }).catch(callback); + }); + + // Delete the document given by doc from the database given by host. + api.remove = adapterFun$$('remove', + function (docOrId, optsOrRev, opts, callback) { + var doc; + if (typeof optsOrRev === 'string') { + // id, rev, opts, callback style + doc = { + _id: docOrId, + _rev: optsOrRev + }; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + } else { + // doc, opts, callback style + doc = docOrId; + if (typeof optsOrRev === 'function') { + callback = optsOrRev; + opts = {}; + } else { + callback = opts; + opts = optsOrRev; + } + } + + var rev = (doc._rev || opts.rev); + + // Delete the document + ajax$$(opts, { + method: 'DELETE', + url: genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev + }, callback); + }); + + function encodeAttachmentId(attachmentId) { + return attachmentId.split("/").map(encodeURIComponent).join("/"); + } + + // Get the attachment + api.getAttachment = + adapterFun$$('getAttachment', function (docId, attachmentId, opts, + callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + var params = opts.rev ? ('?rev=' + opts.rev) : ''; + var url = genDBUrl(host, encodeDocId(docId)) + '/' + + encodeAttachmentId(attachmentId) + params; + ajax$$(opts, { + method: 'GET', + url: url, + binary: true + }, callback); + }); + + // Remove the attachment given by the id and rev + api.removeAttachment = + adapterFun$$('removeAttachment', function (docId, attachmentId, rev, + callback) { + + var url = genDBUrl(host, encodeDocId(docId) + '/' + + encodeAttachmentId(attachmentId)) + '?rev=' + rev; + + ajax$$({}, { + method: 'DELETE', + url: url + }, callback); + }); + + // Add the attachment given by blob and its contentType property + // to the document with the given id, the revision given by rev, and + // add it to the database given by host. + api.putAttachment = + adapterFun$$('putAttachment', function (docId, attachmentId, rev, blob, + type, callback) { + if (typeof type === 'function') { + callback = type; + type = blob; + blob = rev; + rev = null; + } + var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId); + var url = genDBUrl(host, id); + if (rev) { + url += '?rev=' + rev; + } + + if (typeof blob === 'string') { + // input is assumed to be a base64 string + var binary; + try { + binary = atob(blob); + } catch (err) { + return callback(createError(BAD_ARG, + 'Attachment is not a valid base64 string')); + } + blob = binary ? binStringToBluffer(binary, type) : ''; + } + + var opts = { + headers: {'Content-Type': type}, + method: 'PUT', + url: url, + processData: false, + body: blob, + timeout: ajaxOpts.timeout || 60000 + }; + // Add the attachment + ajax$$({}, opts, callback); + }); + + // Update/create multiple documents given by req in the database + // given by host. + api._bulkDocs = function (req, opts, callback) { + // If new_edits=false then it prevents the database from creating + // new revision numbers for the documents. Instead it just uses + // the old ones. This is used in database replication. + req.new_edits = opts.new_edits; + + setup().then(function () { + return PouchPromise.all(req.docs.map(preprocessAttachments$1)); + }).then(function () { + // Update/create the documents + ajax$$(opts, { + method: 'POST', + url: genDBUrl(host, '_bulk_docs'), + timeout: opts.timeout, + body: req + }, function (err, results) { + if (err) { + return callback(err); + } + results.forEach(function (result) { + result.ok = true; // smooths out cloudant not adding this + }); + callback(null, results); + }); + }).catch(callback); + }; + + + // Update/create document + api._put = function (doc, opts, callback) { + setup().then(function () { + return preprocessAttachments$1(doc); + }).then(function () { + // Update/create the document + ajax$$(opts, { + method: 'PUT', + url: genDBUrl(host, encodeDocId(doc._id)), + body: doc + }, function (err, result) { + if (err) { + return callback(err); + } + callback(null, result); + }); + }).catch(callback); + }; + + + // Get a listing of the documents in the database given + // by host and ordered by increasing id. + api.allDocs = adapterFun$$('allDocs', function (opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = clone(opts); + + // List of parameters to add to the GET request + var params = {}; + var body; + var method = 'GET'; + + if (opts.conflicts) { + params.conflicts = true; + } + + if (opts.descending) { + params.descending = true; + } + + if (opts.include_docs) { + params.include_docs = true; + } + + // added in CouchDB 1.6.0 + if (opts.attachments) { + params.attachments = true; + } + + if (opts.key) { + params.key = JSON.stringify(opts.key); + } + + if (opts.start_key) { + opts.startkey = opts.start_key; + } + + if (opts.startkey) { + params.startkey = JSON.stringify(opts.startkey); + } + + if (opts.end_key) { + opts.endkey = opts.end_key; + } + + if (opts.endkey) { + params.endkey = JSON.stringify(opts.endkey); + } + + if (typeof opts.inclusive_end !== 'undefined') { + params.inclusive_end = !!opts.inclusive_end; + } + + if (typeof opts.limit !== 'undefined') { + params.limit = opts.limit; + } + + if (typeof opts.skip !== 'undefined') { + params.skip = opts.skip; + } + + var paramStr = paramsToStr(params); + + if (typeof opts.keys !== 'undefined') { + method = 'POST'; + body = {keys: opts.keys}; + } + + // Get the document listing + ajaxPromise(opts, { + method: method, + url: genDBUrl(host, '_all_docs' + paramStr), + body: body + }).then(function (res$$) { + if (opts.include_docs && opts.attachments && opts.binary) { + res$$.rows.forEach(readAttachmentsAsBlobOrBuffer); + } + callback(null, res$$); + }).catch(callback); + }); + + // Get a list of changes made to documents in the database given by host. + // TODO According to the README, there should be two other methods here, + // api.changes.addListener and api.changes.removeListener. + api._changes = function (opts) { + + // We internally page the results of a changes request, this means + // if there is a large set of changes to be returned we can start + // processing them quicker instead of waiting on the entire + // set of changes to return and attempting to process them at once + var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE; + + opts = clone(opts); + opts.timeout = ('timeout' in opts) ? opts.timeout : + ('timeout' in ajaxOpts) ? ajaxOpts.timeout : + 30 * 1000; + + // We give a 5 second buffer for CouchDB changes to respond with + // an ok timeout (if a timeout it set) + var params = opts.timeout ? {timeout: opts.timeout - (5 * 1000)} : {}; + var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false; + var returnDocs; + if ('return_docs' in opts) { + returnDocs = opts.return_docs; + } else if ('returnDocs' in opts) { + // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release + returnDocs = opts.returnDocs; + } else { + returnDocs = true; + } + // + var leftToFetch = limit; + + if (opts.style) { + params.style = opts.style; + } + + if (opts.include_docs || opts.filter && typeof opts.filter === 'function') { + params.include_docs = true; + } + + if (opts.attachments) { + params.attachments = true; + } + + if (opts.continuous) { + params.feed = 'longpoll'; + } + + if (opts.conflicts) { + params.conflicts = true; + } + + if (opts.descending) { + params.descending = true; + } + + if ('heartbeat' in opts) { + // If the heartbeat value is false, it disables the default heartbeat + if (opts.heartbeat) { + params.heartbeat = opts.heartbeat; + } + } else { + // Default heartbeat to 10 seconds + params.heartbeat = 10000; + } + + if (opts.filter && typeof opts.filter === 'string') { + params.filter = opts.filter; + } + + if (opts.view && typeof opts.view === 'string') { + params.filter = '_view'; + params.view = opts.view; + } + + // If opts.query_params exists, pass it through to the changes request. + // These parameters may be used by the filter on the source database. + if (opts.query_params && typeof opts.query_params === 'object') { + for (var param_name in opts.query_params) { + /* istanbul ignore else */ + if (opts.query_params.hasOwnProperty(param_name)) { + params[param_name] = opts.query_params[param_name]; + } + } + } + + var method = 'GET'; + var body; + + if (opts.doc_ids) { + // set this automagically for the user; it's annoying that couchdb + // requires both a "filter" and a "doc_ids" param. + params.filter = '_doc_ids'; + method = 'POST'; + body = {doc_ids: opts.doc_ids }; + } + + var xhr; + var lastFetchedSeq; + + // Get all the changes starting wtih the one immediately after the + // sequence number given by since. + var fetch = function (since, callback) { + if (opts.aborted) { + return; + } + params.since = since; + // "since" can be any kind of json object in Coudant/CouchDB 2.x + /* istanbul ignore next */ + if (typeof params.since === "object") { + params.since = JSON.stringify(params.since); + } + + if (opts.descending) { + if (limit) { + params.limit = leftToFetch; + } + } else { + params.limit = (!limit || leftToFetch > batchSize) ? + batchSize : leftToFetch; + } + + // Set the options for the ajax call + var xhrOpts = { + method: method, + url: genDBUrl(host, '_changes' + paramsToStr(params)), + timeout: opts.timeout, + body: body + }; + lastFetchedSeq = since; + + /* istanbul ignore if */ + if (opts.aborted) { + return; + } + + // Get the changes + setup().then(function () { + xhr = ajax$$(opts, xhrOpts, callback); + }).catch(callback); + }; + + // If opts.since exists, get all the changes from the sequence + // number given by opts.since. Otherwise, get all the changes + // from the sequence number 0. + var results = {results: []}; + + var fetched = function (err, res$$) { + if (opts.aborted) { + return; + } + var raw_results_length = 0; + // If the result of the ajax call (res) contains changes (res.results) + if (res$$ && res$$.results) { + raw_results_length = res$$.results.length; + results.last_seq = res$$.last_seq; + // For each change + var req = {}; + req.query = opts.query_params; + res$$.results = res$$.results.filter(function (c) { + leftToFetch--; + var ret = filterChange(opts)(c); + if (ret) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer(c); + } + if (returnDocs) { + results.results.push(c); + } + opts.onChange(c); + } + return ret; + }); + } else if (err) { + // In case of an error, stop listening for changes and call + // opts.complete + opts.aborted = true; + opts.complete(err); + return; + } + + // The changes feed may have timed out with no results + // if so reuse last update sequence + if (res$$ && res$$.last_seq) { + lastFetchedSeq = res$$.last_seq; + } + + var finished = (limit && leftToFetch <= 0) || + (res$$ && raw_results_length < batchSize) || + (opts.descending); + + if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) { + // Queue a call to fetch again with the newest sequence number + setTimeout(function () { fetch(lastFetchedSeq, fetched); }, 0); + } else { + // We're done, call the callback + opts.complete(null, results); + } + }; + + fetch(opts.since || 0, fetched); + + // Return a method to cancel this method from processing any more + return { + cancel: function () { + opts.aborted = true; + if (xhr) { + xhr.abort(); + } + } + }; + }; + + // Given a set of document/revision IDs (given by req), tets the subset of + // those that do NOT correspond to revisions stored in the database. + // See http://wiki.apache.org/couchdb/HttpPostRevsDiff + api.revsDiff = adapterFun$$('revsDiff', function (req, opts, callback) { + // If no options were given, set the callback to be the second parameter + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + + // Get the missing document/revision IDs + ajax$$(opts, { + method: 'POST', + url: genDBUrl(host, '_revs_diff'), + body: req + }, callback); + }); + + api._close = function (callback) { + callback(); + }; + + api._destroy = function (options, callback) { + ajax$$(options, { + url: genDBUrl(host, ''), + method: 'DELETE' + }, function (err, resp) { + if (err && err.status && err.status !== 404) { + return callback(err); + } + callback(null, resp); + }); + }; +} + +// HttpPouch is a valid adapter. +HttpPouch.valid = function () { + return true; +}; + +function HttpPouch$1 (PouchDB) { + PouchDB.adapter('http', HttpPouch, false); + PouchDB.adapter('https', HttpPouch, false); +} + +function pad(str, padWith, upToLength) { + var padding = ''; + var targetLength = upToLength - str.length; + /* istanbul ignore next */ + while (padding.length < targetLength) { + padding += padWith; + } + return padding; +} + +function padLeft(str, padWith, upToLength) { + var padding = pad(str, padWith, upToLength); + return padding + str; +} + +var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE +var MAGNITUDE_DIGITS = 3; // ditto +var SEP = ''; // set to '_' for easier debugging + +function collate(a, b) { + + if (a === b) { + return 0; + } + + a = normalizeKey(a); + b = normalizeKey(b); + + var ai = collationIndex(a); + var bi = collationIndex(b); + if ((ai - bi) !== 0) { + return ai - bi; + } + if (a === null) { + return 0; + } + switch (typeof a) { + case 'number': + return a - b; + case 'boolean': + return a === b ? 0 : (a < b ? -1 : 1); + case 'string': + return stringCollate(a, b); + } + return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b); +} + +// couch considers null/NaN/Infinity/-Infinity === undefined, +// for the purposes of mapreduce indexes. also, dates get stringified. +function normalizeKey(key) { + switch (typeof key) { + case 'undefined': + return null; + case 'number': + if (key === Infinity || key === -Infinity || isNaN(key)) { + return null; + } + return key; + case 'object': + var origKey = key; + if (Array.isArray(key)) { + var len = key.length; + key = new Array(len); + for (var i = 0; i < len; i++) { + key[i] = normalizeKey(origKey[i]); + } + /* istanbul ignore next */ + } else if (key instanceof Date) { + return key.toJSON(); + } else if (key !== null) { // generic object + key = {}; + for (var k in origKey) { + if (origKey.hasOwnProperty(k)) { + var val = origKey[k]; + if (typeof val !== 'undefined') { + key[k] = normalizeKey(val); + } + } + } + } + } + return key; +} + +function indexify(key) { + if (key !== null) { + switch (typeof key) { + case 'boolean': + return key ? 1 : 0; + case 'number': + return numToIndexableString(key); + case 'string': + // We've to be sure that key does not contain \u0000 + // Do order-preserving replacements: + // 0 -> 1, 1 + // 1 -> 1, 2 + // 2 -> 2, 2 + return key + .replace(/\u0002/g, '\u0002\u0002') + .replace(/\u0001/g, '\u0001\u0002') + .replace(/\u0000/g, '\u0001\u0001'); + case 'object': + var isArray = Array.isArray(key); + var arr = isArray ? key : Object.keys(key); + var i = -1; + var len = arr.length; + var result = ''; + if (isArray) { + while (++i < len) { + result += toIndexableString(arr[i]); + } + } else { + while (++i < len) { + var objKey = arr[i]; + result += toIndexableString(objKey) + + toIndexableString(key[objKey]); + } + } + return result; + } + } + return ''; +} + +// convert the given key to a string that would be appropriate +// for lexical sorting, e.g. within a database, where the +// sorting is the same given by the collate() function. +function toIndexableString(key) { + var zero = '\u0000'; + key = normalizeKey(key); + return collationIndex(key) + SEP + indexify(key) + zero; +} + +function parseNumber(str, i) { + var originalIdx = i; + var num; + var zero = str[i] === '1'; + if (zero) { + num = 0; + i++; + } else { + var neg = str[i] === '0'; + i++; + var numAsString = ''; + var magAsString = str.substring(i, i + MAGNITUDE_DIGITS); + var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE; + /* istanbul ignore next */ + if (neg) { + magnitude = -magnitude; + } + i += MAGNITUDE_DIGITS; + while (true) { + var ch = str[i]; + if (ch === '\u0000') { + break; + } else { + numAsString += ch; + } + i++; + } + numAsString = numAsString.split('.'); + if (numAsString.length === 1) { + num = parseInt(numAsString, 10); + } else { + /* istanbul ignore next */ + num = parseFloat(numAsString[0] + '.' + numAsString[1]); + } + /* istanbul ignore next */ + if (neg) { + num = num - 10; + } + /* istanbul ignore next */ + if (magnitude !== 0) { + // parseFloat is more reliable than pow due to rounding errors + // e.g. Number.MAX_VALUE would return Infinity if we did + // num * Math.pow(10, magnitude); + num = parseFloat(num + 'e' + magnitude); + } + } + return {num: num, length : i - originalIdx}; +} + +// move up the stack while parsing +// this function moved outside of parseIndexableString for performance +function pop(stack, metaStack) { + var obj = stack.pop(); + + if (metaStack.length) { + var lastMetaElement = metaStack[metaStack.length - 1]; + if (obj === lastMetaElement.element) { + // popping a meta-element, e.g. an object whose value is another object + metaStack.pop(); + lastMetaElement = metaStack[metaStack.length - 1]; + } + var element = lastMetaElement.element; + var lastElementIndex = lastMetaElement.index; + if (Array.isArray(element)) { + element.push(obj); + } else if (lastElementIndex === stack.length - 2) { // obj with key+value + var key = stack.pop(); + element[key] = obj; + } else { + stack.push(obj); // obj with key only + } + } +} + +function parseIndexableString(str) { + var stack = []; + var metaStack = []; // stack for arrays and objects + var i = 0; + + /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ + while (true) { + var collationIndex = str[i++]; + if (collationIndex === '\u0000') { + if (stack.length === 1) { + return stack.pop(); + } else { + pop(stack, metaStack); + continue; + } + } + switch (collationIndex) { + case '1': + stack.push(null); + break; + case '2': + stack.push(str[i] === '1'); + i++; + break; + case '3': + var parsedNum = parseNumber(str, i); + stack.push(parsedNum.num); + i += parsedNum.length; + break; + case '4': + var parsedStr = ''; + /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ + while (true) { + var ch = str[i]; + if (ch === '\u0000') { + break; + } + parsedStr += ch; + i++; + } + // perform the reverse of the order-preserving replacement + // algorithm (see above) + parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000') + .replace(/\u0001\u0002/g, '\u0001') + .replace(/\u0002\u0002/g, '\u0002'); + stack.push(parsedStr); + break; + case '5': + var arrayElement = { element: [], index: stack.length }; + stack.push(arrayElement.element); + metaStack.push(arrayElement); + break; + case '6': + var objElement = { element: {}, index: stack.length }; + stack.push(objElement.element); + metaStack.push(objElement); + break; + /* istanbul ignore next */ + default: + throw new Error( + 'bad collationIndex or unexpectedly reached end of input: ' + + collationIndex); + } + } +} + +function arrayCollate(a, b) { + var len = Math.min(a.length, b.length); + for (var i = 0; i < len; i++) { + var sort = collate(a[i], b[i]); + if (sort !== 0) { + return sort; + } + } + return (a.length === b.length) ? 0 : + (a.length > b.length) ? 1 : -1; +} +function stringCollate(a, b) { + // See: https://github.com/daleharvey/pouchdb/issues/40 + // This is incompatible with the CouchDB implementation, but its the + // best we can do for now + return (a === b) ? 0 : ((a > b) ? 1 : -1); +} +function objectCollate(a, b) { + var ak = Object.keys(a), bk = Object.keys(b); + var len = Math.min(ak.length, bk.length); + for (var i = 0; i < len; i++) { + // First sort the keys + var sort = collate(ak[i], bk[i]); + if (sort !== 0) { + return sort; + } + // if the keys are equal sort the values + sort = collate(a[ak[i]], b[bk[i]]); + if (sort !== 0) { + return sort; + } + + } + return (ak.length === bk.length) ? 0 : + (ak.length > bk.length) ? 1 : -1; +} +// The collation is defined by erlangs ordered terms +// the atoms null, true, false come first, then numbers, strings, +// arrays, then objects +// null/undefined/NaN/Infinity/-Infinity are all considered null +function collationIndex(x) { + var id = ['boolean', 'number', 'string', 'object']; + var idx = id.indexOf(typeof x); + //false if -1 otherwise true, but fast!!!!1 + if (~idx) { + if (x === null) { + return 1; + } + if (Array.isArray(x)) { + return 5; + } + return idx < 3 ? (idx + 2) : (idx + 3); + } + /* istanbul ignore next */ + if (Array.isArray(x)) { + return 5; + } +} + +// conversion: +// x yyy zz...zz +// x = 0 for negative, 1 for 0, 2 for positive +// y = exponent (for negative numbers negated) moved so that it's >= 0 +// z = mantisse +function numToIndexableString(num) { + + if (num === 0) { + return '1'; + } + + // convert number to exponential format for easier and + // more succinct string sorting + var expFormat = num.toExponential().split(/e\+?/); + var magnitude = parseInt(expFormat[1], 10); + + var neg = num < 0; + + var result = neg ? '0' : '2'; + + // first sort by magnitude + // it's easier if all magnitudes are positive + var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE); + var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS); + + result += SEP + magString; + + // then sort by the factor + var factor = Math.abs(parseFloat(expFormat[0])); // [1..10) + /* istanbul ignore next */ + if (neg) { // for negative reverse ordering + factor = 10 - factor; + } + + var factorStr = factor.toFixed(20); + + // strip zeros from the end + factorStr = factorStr.replace(/\.?0+$/, ''); + + result += SEP + factorStr; + + return result; +} + +/* + * Simple task queue to sequentialize actions. Assumes + * callbacks will eventually fire (once). + */ + +function TaskQueue$1() { + this.promise = new PouchPromise(function (fulfill) {fulfill(); }); +} +TaskQueue$1.prototype.add = function (promiseFactory) { + this.promise = this.promise.catch(function () { + // just recover + }).then(function () { + return promiseFactory(); + }); + return this.promise; +}; +TaskQueue$1.prototype.finish = function () { + return this.promise; +}; + +function createView(opts) { + var sourceDB = opts.db; + var viewName = opts.viewName; + var mapFun = opts.map; + var reduceFun = opts.reduce; + var temporary = opts.temporary; + + // the "undefined" part is for backwards compatibility + var viewSignature = mapFun.toString() + (reduceFun && reduceFun.toString()) + + 'undefined'; + + var cachedViews; + if (!temporary) { + // cache this to ensure we don't try to update the same view twice + cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {}; + if (cachedViews[viewSignature]) { + return cachedViews[viewSignature]; + } + } + + var promiseForView = sourceDB.info().then(function (info) { + + var depDbName = info.db_name + '-mrview-' + + (temporary ? 'temp' : stringMd5(viewSignature)); + + // save the view name in the source db so it can be cleaned up if necessary + // (e.g. when the _design doc is deleted, remove all associated view data) + function diffFunction(doc) { + doc.views = doc.views || {}; + var fullViewName = viewName; + if (fullViewName.indexOf('/') === -1) { + fullViewName = viewName + '/' + viewName; + } + var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {}; + /* istanbul ignore if */ + if (depDbs[depDbName]) { + return; // no update necessary + } + depDbs[depDbName] = true; + return doc; + } + return upsert(sourceDB, '_local/mrviews', diffFunction).then(function () { + return sourceDB.registerDependentDatabase(depDbName).then(function (res) { + var db = res.db; + db.auto_compaction = true; + var view = { + name: depDbName, + db: db, + sourceDB: sourceDB, + adapter: sourceDB.adapter, + mapFun: mapFun, + reduceFun: reduceFun + }; + return view.db.get('_local/lastSeq').catch(function (err) { + /* istanbul ignore if */ + if (err.status !== 404) { + throw err; + } + }).then(function (lastSeqDoc) { + view.seq = lastSeqDoc ? lastSeqDoc.seq : 0; + if (cachedViews) { + view.db.once('destroyed', function () { + delete cachedViews[viewSignature]; + }); + } + return view; + }); + }); + }); + }); + + if (cachedViews) { + cachedViews[viewSignature] = promiseForView; + } + return promiseForView; +} + +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} + +inherits(QueryParseError, Error); + +function NotFoundError$1(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError$1); + } catch (e) {} +} + +inherits(NotFoundError$1, Error); + +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} + +inherits(BuiltInError, Error); + +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} + +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} + +// Inside of 'vm' for Node, we need a way to translate a pseudo-error +// back into a real error once it's out of the VM. +function createBuiltInErrorInVm(name) { + return { + builtInError: true, + name: name + }; +} + +function convertToTrueError(err) { + return createBuiltInError(err.name); +} + +function isBuiltInError(obj) { + return obj && obj.builtInError; +} + +// All of this vm hullaballoo is to be able to run arbitrary code in a sandbox +// for security reasons. +function evalFunctionInVm(func, emit) { + return function (arg1, arg2, arg3) { + var code = '(function() {"use strict";' + + 'var createBuiltInError = ' + createBuiltInErrorInVm.toString() + ';' + + 'var sum = ' + sum.toString() + ';' + + 'var log = function () {};' + + 'var isArray = Array.isArray;' + + 'var toJSON = JSON.parse;' + + 'var __emitteds__ = [];' + + 'var emit = function (key, value) {__emitteds__.push([key, value]);};' + + 'var __result__ = (' + + func.replace(/;\s*$/, '') + ')' + '(' + + JSON.stringify(arg1) + ',' + + JSON.stringify(arg2) + ',' + + JSON.stringify(arg3) + ');' + + 'return {result: __result__, emitteds: __emitteds__};' + + '})()'; + + var output = vm.runInNewContext(code); + + output.emitteds.forEach(function (emitted) { + emit(emitted[0], emitted[1]); + }); + if (isBuiltInError(output.result)) { + output.result = convertToTrueError(output.result); + } + return output.result; + }; +} + +var log$2 = guardedConsole.bind(null, 'log'); + +// The "stringify, then execute in a VM" strategy totally breaks Istanbul due +// to missing __coverage global objects. As a solution, export different +// code during coverage testing and during regular execution. +// Note that this doesn't get shipped to consumers because Rollup replaces it +// with rollup-plugin-replace, so false is replaced with `false` +var evalFunc; +/* istanbul ignore else */ +if (false) {} else { + evalFunc = evalFunctionInVm; +} + +var evalFunction = evalFunc; + +var promisedCallback = function (promise, callback) { + if (callback) { + promise.then(function (res) { + process.nextTick(function () { + callback(null, res); + }); + }, function (reason) { + process.nextTick(function () { + callback(reason); + }); + }); + } + return promise; +}; + +var callbackify = function (fun) { + return getArguments(function (args) { + var cb = args.pop(); + var promise = fun.apply(this, args); + if (typeof cb === 'function') { + promisedCallback(promise, cb); + } + return promise; + }); +}; + +// Promise finally util similar to Q.finally +var fin = function (promise, finalPromiseFactory) { + return promise.then(function (res) { + return finalPromiseFactory().then(function () { + return res; + }); + }, function (reason) { + return finalPromiseFactory().then(function () { + throw reason; + }); + }); +}; + +var sequentialize = function (queue, promiseFactory) { + return function () { + var args = arguments; + var that = this; + return queue.add(function () { + return promiseFactory.apply(that, args); + }); + }; +}; + +// uniq an array of strings, order not guaranteed +// similar to underscore/lodash _.uniq +var uniq = function (arr) { + var map = {}; + + for (var i = 0, len = arr.length; i < len; i++) { + map['$' + arr[i]] = true; + } + + var keys = Object.keys(map); + var output = new Array(keys.length); + + for (i = 0, len = keys.length; i < len; i++) { + output[i] = keys[i].substring(1); + } + return output; +}; + +var persistentQueues = {}; +var tempViewQueue = new TaskQueue$1(); +var CHANGES_BATCH_SIZE$1 = 50; + +function parseViewName(name) { + // can be either 'ddocname/viewname' or just 'viewname' + // (where the ddoc name is the same) + return name.indexOf('/') === -1 ? [name, name] : name.split('/'); +} + +function isGenOne(changes) { + // only return true if the current change is 1- + // and there are no other leafs + return changes.length === 1 && /^1-/.test(changes[0].rev); +} + +function emitError(db, e) { + try { + db.emit('error', e); + } catch (err) { + guardedConsole('error', + 'The user\'s map/reduce function threw an uncaught error.\n' + + 'You can debug this error by doing:\n' + + 'myDatabase.on(\'error\', function (err) { debugger; });\n' + + 'Please double-check your map/reduce function.'); + guardedConsole('error', e); + } +} + +function tryCode(db, fun, args) { + // emit an event if there was an error thrown by a map/reduce function. + // putting try/catches in a single function also avoids deoptimizations. + try { + return { + output : fun.apply(null, args) + }; + } catch (e) { + emitError(db, e); + return {error: e}; + } +} + +function sortByKeyThenValue(x, y) { + var keyCompare = collate(x.key, y.key); + return keyCompare !== 0 ? keyCompare : collate(x.value, y.value); +} + +function sliceResults(results, limit, skip) { + skip = skip || 0; + if (typeof limit === 'number') { + return results.slice(skip, limit + skip); + } else if (skip > 0) { + return results.slice(skip); + } + return results; +} + +function rowToDocId(row) { + var val = row.value; + // Users can explicitly specify a joined doc _id, or it + // defaults to the doc _id that emitted the key/value. + var docId = (val && typeof val === 'object' && val._id) || row.id; + return docId; +} + +function readAttachmentsAsBlobOrBuffer$1(res) { + res.rows.forEach(function (row) { + var atts = row.doc && row.doc._attachments; + if (!atts) { + return; + } + Object.keys(atts).forEach(function (filename) { + var att = atts[filename]; + atts[filename].data = b64ToBluffer(att.data, att.content_type); + }); + }); +} + +function postprocessAttachments(opts) { + return function (res) { + if (opts.include_docs && opts.attachments && opts.binary) { + readAttachmentsAsBlobOrBuffer$1(res); + } + return res; + }; +} + +var builtInReduce = { + _sum: function (keys, values) { + return sum(values); + }, + + _count: function (keys, values) { + return values.length; + }, + + _stats: function (keys, values) { + // no need to implement rereduce=true, because Pouch + // will never call it + function sumsqr(values) { + var _sumsqr = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + _sumsqr += (num * num); + } + return _sumsqr; + } + return { + sum : sum(values), + min : Math.min.apply(null, values), + max : Math.max.apply(null, values), + count : values.length, + sumsqr : sumsqr(values) + }; + } +}; + +function addHttpParam(paramName, opts, params, asJson) { + // add an http param from opts to params, optionally json-encoded + var val = opts[paramName]; + if (typeof val !== 'undefined') { + if (asJson) { + val = encodeURIComponent(JSON.stringify(val)); + } + params.push(paramName + '=' + val); + } +} + +function coerceInteger(integerCandidate) { + if (typeof integerCandidate !== 'undefined') { + var asNumber = Number(integerCandidate); + // prevents e.g. '1foo' or '1.1' being coerced to 1 + if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) { + return asNumber; + } else { + return integerCandidate; + } + } +} + +function coerceOptions(opts) { + opts.group_level = coerceInteger(opts.group_level); + opts.limit = coerceInteger(opts.limit); + opts.skip = coerceInteger(opts.skip); + return opts; +} + +function checkPositiveInteger(number) { + if (number) { + if (typeof number !== 'number') { + return new QueryParseError('Invalid value for integer: "' + + number + '"'); + } + if (number < 0) { + return new QueryParseError('Invalid value for positive integer: ' + + '"' + number + '"'); + } + } +} + +function checkQueryParseError(options, fun) { + var startkeyName = options.descending ? 'endkey' : 'startkey'; + var endkeyName = options.descending ? 'startkey' : 'endkey'; + + if (typeof options[startkeyName] !== 'undefined' && + typeof options[endkeyName] !== 'undefined' && + collate(options[startkeyName], options[endkeyName]) > 0) { + throw new QueryParseError('No rows can match your key range, ' + + 'reverse your start_key and end_key or set {descending : true}'); + } else if (fun.reduce && options.reduce !== false) { + if (options.include_docs) { + throw new QueryParseError('{include_docs:true} is invalid for reduce'); + } else if (options.keys && options.keys.length > 1 && + !options.group && !options.group_level) { + throw new QueryParseError('Multi-key fetches for reduce views must use ' + + '{group: true}'); + } + } + ['group_level', 'limit', 'skip'].forEach(function (optionName) { + var error = checkPositiveInteger(options[optionName]); + if (error) { + throw error; + } + }); +} + +function httpQuery(db, fun, opts) { + // List of parameters to add to the PUT request + var params = []; + var body; + var method = 'GET'; + + // If opts.reduce exists and is defined, then add it to the list + // of parameters. + // If reduce=false then the results are that of only the map function + // not the final result of map and reduce. + addHttpParam('reduce', opts, params); + addHttpParam('include_docs', opts, params); + addHttpParam('attachments', opts, params); + addHttpParam('limit', opts, params); + addHttpParam('descending', opts, params); + addHttpParam('group', opts, params); + addHttpParam('group_level', opts, params); + addHttpParam('skip', opts, params); + addHttpParam('stale', opts, params); + addHttpParam('conflicts', opts, params); + addHttpParam('startkey', opts, params, true); + addHttpParam('start_key', opts, params, true); + addHttpParam('endkey', opts, params, true); + addHttpParam('end_key', opts, params, true); + addHttpParam('inclusive_end', opts, params); + addHttpParam('key', opts, params, true); + + // Format the list of parameters into a valid URI query string + params = params.join('&'); + params = params === '' ? '' : '?' + params; + + // If keys are supplied, issue a POST to circumvent GET query string limits + // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options + if (typeof opts.keys !== 'undefined') { + var MAX_URL_LENGTH = 2000; + // according to http://stackoverflow.com/a/417184/680742, + // the de facto URL length limit is 2000 characters + + var keysAsString = + 'keys=' + encodeURIComponent(JSON.stringify(opts.keys)); + if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) { + // If the keys are short enough, do a GET. we do this to work around + // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239) + params += (params[0] === '?' ? '&' : '?') + keysAsString; + } else { + method = 'POST'; + if (typeof fun === 'string') { + body = {keys: opts.keys}; + } else { // fun is {map : mapfun}, so append to this + fun.keys = opts.keys; + } + } + } + + // We are referencing a query defined in the design doc + if (typeof fun === 'string') { + var parts = parseViewName(fun); + return db.request({ + method: method, + url: '_design/' + parts[0] + '/_view/' + parts[1] + params, + body: body + }).then(postprocessAttachments(opts)); + } + + // We are using a temporary view, terrible for performance, good for testing + body = body || {}; + Object.keys(fun).forEach(function (key) { + if (Array.isArray(fun[key])) { + body[key] = fun[key]; + } else { + body[key] = fun[key].toString(); + } + }); + return db.request({ + method: 'POST', + url: '_temp_view' + params, + body: body + }).then(postprocessAttachments(opts)); +} + +// custom adapters can define their own api._query +// and override the default behavior +/* istanbul ignore next */ +function customQuery(db, fun, opts) { + return new PouchPromise(function (resolve, reject) { + db._query(fun, opts, function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} + +// custom adapters can define their own api._viewCleanup +// and override the default behavior +/* istanbul ignore next */ +function customViewCleanup(db) { + return new PouchPromise(function (resolve, reject) { + db._viewCleanup(function (err, res) { + if (err) { + return reject(err); + } + resolve(res); + }); + }); +} + +function defaultsTo(value) { + return function (reason) { + /* istanbul ignore else */ + if (reason.status === 404) { + return value; + } else { + throw reason; + } + }; +} + +// returns a promise for a list of docs to update, based on the input docId. +// the order doesn't matter, because post-3.2.0, bulkDocs +// is an atomic operation in all three adapters. +function getDocsToPersist(docId, view, docIdsToChangesAndEmits) { + var metaDocId = '_local/doc_' + docId; + var defaultMetaDoc = {_id: metaDocId, keys: []}; + var docData = docIdsToChangesAndEmits[docId]; + var indexableKeysToKeyValues = docData.indexableKeysToKeyValues; + var changes = docData.changes; + + function getMetaDoc() { + if (isGenOne(changes)) { + // generation 1, so we can safely assume initial state + // for performance reasons (avoids unnecessary GETs) + return PouchPromise.resolve(defaultMetaDoc); + } + return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc)); + } + + function getKeyValueDocs(metaDoc) { + if (!metaDoc.keys.length) { + // no keys, no need for a lookup + return PouchPromise.resolve({rows: []}); + } + return view.db.allDocs({ + keys: metaDoc.keys, + include_docs: true + }); + } + + function processKvDocs(metaDoc, kvDocsRes) { + var kvDocs = []; + var oldKeysMap = {}; + + for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) { + var row = kvDocsRes.rows[i]; + var doc = row.doc; + if (!doc) { // deleted + continue; + } + kvDocs.push(doc); + oldKeysMap[doc._id] = true; + doc._deleted = !indexableKeysToKeyValues[doc._id]; + if (!doc._deleted) { + var keyValue = indexableKeysToKeyValues[doc._id]; + if ('value' in keyValue) { + doc.value = keyValue.value; + } + } + } + + var newKeys = Object.keys(indexableKeysToKeyValues); + newKeys.forEach(function (key) { + if (!oldKeysMap[key]) { + // new doc + var kvDoc = { + _id: key + }; + var keyValue = indexableKeysToKeyValues[key]; + if ('value' in keyValue) { + kvDoc.value = keyValue.value; + } + kvDocs.push(kvDoc); + } + }); + metaDoc.keys = uniq(newKeys.concat(metaDoc.keys)); + kvDocs.push(metaDoc); + + return kvDocs; + } + + return getMetaDoc().then(function (metaDoc) { + return getKeyValueDocs(metaDoc).then(function (kvDocsRes) { + return processKvDocs(metaDoc, kvDocsRes); + }); + }); +} + +// updates all emitted key/value docs and metaDocs in the mrview database +// for the given batch of documents from the source database +function saveKeyValues(view, docIdsToChangesAndEmits, seq) { + var seqDocId = '_local/lastSeq'; + return view.db.get(seqDocId) + .catch(defaultsTo({_id: seqDocId, seq: 0})) + .then(function (lastSeqDoc) { + var docIds = Object.keys(docIdsToChangesAndEmits); + return PouchPromise.all(docIds.map(function (docId) { + return getDocsToPersist(docId, view, docIdsToChangesAndEmits); + })).then(function (listOfDocsToPersist) { + var docsToPersist = flatten(listOfDocsToPersist); + lastSeqDoc.seq = seq; + docsToPersist.push(lastSeqDoc); + // write all docs in a single operation, update the seq once + return view.db.bulkDocs({docs : docsToPersist}); + }); + }); +} + +function getQueue(view) { + var viewName = typeof view === 'string' ? view : view.name; + var queue = persistentQueues[viewName]; + if (!queue) { + queue = persistentQueues[viewName] = new TaskQueue$1(); + } + return queue; +} + +function updateView(view) { + return sequentialize(getQueue(view), function () { + return updateViewInQueue(view); + })(); +} + +function updateViewInQueue(view) { + // bind the emit function once + var mapResults; + var doc; + + function emit(key, value) { + var output = {id: doc._id, key: normalizeKey(key)}; + // Don't explicitly store the value unless it's defined and non-null. + // This saves on storage space, because often people don't use it. + if (typeof value !== 'undefined' && value !== null) { + output.value = normalizeKey(value); + } + mapResults.push(output); + } + + var mapFun; + // for temp_views one can use emit(doc, emit), see #38 + if (typeof view.mapFun === "function" && view.mapFun.length === 2) { + var origMap = view.mapFun; + mapFun = function (doc) { + return origMap(doc, emit); + }; + } else { + mapFun = evalFunction(view.mapFun.toString(), emit); + } + + var currentSeq = view.seq || 0; + + function processChange(docIdsToChangesAndEmits, seq) { + return function () { + return saveKeyValues(view, docIdsToChangesAndEmits, seq); + }; + } + + var queue = new TaskQueue$1(); + // TODO(neojski): https://github.com/daleharvey/pouchdb/issues/1521 + + return new PouchPromise(function (resolve, reject) { + + function complete() { + queue.finish().then(function () { + view.seq = currentSeq; + resolve(); + }); + } + + function processNextBatch() { + view.sourceDB.changes({ + conflicts: true, + include_docs: true, + style: 'all_docs', + since: currentSeq, + limit: CHANGES_BATCH_SIZE$1 + }).on('complete', function (response) { + var results = response.results; + if (!results.length) { + return complete(); + } + var docIdsToChangesAndEmits = {}; + for (var i = 0, l = results.length; i < l; i++) { + var change = results[i]; + if (change.doc._id[0] !== '_') { + mapResults = []; + doc = change.doc; + + if (!doc._deleted) { + tryCode(view.sourceDB, mapFun, [doc]); + } + mapResults.sort(sortByKeyThenValue); + + var indexableKeysToKeyValues = {}; + var lastKey; + for (var j = 0, jl = mapResults.length; j < jl; j++) { + var obj = mapResults[j]; + var complexKey = [obj.key, obj.id]; + if (collate(obj.key, lastKey) === 0) { + complexKey.push(j); // dup key+id, so make it unique + } + var indexableKey = toIndexableString(complexKey); + indexableKeysToKeyValues[indexableKey] = obj; + lastKey = obj.key; + } + docIdsToChangesAndEmits[change.doc._id] = { + indexableKeysToKeyValues: indexableKeysToKeyValues, + changes: change.changes + }; + } + currentSeq = change.seq; + } + queue.add(processChange(docIdsToChangesAndEmits, currentSeq)); + if (results.length < CHANGES_BATCH_SIZE$1) { + return complete(); + } + return processNextBatch(); + }).on('error', onError); + /* istanbul ignore next */ + function onError(err) { + reject(err); + } + } + + processNextBatch(); + }); +} + +function reduceView(view, results, options) { + if (options.group_level === 0) { + delete options.group_level; + } + + var shouldGroup = options.group || options.group_level; + + var reduceFun; + if (builtInReduce[view.reduceFun]) { + reduceFun = builtInReduce[view.reduceFun]; + } else { + reduceFun = evalFunction(view.reduceFun.toString()); + } + + var groups = []; + var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY : + options.group_level; + results.forEach(function (e) { + var last = groups[groups.length - 1]; + var groupKey = shouldGroup ? e.key : null; + + // only set group_level for array keys + if (shouldGroup && Array.isArray(groupKey)) { + groupKey = groupKey.slice(0, lvl); + } + + if (last && collate(last.groupKey, groupKey) === 0) { + last.keys.push([e.key, e.id]); + last.values.push(e.value); + return; + } + groups.push({ + keys: [[e.key, e.id]], + values: [e.value], + groupKey: groupKey + }); + }); + results = []; + for (var i = 0, len = groups.length; i < len; i++) { + var e = groups[i]; + var reduceTry = tryCode(view.sourceDB, reduceFun, + [e.keys, e.values, false]); + if (reduceTry.error && reduceTry.error instanceof BuiltInError) { + // CouchDB returns an error if a built-in errors out + throw reduceTry.error; + } + results.push({ + // CouchDB just sets the value to null if a non-built-in errors out + value: reduceTry.error ? null : reduceTry.output, + key: e.groupKey + }); + } + // no total_rows/offset when reducing + return {rows: sliceResults(results, options.limit, options.skip)}; +} + +function queryView(view, opts) { + return sequentialize(getQueue(view), function () { + return queryViewInQueue(view, opts); + })(); +} + +function queryViewInQueue(view, opts) { + var totalRows; + var shouldReduce = view.reduceFun && opts.reduce !== false; + var skip = opts.skip || 0; + if (typeof opts.keys !== 'undefined' && !opts.keys.length) { + // equivalent query + opts.limit = 0; + delete opts.keys; + } + + function fetchFromView(viewOpts) { + viewOpts.include_docs = true; + return view.db.allDocs(viewOpts).then(function (res) { + totalRows = res.total_rows; + return res.rows.map(function (result) { + + // implicit migration - in older versions of PouchDB, + // we explicitly stored the doc as {id: ..., key: ..., value: ...} + // this is tested in a migration test + /* istanbul ignore next */ + if ('value' in result.doc && typeof result.doc.value === 'object' && + result.doc.value !== null) { + var keys = Object.keys(result.doc.value).sort(); + // this detection method is not perfect, but it's unlikely the user + // emitted a value which was an object with these 3 exact keys + var expectedKeys = ['id', 'key', 'value']; + if (!(keys < expectedKeys || keys > expectedKeys)) { + return result.doc.value; + } + } + + var parsedKeyAndDocId = parseIndexableString(result.doc._id); + return { + key: parsedKeyAndDocId[0], + id: parsedKeyAndDocId[1], + value: ('value' in result.doc ? result.doc.value : null) + }; + }); + }); + } + + function onMapResultsReady(rows) { + var finalResults; + if (shouldReduce) { + finalResults = reduceView(view, rows, opts); + } else { + finalResults = { + total_rows: totalRows, + offset: skip, + rows: rows + }; + } + if (opts.include_docs) { + var docIds = uniq(rows.map(rowToDocId)); + + return view.sourceDB.allDocs({ + keys: docIds, + include_docs: true, + conflicts: opts.conflicts, + attachments: opts.attachments, + binary: opts.binary + }).then(function (allDocsRes) { + var docIdsToDocs = {}; + allDocsRes.rows.forEach(function (row) { + if (row.doc) { + docIdsToDocs['$' + row.id] = row.doc; + } + }); + rows.forEach(function (row) { + var docId = rowToDocId(row); + var doc = docIdsToDocs['$' + docId]; + if (doc) { + row.doc = doc; + } + }); + return finalResults; + }); + } else { + return finalResults; + } + } + + if (typeof opts.keys !== 'undefined') { + var keys = opts.keys; + var fetchPromises = keys.map(function (key) { + var viewOpts = { + startkey : toIndexableString([key]), + endkey : toIndexableString([key, {}]) + }; + return fetchFromView(viewOpts); + }); + return PouchPromise.all(fetchPromises).then(flatten).then(onMapResultsReady); + } else { // normal query, no 'keys' + var viewOpts = { + descending : opts.descending + }; + if (opts.start_key) { + opts.startkey = opts.start_key; + } + if (opts.end_key) { + opts.endkey = opts.end_key; + } + if (typeof opts.startkey !== 'undefined') { + viewOpts.startkey = opts.descending ? + toIndexableString([opts.startkey, {}]) : + toIndexableString([opts.startkey]); + } + if (typeof opts.endkey !== 'undefined') { + var inclusiveEnd = opts.inclusive_end !== false; + if (opts.descending) { + inclusiveEnd = !inclusiveEnd; + } + + viewOpts.endkey = toIndexableString( + inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]); + } + if (typeof opts.key !== 'undefined') { + var keyStart = toIndexableString([opts.key]); + var keyEnd = toIndexableString([opts.key, {}]); + if (viewOpts.descending) { + viewOpts.endkey = keyStart; + viewOpts.startkey = keyEnd; + } else { + viewOpts.startkey = keyStart; + viewOpts.endkey = keyEnd; + } + } + if (!shouldReduce) { + if (typeof opts.limit === 'number') { + viewOpts.limit = opts.limit; + } + viewOpts.skip = skip; + } + return fetchFromView(viewOpts).then(onMapResultsReady); + } +} + +function httpViewCleanup(db) { + return db.request({ + method: 'POST', + url: '_view_cleanup' + }); +} + +function localViewCleanup(db) { + return db.get('_local/mrviews').then(function (metaDoc) { + var docsToViews = {}; + Object.keys(metaDoc.views).forEach(function (fullViewName) { + var parts = parseViewName(fullViewName); + var designDocName = '_design/' + parts[0]; + var viewName = parts[1]; + docsToViews[designDocName] = docsToViews[designDocName] || {}; + docsToViews[designDocName][viewName] = true; + }); + var opts = { + keys : Object.keys(docsToViews), + include_docs : true + }; + return db.allDocs(opts).then(function (res) { + var viewsToStatus = {}; + res.rows.forEach(function (row) { + var ddocName = row.key.substring(8); + Object.keys(docsToViews[row.key]).forEach(function (viewName) { + var fullViewName = ddocName + '/' + viewName; + /* istanbul ignore if */ + if (!metaDoc.views[fullViewName]) { + // new format, without slashes, to support PouchDB 2.2.0 + // migration test in pouchdb's browser.migration.js verifies this + fullViewName = viewName; + } + var viewDBNames = Object.keys(metaDoc.views[fullViewName]); + // design doc deleted, or view function nonexistent + var statusIsGood = row.doc && row.doc.views && + row.doc.views[viewName]; + viewDBNames.forEach(function (viewDBName) { + viewsToStatus[viewDBName] = + viewsToStatus[viewDBName] || statusIsGood; + }); + }); + }); + var dbsToDelete = Object.keys(viewsToStatus).filter( + function (viewDBName) { return !viewsToStatus[viewDBName]; }); + var destroyPromises = dbsToDelete.map(function (viewDBName) { + return sequentialize(getQueue(viewDBName), function () { + return new db.constructor(viewDBName, db.__opts).destroy(); + })(); + }); + return PouchPromise.all(destroyPromises).then(function () { + return {ok: true}; + }); + }); + }, defaultsTo({ok: true})); +} + +var viewCleanup = callbackify(function () { + var db = this; + if (db.type() === 'http') { + return httpViewCleanup(db); + } + /* istanbul ignore next */ + if (typeof db._viewCleanup === 'function') { + return customViewCleanup(db); + } + return localViewCleanup(db); +}); + +function queryPromised(db, fun, opts) { + if (db.type() === 'http') { + return httpQuery(db, fun, opts); + } + + /* istanbul ignore next */ + if (typeof db._query === 'function') { + return customQuery(db, fun, opts); + } + + if (typeof fun !== 'string') { + // temp_view + checkQueryParseError(opts, fun); + + var createViewOpts = { + db : db, + viewName : 'temp_view/temp_view', + map : fun.map, + reduce : fun.reduce, + temporary : true + }; + tempViewQueue.add(function () { + return createView(createViewOpts).then(function (view) { + function cleanup() { + return view.db.destroy(); + } + return fin(updateView(view).then(function () { + return queryView(view, opts); + }), cleanup); + }); + }); + return tempViewQueue.finish(); + } else { + // persistent view + var fullViewName = fun; + var parts = parseViewName(fullViewName); + var designDocName = parts[0]; + var viewName = parts[1]; + return db.get('_design/' + designDocName).then(function (doc) { + var fun = doc.views && doc.views[viewName]; + + if (!fun || typeof fun.map !== 'string') { + throw new NotFoundError$1('ddoc ' + designDocName + + ' has no view named ' + viewName); + } + checkQueryParseError(opts, fun); + + var createViewOpts = { + db : db, + viewName : fullViewName, + map : fun.map, + reduce : fun.reduce + }; + return createView(createViewOpts).then(function (view) { + if (opts.stale === 'ok' || opts.stale === 'update_after') { + if (opts.stale === 'update_after') { + process.nextTick(function () { + updateView(view); + }); + } + return queryView(view, opts); + } else { // stale not ok + return updateView(view).then(function () { + return queryView(view, opts); + }); + } + }); + }); + } +} + +var query = function (fun, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts ? coerceOptions(opts) : {}; + + if (typeof fun === 'function') { + fun = {map : fun}; + } + + var db = this; + var promise = PouchPromise.resolve().then(function () { + return queryPromised(db, fun, opts); + }); + promisedCallback(promise, callback); + return promise; +}; + + +var mapreduce = { + query: query, + viewCleanup: viewCleanup +}; + +function isGenOne$1(rev) { + return /^1-/.test(rev); +} + +function fileHasChanged(localDoc, remoteDoc, filename) { + return !localDoc._attachments || + !localDoc._attachments[filename] || + localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest; +} + +function getDocAttachments(db, doc) { + var filenames = Object.keys(doc._attachments); + return PouchPromise.all(filenames.map(function (filename) { + return db.getAttachment(doc._id, filename, {rev: doc._rev}); + })); +} + +function getDocAttachmentsFromTargetOrSource(target, src, doc) { + var doCheckForLocalAttachments = src.type() === 'http' && target.type() !== 'http'; + var filenames = Object.keys(doc._attachments); + + if (!doCheckForLocalAttachments) { + return getDocAttachments(src, doc); + } + + return target.get(doc._id).then(function (localDoc) { + return PouchPromise.all(filenames.map(function (filename) { + if (fileHasChanged(localDoc, doc, filename)) { + return src.getAttachment(doc._id, filename); + } + + return target.getAttachment(localDoc._id, filename); + })); + }).catch(function (error) { + /* istanbul ignore if */ + if (error.status !== 404) { + throw error; + } + + return getDocAttachments(src, doc); + }); +} + +function createBulkGetOpts(diffs) { + var requests = []; + Object.keys(diffs).forEach(function (id) { + var missingRevs = diffs[id].missing; + missingRevs.forEach(function (missingRev) { + requests.push({ + id: id, + rev: missingRev + }); + }); + }); + + return { + docs: requests, + revs: true + }; +} + +// +// Fetch all the documents from the src as described in the "diffs", +// which is a mapping of docs IDs to revisions. If the state ever +// changes to "cancelled", then the returned promise will be rejected. +// Else it will be resolved with a list of fetched documents. +// +function getDocs(src, target, diffs, state) { + diffs = clone(diffs); // we do not need to modify this + + var resultDocs = [], + ok = true; + + function getAllDocs() { + + var bulkGetOpts = createBulkGetOpts(diffs); + + if (!bulkGetOpts.docs.length) { // optimization: skip empty requests + return; + } + + return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) { + /* istanbul ignore if */ + if (state.cancelled) { + throw new Error('cancelled'); + } + return PouchPromise.all(bulkGetResponse.results.map(function (bulkGetInfo) { + return PouchPromise.all(bulkGetInfo.docs.map(function (doc) { + var remoteDoc = doc.ok; + + if (doc.error) { + // when AUTO_COMPACTION is set, docs can be returned which look + // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"} + ok = false; + } + + if (!remoteDoc || !remoteDoc._attachments) { + return remoteDoc; + } + + return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc).then(function (attachments) { + var filenames = Object.keys(remoteDoc._attachments); + attachments.forEach(function (attachment, i) { + var att = remoteDoc._attachments[filenames[i]]; + delete att.stub; + delete att.length; + att.data = attachment; + }); + + return remoteDoc; + }); + })); + })) + + .then(function (results) { + resultDocs = resultDocs.concat(flatten(results).filter(Boolean)); + }); + }); + } + + function hasAttachments(doc) { + return doc._attachments && Object.keys(doc._attachments).length > 0; + } + + function fetchRevisionOneDocs(ids) { + // Optimization: fetch gen-1 docs and attachments in + // a single request using _all_docs + return src.allDocs({ + keys: ids, + include_docs: true + }).then(function (res) { + if (state.cancelled) { + throw new Error('cancelled'); + } + res.rows.forEach(function (row) { + if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) || + hasAttachments(row.doc)) { + // if any of these conditions apply, we need to fetch using get() + return; + } + + // the doc we got back from allDocs() is sufficient + resultDocs.push(row.doc); + delete diffs[row.id]; + }); + }); + } + + function getRevisionOneDocs() { + // filter out the generation 1 docs and get them + // leaving the non-generation one docs to be got otherwise + var ids = Object.keys(diffs).filter(function (id) { + var missing = diffs[id].missing; + return missing.length === 1 && isGenOne$1(missing[0]); + }); + if (ids.length > 0) { + return fetchRevisionOneDocs(ids); + } + } + + function returnResult() { + return { ok:ok, docs:resultDocs }; + } + + return PouchPromise.resolve() + .then(getRevisionOneDocs) + .then(getAllDocs) + .then(returnResult); +} + +var CHECKPOINT_VERSION = 1; +var REPLICATOR = "pouchdb"; +// This is an arbitrary number to limit the +// amount of replication history we save in the checkpoint. +// If we save too much, the checkpoing docs will become very big, +// if we save fewer, we'll run a greater risk of having to +// read all the changes from 0 when checkpoint PUTs fail +// CouchDB 2.0 has a more involved history pruning, +// but let's go for the simple version for now. +var CHECKPOINT_HISTORY_SIZE = 5; +var LOWEST_SEQ = 0; + +function updateCheckpoint(db, id, checkpoint, session, returnValue) { + return db.get(id).catch(function (err) { + if (err.status === 404) { + if (db.type() === 'http') { + res( + 404, 'PouchDB is just checking if a remote checkpoint exists.' + ); + } + return { + session_id: session, + _id: id, + history: [], + replicator: REPLICATOR, + version: CHECKPOINT_VERSION + }; + } + throw err; + }).then(function (doc) { + if (returnValue.cancelled) { + return; + } + + // if the checkpoint has not changed, do not update + if (doc.last_seq === checkpoint) { + return; + } + + // Filter out current entry for this replication + doc.history = (doc.history || []).filter(function (item) { + return item.session_id !== session; + }); + + // Add the latest checkpoint to history + doc.history.unshift({ + last_seq: checkpoint, + session_id: session + }); + + // Just take the last pieces in history, to + // avoid really big checkpoint docs. + // see comment on history size above + doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE); + + doc.version = CHECKPOINT_VERSION; + doc.replicator = REPLICATOR; + + doc.session_id = session; + doc.last_seq = checkpoint; + + return db.put(doc).catch(function (err) { + if (err.status === 409) { + // retry; someone is trying to write a checkpoint simultaneously + return updateCheckpoint(db, id, checkpoint, session, returnValue); + } + throw err; + }); + }); +} + +function Checkpointer(src, target, id, returnValue) { + this.src = src; + this.target = target; + this.id = id; + this.returnValue = returnValue; +} + +Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) { + var self = this; + return this.updateTarget(checkpoint, session).then(function () { + return self.updateSource(checkpoint, session); + }); +}; + +Checkpointer.prototype.updateTarget = function (checkpoint, session) { + return updateCheckpoint(this.target, this.id, checkpoint, + session, this.returnValue); +}; + +Checkpointer.prototype.updateSource = function (checkpoint, session) { + var self = this; + if (this.readOnlySource) { + return PouchPromise.resolve(true); + } + return updateCheckpoint(this.src, this.id, checkpoint, + session, this.returnValue) + .catch(function (err) { + if (isForbiddenError(err)) { + self.readOnlySource = true; + return true; + } + throw err; + }); +}; + +var comparisons = { + "undefined": function (targetDoc, sourceDoc) { + // This is the previous comparison function + if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) { + return sourceDoc.last_seq; + } + /* istanbul ignore next */ + return 0; + }, + "1": function (targetDoc, sourceDoc) { + // This is the comparison function ported from CouchDB + return compareReplicationLogs(sourceDoc, targetDoc).last_seq; + } +}; + +Checkpointer.prototype.getCheckpoint = function () { + var self = this; + return self.target.get(self.id).then(function (targetDoc) { + if (self.readOnlySource) { + return PouchPromise.resolve(targetDoc.last_seq); + } + + return self.src.get(self.id).then(function (sourceDoc) { + // Since we can't migrate an old version doc to a new one + // (no session id), we just go with the lowest seq in this case + /* istanbul ignore if */ + if (targetDoc.version !== sourceDoc.version) { + return LOWEST_SEQ; + } + + var version; + if (targetDoc.version) { + version = targetDoc.version.toString(); + } else { + version = "undefined"; + } + + if (version in comparisons) { + return comparisons[version](targetDoc, sourceDoc); + } + /* istanbul ignore next */ + return LOWEST_SEQ; + }, function (err) { + if (err.status === 404 && targetDoc.last_seq) { + return self.src.put({ + _id: self.id, + last_seq: LOWEST_SEQ + }).then(function () { + return LOWEST_SEQ; + }, function (err) { + if (isForbiddenError(err)) { + self.readOnlySource = true; + return targetDoc.last_seq; + } + /* istanbul ignore next */ + return LOWEST_SEQ; + }); + } + throw err; + }); + }).catch(function (err) { + if (err.status !== 404) { + throw err; + } + return LOWEST_SEQ; + }); +}; +// This checkpoint comparison is ported from CouchDBs source +// they come from here: +// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906 + +function compareReplicationLogs(srcDoc, tgtDoc) { + if (srcDoc.session_id === tgtDoc.session_id) { + return { + last_seq: srcDoc.last_seq, + history: srcDoc.history + }; + } + + return compareReplicationHistory(srcDoc.history, tgtDoc.history); +} + +function compareReplicationHistory(sourceHistory, targetHistory) { + // the erlang loop via function arguments is not so easy to repeat in JS + // therefore, doing this as recursion + var S = sourceHistory[0]; + var sourceRest = sourceHistory.slice(1); + var T = targetHistory[0]; + var targetRest = targetHistory.slice(1); + + if (!S || targetHistory.length === 0) { + return { + last_seq: LOWEST_SEQ, + history: [] + }; + } + + var sourceId = S.session_id; + /* istanbul ignore if */ + if (hasSessionId(sourceId, targetHistory)) { + return { + last_seq: S.last_seq, + history: sourceHistory + }; + } + + var targetId = T.session_id; + if (hasSessionId(targetId, sourceRest)) { + return { + last_seq: T.last_seq, + history: targetRest + }; + } + + return compareReplicationHistory(sourceRest, targetRest); +} + +function hasSessionId(sessionId, history) { + var props = history[0]; + var rest = history.slice(1); + + if (!sessionId || history.length === 0) { + return false; + } + + if (sessionId === props.session_id) { + return true; + } + + return hasSessionId(sessionId, rest); +} + +function isForbiddenError(err) { + return typeof err.status === 'number' && Math.floor(err.status / 100) === 4; +} + +var STARTING_BACK_OFF = 0; + +function backOff(opts, returnValue, error, callback) { + if (opts.retry === false) { + returnValue.emit('error', error); + returnValue.removeAllListeners(); + return; + } + if (typeof opts.back_off_function !== 'function') { + opts.back_off_function = defaultBackOff; + } + returnValue.emit('requestError', error); + if (returnValue.state === 'active' || returnValue.state === 'pending') { + returnValue.emit('paused', error); + returnValue.state = 'stopped'; + var backOffSet = function backoffTimeSet() { + opts.current_back_off = STARTING_BACK_OFF; + }; + var removeBackOffSetter = function removeBackOffTimeSet() { + returnValue.removeListener('active', backOffSet); + }; + returnValue.once('paused', removeBackOffSetter); + returnValue.once('active', backOffSet); + } + + opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF; + opts.current_back_off = opts.back_off_function(opts.current_back_off); + setTimeout(callback, opts.current_back_off); +} + +function sortObjectPropertiesByKey(queryParams) { + return Object.keys(queryParams).sort(collate).reduce(function (result, key) { + result[key] = queryParams[key]; + return result; + }, {}); +} + +// Generate a unique id particular to this replication. +// Not guaranteed to align perfectly with CouchDB's rep ids. +function generateReplicationId(src, target, opts) { + var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : ''; + var filterFun = opts.filter ? opts.filter.toString() : ''; + var queryParams = ''; + var filterViewName = ''; + + if (opts.filter && opts.query_params) { + queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params)); + } + + if (opts.filter && opts.filter === '_view') { + filterViewName = opts.view.toString(); + } + + return PouchPromise.all([src.id(), target.id()]).then(function (res) { + var queryData = res[0] + res[1] + filterFun + filterViewName + + queryParams + docIds; + return new PouchPromise(function (resolve) { + binaryMd5(queryData, resolve); + }); + }).then(function (md5sum) { + // can't use straight-up md5 alphabet, because + // the char '/' is interpreted as being for attachments, + // and + is also not url-safe + md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_'); + return '_local/' + md5sum; + }); +} + +function replicate$1(src, target, opts, returnValue, result) { + var batches = []; // list of batches to be processed + var currentBatch; // the batch currently being processed + var pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; // next batch, not yet ready to be processed + var writingCheckpoint = false; // true while checkpoint is being written + var changesCompleted = false; // true when all changes received + var replicationCompleted = false; // true when replication has completed + var last_seq = 0; + var continuous = opts.continuous || opts.live || false; + var batch_size = opts.batch_size || 100; + var batches_limit = opts.batches_limit || 10; + var changesPending = false; // true while src.changes is running + var doc_ids = opts.doc_ids; + var repId; + var checkpointer; + var changedDocs = []; + // Like couchdb, every replication gets a unique session id + var session = uuid(); + + result = result || { + ok: true, + start_time: new Date(), + docs_read: 0, + docs_written: 0, + doc_write_failures: 0, + errors: [] + }; + + var changesOpts = {}; + returnValue.ready(src, target); + + function initCheckpointer() { + if (checkpointer) { + return PouchPromise.resolve(); + } + return generateReplicationId(src, target, opts).then(function (res) { + repId = res; + checkpointer = new Checkpointer(src, target, repId, returnValue); + }); + } + + function writeDocs() { + changedDocs = []; + + if (currentBatch.docs.length === 0) { + return; + } + var docs = currentBatch.docs; + var bulkOpts = {timeout: opts.timeout}; + return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + + // `res` doesn't include full documents (which live in `docs`), so we create a map of + // (id -> error), and check for errors while iterating over `docs` + var errorsById = Object.create(null); + res.forEach(function (res) { + if (res.error) { + errorsById[res.id] = res; + } + }); + + var errorsNo = Object.keys(errorsById).length; + result.doc_write_failures += errorsNo; + result.docs_written += docs.length - errorsNo; + + docs.forEach(function (doc) { + var error = errorsById[doc._id]; + if (error) { + result.errors.push(error); + if (error.name === 'unauthorized' || error.name === 'forbidden') { + returnValue.emit('denied', clone(error)); + } else { + throw error; + } + } else { + changedDocs.push(doc); + } + }); + + }, function (err) { + result.doc_write_failures += docs.length; + throw err; + }); + } + + function finishBatch() { + if (currentBatch.error) { + throw new Error('There was a problem getting docs.'); + } + result.last_seq = last_seq = currentBatch.seq; + var outResult = clone(result); + if (changedDocs.length) { + outResult.docs = changedDocs; + returnValue.emit('change', outResult); + } + writingCheckpoint = true; + return checkpointer.writeCheckpoint(currentBatch.seq, + session).then(function () { + writingCheckpoint = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + currentBatch = undefined; + getChanges(); + }).catch(function (err) { + onCheckpointError(err); + throw err; + }); + } + + function getDiffs() { + var diff = {}; + currentBatch.changes.forEach(function (change) { + // Couchbase Sync Gateway emits these, but we can ignore them + /* istanbul ignore if */ + if (change.id === "_user/") { + return; + } + diff[change.id] = change.changes.map(function (x) { + return x.rev; + }); + }); + return target.revsDiff(diff).then(function (diffs) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + throw new Error('cancelled'); + } + // currentBatch.diffs elements are deleted as the documents are written + currentBatch.diffs = diffs; + }); + } + + function getBatchDocs() { + return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) { + currentBatch.error = !got.ok; + got.docs.forEach(function (doc) { + delete currentBatch.diffs[doc._id]; + result.docs_read++; + currentBatch.docs.push(doc); + }); + }); + } + + function startNextBatch() { + if (returnValue.cancelled || currentBatch) { + return; + } + if (batches.length === 0) { + processPendingBatch(true); + return; + } + currentBatch = batches.shift(); + getDiffs() + .then(getBatchDocs) + .then(writeDocs) + .then(finishBatch) + .then(startNextBatch) + .catch(function (err) { + abortReplication('batch processing terminated with error', err); + }); + } + + + function processPendingBatch(immediate) { + if (pendingBatch.changes.length === 0) { + if (batches.length === 0 && !currentBatch) { + if ((continuous && changesOpts.live) || changesCompleted) { + returnValue.state = 'pending'; + returnValue.emit('paused'); + } + if (changesCompleted) { + completeReplication(); + } + } + return; + } + if ( + immediate || + changesCompleted || + pendingBatch.changes.length >= batch_size + ) { + batches.push(pendingBatch); + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + if (returnValue.state === 'pending' || returnValue.state === 'stopped') { + returnValue.state = 'active'; + returnValue.emit('active'); + } + startNextBatch(); + } + } + + + function abortReplication(reason, err) { + if (replicationCompleted) { + return; + } + if (!err.message) { + err.message = reason; + } + result.ok = false; + result.status = 'aborting'; + batches = []; + pendingBatch = { + seq: 0, + changes: [], + docs: [] + }; + completeReplication(err); + } + + + function completeReplication(fatalError) { + if (replicationCompleted) { + return; + } + /* istanbul ignore if */ + if (returnValue.cancelled) { + result.status = 'cancelled'; + if (writingCheckpoint) { + return; + } + } + result.status = result.status || 'complete'; + result.end_time = new Date(); + result.last_seq = last_seq; + replicationCompleted = true; + + if (fatalError) { + fatalError.result = result; + + if (fatalError.name === 'unauthorized' || fatalError.name === 'forbidden') { + returnValue.emit('error', fatalError); + returnValue.removeAllListeners(); + } else { + backOff(opts, returnValue, fatalError, function () { + replicate$1(src, target, opts, returnValue); + }); + } + } else { + returnValue.emit('complete', result); + returnValue.removeAllListeners(); + } + } + + + function onChange(change) { + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + var filter = filterChange(opts)(change); + if (!filter) { + return; + } + pendingBatch.seq = change.seq; + pendingBatch.changes.push(change); + processPendingBatch(batches.length === 0 && changesOpts.live); + } + + + function onChangesComplete(changes) { + changesPending = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + + // if no results were returned then we're done, + // else fetch more + if (changes.results.length > 0) { + changesOpts.since = changes.last_seq; + getChanges(); + processPendingBatch(true); + } else { + + var complete = function () { + if (continuous) { + changesOpts.live = true; + getChanges(); + } else { + changesCompleted = true; + } + processPendingBatch(true); + }; + + // update the checkpoint so we start from the right seq next time + if (!currentBatch && changes.results.length === 0) { + writingCheckpoint = true; + checkpointer.writeCheckpoint(changes.last_seq, + session).then(function () { + writingCheckpoint = false; + result.last_seq = last_seq = changes.last_seq; + complete(); + }) + .catch(onCheckpointError); + } else { + complete(); + } + } + } + + + function onChangesError(err) { + changesPending = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + return completeReplication(); + } + abortReplication('changes rejected', err); + } + + + function getChanges() { + if (!( + !changesPending && + !changesCompleted && + batches.length < batches_limit + )) { + return; + } + changesPending = true; + function abortChanges() { + changes.cancel(); + } + function removeListener() { + returnValue.removeListener('cancel', abortChanges); + } + + if (returnValue._changes) { // remove old changes() and listeners + returnValue.removeListener('cancel', returnValue._abortChanges); + returnValue._changes.cancel(); + } + returnValue.once('cancel', abortChanges); + + var changes = src.changes(changesOpts) + .on('change', onChange); + changes.then(removeListener, removeListener); + changes.then(onChangesComplete) + .catch(onChangesError); + + if (opts.retry) { + // save for later so we can cancel if necessary + returnValue._changes = changes; + returnValue._abortChanges = abortChanges; + } + } + + + function startChanges() { + initCheckpointer().then(function () { + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + return; + } + return checkpointer.getCheckpoint().then(function (checkpoint) { + last_seq = checkpoint; + changesOpts = { + since: last_seq, + limit: batch_size, + batch_size: batch_size, + style: 'all_docs', + doc_ids: doc_ids, + return_docs: true // required so we know when we're done + }; + if (opts.filter) { + if (typeof opts.filter !== 'string') { + // required for the client-side filter in onChange + changesOpts.include_docs = true; + } else { // ddoc filter + changesOpts.filter = opts.filter; + } + } + if ('heartbeat' in opts) { + changesOpts.heartbeat = opts.heartbeat; + } + if ('timeout' in opts) { + changesOpts.timeout = opts.timeout; + } + if (opts.query_params) { + changesOpts.query_params = opts.query_params; + } + if (opts.view) { + changesOpts.view = opts.view; + } + getChanges(); + }); + }).catch(function (err) { + abortReplication('getCheckpoint rejected with ', err); + }); + } + + /* istanbul ignore next */ + function onCheckpointError(err) { + writingCheckpoint = false; + abortReplication('writeCheckpoint completed with error', err); + } + + /* istanbul ignore if */ + if (returnValue.cancelled) { // cancelled immediately + completeReplication(); + return; + } + + if (!returnValue._addedListeners) { + returnValue.once('cancel', completeReplication); + + if (typeof opts.complete === 'function') { + returnValue.once('error', opts.complete); + returnValue.once('complete', function (result) { + opts.complete(null, result); + }); + } + returnValue._addedListeners = true; + } + + if (typeof opts.since === 'undefined') { + startChanges(); + } else { + initCheckpointer().then(function () { + writingCheckpoint = true; + return checkpointer.writeCheckpoint(opts.since, session); + }).then(function () { + writingCheckpoint = false; + /* istanbul ignore if */ + if (returnValue.cancelled) { + completeReplication(); + return; + } + last_seq = opts.since; + startChanges(); + }).catch(onCheckpointError); + } +} + +// We create a basic promise so the caller can cancel the replication possibly +// before we have actually started listening to changes etc +inherits(Replication, EventEmitter); +function Replication() { + EventEmitter.call(this); + this.cancelled = false; + this.state = 'pending'; + var self = this; + var promise = new PouchPromise(function (fulfill, reject) { + self.once('complete', fulfill); + self.once('error', reject); + }); + self.then = function (resolve, reject) { + return promise.then(resolve, reject); + }; + self.catch = function (reject) { + return promise.catch(reject); + }; + // As we allow error handling via "error" event as well, + // put a stub in here so that rejecting never throws UnhandledError. + self.catch(function () {}); +} + +Replication.prototype.cancel = function () { + this.cancelled = true; + this.state = 'cancelled'; + this.emit('cancel'); +}; + +Replication.prototype.ready = function (src, target) { + var self = this; + if (self._readyCalled) { + return; + } + self._readyCalled = true; + + function onDestroy() { + self.cancel(); + } + src.once('destroyed', onDestroy); + target.once('destroyed', onDestroy); + function cleanup() { + src.removeListener('destroyed', onDestroy); + target.removeListener('destroyed', onDestroy); + } + self.once('complete', cleanup); +}; + +function toPouch(db, opts) { + var PouchConstructor = opts.PouchConstructor; + if (typeof db === 'string') { + return new PouchConstructor(db, opts); + } else { + return db; + } +} + +function replicate(src, target, opts, callback) { + + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof opts === 'undefined') { + opts = {}; + } + + if (opts.doc_ids && !Array.isArray(opts.doc_ids)) { + throw createError(BAD_REQUEST, + "`doc_ids` filter parameter is not a list."); + } + + opts.complete = callback; + opts = clone(opts); + opts.continuous = opts.continuous || opts.live; + opts.retry = ('retry' in opts) ? opts.retry : false; + /*jshint validthis:true */ + opts.PouchConstructor = opts.PouchConstructor || this; + var replicateRet = new Replication(opts); + var srcPouch = toPouch(src, opts); + var targetPouch = toPouch(target, opts); + replicate$1(srcPouch, targetPouch, opts, replicateRet); + return replicateRet; +} + +inherits(Sync, EventEmitter); +function sync(src, target, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + if (typeof opts === 'undefined') { + opts = {}; + } + opts = clone(opts); + /*jshint validthis:true */ + opts.PouchConstructor = opts.PouchConstructor || this; + src = toPouch(src, opts); + target = toPouch(target, opts); + return new Sync(src, target, opts, callback); +} + +function Sync(src, target, opts, callback) { + var self = this; + this.canceled = false; + + var optsPush = opts.push ? extend({}, opts, opts.push) : opts; + var optsPull = opts.pull ? extend({}, opts, opts.pull) : opts; + + this.push = replicate(src, target, optsPush); + this.pull = replicate(target, src, optsPull); + + this.pushPaused = true; + this.pullPaused = true; + + function pullChange(change) { + self.emit('change', { + direction: 'pull', + change: change + }); + } + function pushChange(change) { + self.emit('change', { + direction: 'push', + change: change + }); + } + function pushDenied(doc) { + self.emit('denied', { + direction: 'push', + doc: doc + }); + } + function pullDenied(doc) { + self.emit('denied', { + direction: 'pull', + doc: doc + }); + } + function pushPaused() { + self.pushPaused = true; + /* istanbul ignore if */ + if (self.pullPaused) { + self.emit('paused'); + } + } + function pullPaused() { + self.pullPaused = true; + /* istanbul ignore if */ + if (self.pushPaused) { + self.emit('paused'); + } + } + function pushActive() { + self.pushPaused = false; + /* istanbul ignore if */ + if (self.pullPaused) { + self.emit('active', { + direction: 'push' + }); + } + } + function pullActive() { + self.pullPaused = false; + /* istanbul ignore if */ + if (self.pushPaused) { + self.emit('active', { + direction: 'pull' + }); + } + } + + var removed = {}; + + function removeAll(type) { // type is 'push' or 'pull' + return function (event, func) { + var isChange = event === 'change' && + (func === pullChange || func === pushChange); + var isDenied = event === 'denied' && + (func === pullDenied || func === pushDenied); + var isPaused = event === 'paused' && + (func === pullPaused || func === pushPaused); + var isActive = event === 'active' && + (func === pullActive || func === pushActive); + + if (isChange || isDenied || isPaused || isActive) { + if (!(event in removed)) { + removed[event] = {}; + } + removed[event][type] = true; + if (Object.keys(removed[event]).length === 2) { + // both push and pull have asked to be removed + self.removeAllListeners(event); + } + } + }; + } + + if (opts.live) { + this.push.on('complete', self.pull.cancel.bind(self.pull)); + this.pull.on('complete', self.push.cancel.bind(self.push)); + } + + this.on('newListener', function (event) { + if (event === 'change') { + self.pull.on('change', pullChange); + self.push.on('change', pushChange); + } else if (event === 'denied') { + self.pull.on('denied', pullDenied); + self.push.on('denied', pushDenied); + } else if (event === 'active') { + self.pull.on('active', pullActive); + self.push.on('active', pushActive); + } else if (event === 'paused') { + self.pull.on('paused', pullPaused); + self.push.on('paused', pushPaused); + } + }); + + this.on('removeListener', function (event) { + if (event === 'change') { + self.pull.removeListener('change', pullChange); + self.push.removeListener('change', pushChange); + } else if (event === 'denied') { + self.pull.removeListener('denied', pullDenied); + self.push.removeListener('denied', pushDenied); + } else if (event === 'active') { + self.pull.removeListener('active', pullActive); + self.push.removeListener('active', pushActive); + } else if (event === 'paused') { + self.pull.removeListener('paused', pullPaused); + self.push.removeListener('paused', pushPaused); + } + }); + + this.pull.on('removeListener', removeAll('pull')); + this.push.on('removeListener', removeAll('push')); + + var promise = PouchPromise.all([ + this.push, + this.pull + ]).then(function (resp) { + var out = { + push: resp[0], + pull: resp[1] + }; + self.emit('complete', out); + if (callback) { + callback(null, out); + } + self.removeAllListeners(); + return out; + }, function (err) { + self.cancel(); + if (callback) { + // if there's a callback, then the callback can receive + // the error event + callback(err); + } else { + // if there's no callback, then we're safe to emit an error + // event, which would otherwise throw an unhandled error + // due to 'error' being a special event in EventEmitters + self.emit('error', err); + } + self.removeAllListeners(); + if (callback) { + // no sense throwing if we're already emitting an 'error' event + throw err; + } + }); + + this.then = function (success, err) { + return promise.then(success, err); + }; + + this.catch = function (err) { + return promise.catch(err); + }; +} + +Sync.prototype.cancel = function () { + if (!this.canceled) { + this.canceled = true; + this.push.cancel(); + this.pull.cancel(); + } +}; + +function replication(PouchDB) { + PouchDB.replicate = replicate; + PouchDB.sync = sync; + + Object.defineProperty(PouchDB.prototype, 'replicate', { + get: function () { + var self = this; + return { + from: function (other, opts, callback) { + return self.constructor.replicate(other, self, opts, callback); + }, + to: function (other, opts, callback) { + return self.constructor.replicate(self, other, opts, callback); + } + }; + } + }); + + PouchDB.prototype.sync = function (dbName, opts, callback) { + return this.constructor.sync(this, dbName, opts, callback); + }; +} + +PouchDB.plugin(LevelPouch) + .plugin(HttpPouch$1) + .plugin(mapreduce) + .plugin(replication); + +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. + +export default PouchDB; \ No newline at end of file diff --git a/lib/pouchdb/lib/index.js b/lib/pouchdb/lib/index.js index 1a075950..30144d07 100644 --- a/lib/pouchdb/lib/index.js +++ b/lib/pouchdb/lib/index.js @@ -15,12 +15,12 @@ var ltgt = _interopDefault(require('ltgt')); var Codec = _interopDefault(require('level-codec')); var ReadableStreamCore = _interopDefault(require('readable-stream')); var through2 = require('through2'); -var fs = _interopDefault(require('fs')); -var path = _interopDefault(require('path')); -var LevelWriteStream = _interopDefault(require('level-write-stream')); var Deque = _interopDefault(require('double-ended-queue')); var crypto = _interopDefault(require('crypto')); var vuvuzela = _interopDefault(require('vuvuzela')); +var fs = _interopDefault(require('fs')); +var path = _interopDefault(require('path')); +var LevelWriteStream = _interopDefault(require('level-write-stream')); var PromisePool = _interopDefault(require('es6-promise-pool')); var scopedEval = _interopDefault(require('scope-eval')); @@ -2826,7 +2826,7 @@ PouchDB.defaults = function (defaultOpts) { }; // managed automatically by set-version.js -var version = "6.0.4"; +var version = "6.0.6"; PouchDB.version = version; @@ -2961,8 +2961,8 @@ function nut(db, precodec, codec) { }; } -function NotFoundError(reason) { - Error.call(this, reason); +function NotFoundError() { + Error.call(this); } inherits(NotFoundError, Error); @@ -2972,6 +2972,8 @@ NotFoundError.prototype.name = 'NotFoundError'; var EventEmitter$1 = events__default.EventEmitter; var version$1 = "6.5.4"; +var NOT_FOUND_ERROR = new NotFoundError(); + var sublevel = function (nut, prefix, createStream, options) { var emitter = new EventEmitter$1(); emitter.sublevels = {}; @@ -3060,7 +3062,7 @@ var sublevel = function (nut, prefix, createStream, options) { } nut.get(key, prefix, mergeOpts(opts), function (err, value) { if (err) { - cb(new NotFoundError(err)); + cb(NOT_FOUND_ERROR); } else { cb(null, value); } @@ -3207,194 +3209,6 @@ function sublevelPouch(db) { return sublevel(nut(db, precodec, codec), [], ReadStream, db.options); } -var stores = [ - 'document-store', - 'by-sequence', - 'attach-store', - 'attach-binary-store' -]; -function formatSeq(n) { - return ('0000000000000000' + n).slice(-16); -} -var UPDATE_SEQ_KEY$1 = '_local_last_update_seq'; -var DOC_COUNT_KEY$1 = '_local_doc_count'; -var UUID_KEY$1 = '_local_uuid'; - -var toSublevel = function (name, db, callback) { - // local require to prevent crashing if leveldown isn't installed. - var leveldown = require("leveldown"); - - var base = path.resolve(name); - function move(store, index, cb) { - var storePath = path.join(base, store); - var opts; - if (index === 3) { - opts = { - valueEncoding: 'binary' - }; - } else { - opts = { - valueEncoding: 'json' - }; - } - var sub = db.sublevel(store, opts); - var orig = levelup(storePath, opts); - var from = orig.createReadStream(); - var writeStream = new LevelWriteStream(sub); - var to = writeStream(); - from.on('end', function () { - orig.close(function (err) { - cb(err, storePath); - }); - }); - from.pipe(to); - } - fs.unlink(base + '.uuid', function (err) { - if (err) { - return callback(); - } - var todo = 4; - var done = []; - stores.forEach(function (store, i) { - move(store, i, function (err, storePath) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - done.push(storePath); - if (!(--todo)) { - done.forEach(function (item) { - leveldown.destroy(item, function () { - if (++todo === done.length) { - fs.rmdir(base, callback); - } - }); - }); - } - }); - }); - }); -}; -var localAndMetaStores = function (db, stores, callback) { - var batches = []; - stores.bySeqStore.get(UUID_KEY$1, function (err, value) { - if (err) { - // no uuid key, so don't need to migrate; - return callback(); - } - batches.push({ - key: UUID_KEY$1, - value: value, - prefix: stores.metaStore, - type: 'put', - valueEncoding: 'json' - }); - batches.push({ - key: UUID_KEY$1, - prefix: stores.bySeqStore, - type: 'del' - }); - stores.bySeqStore.get(DOC_COUNT_KEY$1, function (err, value) { - if (value) { - // if no doc count key, - // just skip - // we can live with this - batches.push({ - key: DOC_COUNT_KEY$1, - value: value, - prefix: stores.metaStore, - type: 'put', - valueEncoding: 'json' - }); - batches.push({ - key: DOC_COUNT_KEY$1, - prefix: stores.bySeqStore, - type: 'del' - }); - } - stores.bySeqStore.get(UPDATE_SEQ_KEY$1, function (err, value) { - if (value) { - // if no UPDATE_SEQ_KEY - // just skip - // we've gone to far to stop. - batches.push({ - key: UPDATE_SEQ_KEY$1, - value: value, - prefix: stores.metaStore, - type: 'put', - valueEncoding: 'json' - }); - batches.push({ - key: UPDATE_SEQ_KEY$1, - prefix: stores.bySeqStore, - type: 'del' - }); - } - var deletedSeqs = {}; - stores.docStore.createReadStream({ - startKey: '_', - endKey: '_\xFF' - }).pipe(through2.obj(function (ch, _, next) { - if (!isLocalId(ch.key)) { - return next(); - } - batches.push({ - key: ch.key, - prefix: stores.docStore, - type: 'del' - }); - var winner = winningRev(ch.value); - Object.keys(ch.value.rev_map).forEach(function (key) { - if (key !== 'winner') { - this.push(formatSeq(ch.value.rev_map[key])); - } - }, this); - var winningSeq = ch.value.rev_map[winner]; - stores.bySeqStore.get(formatSeq(winningSeq), function (err, value) { - if (!err) { - batches.push({ - key: ch.key, - value: value, - prefix: stores.localStore, - type: 'put', - valueEncoding: 'json' - }); - } - next(); - }); - - })).pipe(through2.obj(function (seq, _, next) { - /* istanbul ignore if */ - if (deletedSeqs[seq]) { - return next(); - } - deletedSeqs[seq] = true; - stores.bySeqStore.get(seq, function (err, resp) { - /* istanbul ignore if */ - if (err || !isLocalId(resp._id)) { - return next(); - } - batches.push({ - key: seq, - prefix: stores.bySeqStore, - type: 'del' - }); - next(); - }); - }, function () { - db.batch(batches, callback); - })); - }); - }); - }); - -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - function toObject(array) { return array.reduce(function (obj, item) { obj[item] = true; @@ -4005,8 +3819,8 @@ function LevelPouch$1(opts, callback) { db._docCount = -1; db._queue = new Deque(); /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationOne(name, db, afterDBCreated); } else { afterDBCreated(); } @@ -4021,19 +3835,26 @@ function LevelPouch$1(opts, callback) { stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); + /* istanbul ignore else */ + if (typeof opts.migrate === 'object') { // migration for leveldown + opts.migrate.doMigrationTwo(db, stores, afterLastMigration); + } else { + afterLastMigration(); + } + } + + function afterLastMigration() { + stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { + if (typeof db._updateSeq === 'undefined') { + db._updateSeq = value || 0; + } + stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { + db._docCount = !err ? value : 0; + stores.metaStore.get(UUID_KEY, function (err, value) { + instanceId = !err ? value : uuid(); + stores.metaStore.put(UUID_KEY, instanceId, function () { + process.nextTick(function () { + callback(null, api); }); }); }); @@ -5322,30 +5143,218 @@ var requireLeveldown = function () { } }; -function LevelDownPouch(opts, callback) { - - // Users can pass in their own leveldown alternative here, in which case - // it overrides the default one. (This is in addition to the custom builds.) - var leveldown = opts.db; +var stores = [ + 'document-store', + 'by-sequence', + 'attach-store', + 'attach-binary-store' +]; +function formatSeq(n) { + return ('0000000000000000' + n).slice(-16); +} +var UPDATE_SEQ_KEY$1 = '_local_last_update_seq'; +var DOC_COUNT_KEY$1 = '_local_doc_count'; +var UUID_KEY$1 = '_local_uuid'; - /* istanbul ignore else */ - if (!leveldown) { - leveldown = requireLeveldown(); +var doMigrationOne = function (name, db, callback) { + // local require to prevent crashing if leveldown isn't installed. + var leveldown = require("leveldown"); - /* istanbul ignore if */ - if (leveldown instanceof Error) { - return callback(leveldown); + var base = path.resolve(name); + function move(store, index, cb) { + var storePath = path.join(base, store); + var opts; + if (index === 3) { + opts = { + valueEncoding: 'binary' + }; + } else { + opts = { + valueEncoding: 'json' + }; } + var sub = db.sublevel(store, opts); + var orig = levelup(storePath, opts); + var from = orig.createReadStream(); + var writeStream = new LevelWriteStream(sub); + var to = writeStream(); + from.on('end', function () { + orig.close(function (err) { + cb(err, storePath); + }); + }); + from.pipe(to); } - - var _opts = jsExtend.extend({ - db: leveldown, - migrate: !opts.db - }, opts); - - LevelPouch$1.call(this, _opts, callback); -} - + fs.unlink(base + '.uuid', function (err) { + if (err) { + return callback(); + } + var todo = 4; + var done = []; + stores.forEach(function (store, i) { + move(store, i, function (err, storePath) { + /* istanbul ignore if */ + if (err) { + return callback(err); + } + done.push(storePath); + if (!(--todo)) { + done.forEach(function (item) { + leveldown.destroy(item, function () { + if (++todo === done.length) { + fs.rmdir(base, callback); + } + }); + }); + } + }); + }); + }); +}; +var doMigrationTwo = function (db, stores, callback) { + var batches = []; + stores.bySeqStore.get(UUID_KEY$1, function (err, value) { + if (err) { + // no uuid key, so don't need to migrate; + return callback(); + } + batches.push({ + key: UUID_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: UUID_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + stores.bySeqStore.get(DOC_COUNT_KEY$1, function (err, value) { + if (value) { + // if no doc count key, + // just skip + // we can live with this + batches.push({ + key: DOC_COUNT_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: DOC_COUNT_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + } + stores.bySeqStore.get(UPDATE_SEQ_KEY$1, function (err, value) { + if (value) { + // if no UPDATE_SEQ_KEY + // just skip + // we've gone to far to stop. + batches.push({ + key: UPDATE_SEQ_KEY$1, + value: value, + prefix: stores.metaStore, + type: 'put', + valueEncoding: 'json' + }); + batches.push({ + key: UPDATE_SEQ_KEY$1, + prefix: stores.bySeqStore, + type: 'del' + }); + } + var deletedSeqs = {}; + stores.docStore.createReadStream({ + startKey: '_', + endKey: '_\xFF' + }).pipe(through2.obj(function (ch, _, next) { + if (!isLocalId(ch.key)) { + return next(); + } + batches.push({ + key: ch.key, + prefix: stores.docStore, + type: 'del' + }); + var winner = winningRev(ch.value); + Object.keys(ch.value.rev_map).forEach(function (key) { + if (key !== 'winner') { + this.push(formatSeq(ch.value.rev_map[key])); + } + }, this); + var winningSeq = ch.value.rev_map[winner]; + stores.bySeqStore.get(formatSeq(winningSeq), function (err, value) { + if (!err) { + batches.push({ + key: ch.key, + value: value, + prefix: stores.localStore, + type: 'put', + valueEncoding: 'json' + }); + } + next(); + }); + + })).pipe(through2.obj(function (seq, _, next) { + /* istanbul ignore if */ + if (deletedSeqs[seq]) { + return next(); + } + deletedSeqs[seq] = true; + stores.bySeqStore.get(seq, function (err, resp) { + /* istanbul ignore if */ + if (err || !isLocalId(resp._id)) { + return next(); + } + batches.push({ + key: seq, + prefix: stores.bySeqStore, + type: 'del' + }); + next(); + }); + }, function () { + db.batch(batches, callback); + })); + }); + }); + }); + +}; + +var migrate = { + doMigrationOne: doMigrationOne, + doMigrationTwo: doMigrationTwo +}; + +function LevelDownPouch(opts, callback) { + + // Users can pass in their own leveldown alternative here, in which case + // it overrides the default one. (This is in addition to the custom builds.) + var leveldown = opts.db; + + /* istanbul ignore else */ + if (!leveldown) { + leveldown = requireLeveldown(); + + /* istanbul ignore if */ + if (leveldown instanceof Error) { + return callback(leveldown); + } + } + + var _opts = jsExtend.extend({ + db: leveldown, + migrate: migrate + }, opts); + + LevelPouch$1.call(this, _opts, callback); +} + // overrides for normal LevelDB behavior on Node LevelDownPouch.valid = function () { return true; @@ -6080,7 +6089,7 @@ function HttpPouch(opts, callback) { // Update/create the document ajax$$(opts, { method: 'PUT', - url: genDBUrl(host, encodeURIComponent(doc._id)), + url: genDBUrl(host, encodeDocId(doc._id)), body: doc }, function (err, result) { if (err) { @@ -6906,19 +6915,143 @@ function createView(opts) { return promiseForView; } -function evalfunc(func, emit, sum, log, isArray, toJSON) { - return scopedEval( - "return (" + func.replace(/;\s*$/, "") + ");", - { - emit: emit, - sum: sum, - log: log, - isArray: isArray, - toJSON: toJSON +function QueryParseError(message) { + this.status = 400; + this.name = 'query_parse_error'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, QueryParseError); + } catch (e) {} +} + +inherits(QueryParseError, Error); + +function NotFoundError$1(message) { + this.status = 404; + this.name = 'not_found'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, NotFoundError$1); + } catch (e) {} +} + +inherits(NotFoundError$1, Error); + +function BuiltInError(message) { + this.status = 500; + this.name = 'invalid_value'; + this.message = message; + this.error = true; + try { + Error.captureStackTrace(this, BuiltInError); + } catch (e) {} +} + +inherits(BuiltInError, Error); + +function createBuiltInError(name) { + var message = 'builtin ' + name + + ' function requires map values to be numbers' + + ' or number arrays'; + return new BuiltInError(message); +} + +function sum(values) { + var result = 0; + for (var i = 0, len = values.length; i < len; i++) { + var num = values[i]; + if (typeof num !== 'number') { + if (Array.isArray(num)) { + // lists of numbers are also allowed, sum them separately + result = typeof result === 'number' ? [result] : result; + for (var j = 0, jLen = num.length; j < jLen; j++) { + var jNum = num[j]; + if (typeof jNum !== 'number') { + throw createBuiltInError('_sum'); + } else if (typeof result[j] === 'undefined') { + result.push(jNum); + } else { + result[j] += jNum; + } + } + } else { // not array/number + throw createBuiltInError('_sum'); + } + } else if (typeof result === 'number') { + result += num; + } else { // add number to array + result[0] += num; + } + } + return result; +} + +// Inside of 'vm' for Node, we need a way to translate a pseudo-error +// back into a real error once it's out of the VM. +function createBuiltInErrorInVm(name) { + return { + builtInError: true, + name: name + }; +} + +function convertToTrueError(err) { + return createBuiltInError(err.name); +} + +function isBuiltInError(obj) { + return obj && obj.builtInError; +} + +// All of this vm hullaballoo is to be able to run arbitrary code in a sandbox +// for security reasons. +function evalFunctionInVm(func, emit) { + return function (arg1, arg2, arg3) { + var code = '(function() {"use strict";' + + 'var createBuiltInError = ' + createBuiltInErrorInVm.toString() + ';' + + 'var sum = ' + sum.toString() + ';' + + 'var log = function () {};' + + 'var isArray = Array.isArray;' + + 'var toJSON = JSON.parse;' + + 'var __emitteds__ = [];' + + 'var emit = function (key, value) {__emitteds__.push([key, value]);};' + + 'var __result__ = (' + + func.replace(/;\s*$/, '') + ')' + '(' + + JSON.stringify(arg1) + ',' + + JSON.stringify(arg2) + ',' + + JSON.stringify(arg3) + ');' + + 'return {result: __result__, emitteds: __emitteds__};' + + '})()'; + + var output = vm.runInNewContext(code); + + output.emitteds.forEach(function (emitted) { + emit(emitted[0], emitted[1]); + }); + if (isBuiltInError(output.result)) { + output.result = convertToTrueError(output.result); } - ); + return output.result; + }; } +var log$2 = guardedConsole.bind(null, 'log'); + +// The "stringify, then execute in a VM" strategy totally breaks Istanbul due +// to missing __coverage global objects. As a solution, export different +// code during coverage testing and during regular execution. +// Note that this doesn't get shipped to consumers because Rollup replaces it +// with rollup-plugin-replace, so false is replaced with `false` +var evalFunc; +/* istanbul ignore else */ +if (false) {} else { + evalFunc = evalFunctionInVm; +} + +var evalFunction = evalFunc; + var promisedCallback = function (promise, callback) { if (callback) { promise.then(function (res) { @@ -6990,8 +7123,6 @@ var persistentQueues = {}; var tempViewQueue = new TaskQueue$1(); var CHANGES_BATCH_SIZE$1 = 50; -var log$2 = guardedConsole.bind(null, 'log'); - function parseViewName(name) { // can be either 'ddocname/viewname' or just 'viewname' // (where the ddoc name is the same) @@ -7075,43 +7206,6 @@ function postprocessAttachments(opts) { }; } -function createBuiltInError(name) { - var message = 'builtin ' + name + - ' function requires map values to be numbers' + - ' or number arrays'; - return new BuiltInError(message); -} - -function sum(values) { - var result = 0; - for (var i = 0, len = values.length; i < len; i++) { - var num = values[i]; - if (typeof num !== 'number') { - if (Array.isArray(num)) { - // lists of numbers are also allowed, sum them separately - result = typeof result === 'number' ? [result] : result; - for (var j = 0, jLen = num.length; j < jLen; j++) { - var jNum = num[j]; - if (typeof jNum !== 'number') { - throw createBuiltInError('_sum'); - } else if (typeof result[j] === 'undefined') { - result.push(jNum); - } else { - result[j] += jNum; - } - } - } else { // not array/number - throw createBuiltInError('_sum'); - } - } else if (typeof result === 'number') { - result += num; - } else { // add number to array - result[0] += num; - } - } - return result; -} - var builtInReduce = { _sum: function (keys, values) { return sum(values); @@ -7466,8 +7560,7 @@ function updateViewInQueue(view) { return origMap(doc, emit); }; } else { - mapFun = evalfunc(view.mapFun.toString(), emit, sum, log$2, Array.isArray, - JSON.parse); + mapFun = evalFunction(view.mapFun.toString(), emit); } var currentSeq = view.seq || 0; @@ -7560,8 +7653,7 @@ function reduceView(view, results, options) { if (builtInReduce[view.reduceFun]) { reduceFun = builtInReduce[view.reduceFun]; } else { - reduceFun = evalfunc( - view.reduceFun.toString(), null, sum, log$2, Array.isArray, JSON.parse); + reduceFun = evalFunction(view.reduceFun.toString()); } var groups = []; @@ -7908,41 +8000,6 @@ var query = function (fun, opts, callback) { return promise; }; -function QueryParseError(message) { - this.status = 400; - this.name = 'query_parse_error'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, QueryParseError); - } catch (e) {} -} - -inherits(QueryParseError, Error); - -function NotFoundError$1(message) { - this.status = 404; - this.name = 'not_found'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, NotFoundError$1); - } catch (e) {} -} - -inherits(NotFoundError$1, Error); - -function BuiltInError(message) { - this.status = 500; - this.name = 'invalid_value'; - this.message = message; - this.error = true; - try { - Error.captureStackTrace(this, BuiltInError); - } catch (e) {} -} - -inherits(BuiltInError, Error); var mapreduce = { query: query, @@ -9195,4 +9252,8 @@ PouchDB.plugin(LevelPouch) .plugin(mapreduce) .plugin(replication); +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. + module.exports = PouchDB; \ No newline at end of file diff --git a/lib/pouchdb/lib/plugins/fruitdown.js b/lib/pouchdb/lib/plugins/fruitdown.js deleted file mode 100644 index 688eef9a..00000000 --- a/lib/pouchdb/lib/plugins/fruitdown.js +++ /dev/null @@ -1,3528 +0,0 @@ -'use strict'; - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var levelup = _interopDefault(require('levelup')); -var ltgt = _interopDefault(require('ltgt')); -var events = require('events'); -var events__default = _interopDefault(events); -var inherits = _interopDefault(require('inherits')); -var Codec = _interopDefault(require('level-codec')); -var ReadableStreamCore = _interopDefault(require('readable-stream')); -var through2 = require('through2'); -var getArguments = _interopDefault(require('argsarray')); -var Deque = _interopDefault(require('double-ended-queue')); -var lie = _interopDefault(require('lie')); -var debug = _interopDefault(require('debug')); -var Md5 = _interopDefault(require('spark-md5')); -var vuvuzela = _interopDefault(require('vuvuzela')); -var jsExtend = require('js-extend'); -var fruitdown = _interopDefault(require('fruitdown')); - -function isFunction(f) { - return 'function' === typeof f; -} - -function getPrefix(db) { - if (isFunction(db.prefix)) { - return db.prefix(); - } - return db; -} - -function clone(_obj) { - var obj = {}; - for(var k in _obj) { - obj[k] = _obj[k]; - } - return obj; -} - -function nut(db, precodec, codec) { - function encodePrefix(prefix, key, opts1, opts2) { - return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]); - } - - function addEncodings(op, prefix) { - if(prefix && prefix.options) { - op.keyEncoding = - op.keyEncoding || prefix.options.keyEncoding; - op.valueEncoding = - op.valueEncoding || prefix.options.valueEncoding; - } - return op; - } - - db.open(function () { /* no-op */}); - - return { - apply: function (ops, opts, cb) { - opts = opts || {}; - - var batch = []; - var i = -1; - var len = ops.length; - - while (++i < len) { - var op = ops[i]; - addEncodings(op, op.prefix); - op.prefix = getPrefix(op.prefix); - batch.push({ - key: encodePrefix(op.prefix, op.key, opts, op), - value: op.type !== 'del' && codec.encodeValue(op.value, opts, op), - type: op.type - }); - } - db.db.batch(batch, opts, cb); - }, - get: function (key, prefix, opts, cb) { - opts.asBuffer = codec.valueAsBuffer(opts); - return db.db.get( - encodePrefix(prefix, key, opts), - opts, - function (err, value) { - if (err) { - cb(err); - } else { - cb(null, codec.decodeValue(value, opts)); - } - } - ); - }, - createDecoder: function (opts) { - return function (key, value) { - return { - key: codec.decodeKey(precodec.decode(key)[1], opts), - value: codec.decodeValue(value, opts) - }; - }; - }, - isClosed: function isClosed() { - return db.isClosed(); - }, - close: function close(cb) { - return db.close(cb); - }, - iterator: function (_opts) { - var opts = clone(_opts || {}); - var prefix = _opts.prefix || []; - - function encodeKey(key) { - return encodePrefix(prefix, key, opts, {}); - } - - ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound); - - // if these legacy values are in the options, remove them - - opts.prefix = null; - - //************************************************ - //hard coded defaults, for now... - //TODO: pull defaults and encoding out of levelup. - opts.keyAsBuffer = opts.valueAsBuffer = false; - //************************************************ - - - //this is vital, otherwise limit: undefined will - //create an empty stream. - /* istanbul ignore next */ - if ('number' !== typeof opts.limit) { - opts.limit = -1; - } - - opts.keyAsBuffer = precodec.buffer; - opts.valueAsBuffer = codec.valueAsBuffer(opts); - - function wrapIterator(iterator) { - return { - next: function (cb) { - return iterator.next(cb); - }, - end: function (cb) { - iterator.end(cb); - } - }; - } - - return wrapIterator(db.db.iterator(opts)); - } - }; -} - -function NotFoundError(reason) { - Error.call(this, reason); -} - -inherits(NotFoundError, Error); - -NotFoundError.prototype.name = 'NotFoundError'; - -var EventEmitter$1 = events__default.EventEmitter; -var version = "6.5.4"; - -var sublevel = function (nut, prefix, createStream, options) { - var emitter = new EventEmitter$1(); - emitter.sublevels = {}; - emitter.options = options; - - emitter.version = version; - - emitter.methods = {}; - prefix = prefix || []; - - function mergeOpts(opts) { - var o = {}; - var k; - if (options) { - for (k in options) { - if (typeof options[k] !== 'undefined') { - o[k] = options[k]; - } - } - } - if (opts) { - for (k in opts) { - if (typeof opts[k] !== 'undefined') { - o[k] = opts[k]; - } - } - } - return o; - } - - emitter.put = function (key, value, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - nut.apply([{ - key: key, value: value, - prefix: prefix.slice(), type: 'put' - }], mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('put', key, value); - cb(null); - }); - }; - - emitter.prefix = function () { - return prefix.slice(); - }; - - emitter.batch = function (ops, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - ops = ops.map(function (op) { - return { - key: op.key, - value: op.value, - prefix: op.prefix || prefix, - keyEncoding: op.keyEncoding, // * - valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel) - type: op.type - }; - }); - - nut.apply(ops, mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('batch', ops); - cb(null); - }); - }; - - emitter.get = function (key, opts, cb) { - /* istanbul ignore else */ - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - nut.get(key, prefix, mergeOpts(opts), function (err, value) { - if (err) { - cb(new NotFoundError(err)); - } else { - cb(null, value); - } - }); - }; - - emitter.sublevel = function (name, opts) { - return emitter.sublevels[name] = - emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts)); - }; - - emitter.readStream = emitter.createReadStream = function (opts) { - opts = mergeOpts(opts); - opts.prefix = prefix; - var stream; - var it = nut.iterator(opts); - - stream = createStream(opts, nut.createDecoder(opts)); - stream.setIterator(it); - - return stream; - }; - - emitter.close = function (cb) { - nut.close(cb); - }; - - emitter.isOpen = nut.isOpen; - emitter.isClosed = nut.isClosed; - - return emitter; -}; - -/* Copyright (c) 2012-2014 LevelUP contributors - * See list at - * MIT License - */ - -// NOTE: we are fixed to readable-stream@1.0.x for now -// for pure Streams2 across Node versions -var Readable = ReadableStreamCore.Readable; - -function ReadStream(options, makeData) { - if (!(this instanceof ReadStream)) { - return new ReadStream(options, makeData); - } - - Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); - - // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref - - this._waiting = false; - this._options = options; - this._makeData = makeData; -} - -inherits(ReadStream, Readable); - -ReadStream.prototype.setIterator = function (it) { - this._iterator = it; - /* istanbul ignore if */ - if (this._destroyed) { - return it.end(function () {}); - } - /* istanbul ignore if */ - if (this._waiting) { - this._waiting = false; - return this._read(); - } - return this; -}; - -ReadStream.prototype._read = function read() { - var self = this; - /* istanbul ignore if */ - if (self._destroyed) { - return; - } - /* istanbul ignore if */ - if (!self._iterator) { - return this._waiting = true; - } - - self._iterator.next(function (err, key, value) { - if (err || (key === undefined && value === undefined)) { - if (!err && !self._destroyed) { - self.push(null); - } - return self._cleanup(err); - } - - - value = self._makeData(key, value); - if (!self._destroyed) { - self.push(value); - } - }); -}; - -ReadStream.prototype._cleanup = function (err) { - if (this._destroyed) { - return; - } - - this._destroyed = true; - - var self = this; - /* istanbul ignore if */ - if (err) { - self.emit('error', err); - } - - /* istanbul ignore else */ - if (self._iterator) { - self._iterator.end(function () { - self._iterator = null; - self.emit('close'); - }); - } else { - self.emit('close'); - } -}; - -ReadStream.prototype.destroy = function () { - this._cleanup(); -}; - -var precodec = { - encode: function (decodedKey) { - return '\xff' + decodedKey[0] + '\xff' + decodedKey[1]; - }, - decode: function (encodedKeyAsBuffer) { - var str = encodedKeyAsBuffer.toString(); - var idx = str.indexOf('\xff', 1); - return [str.substring(1, idx), str.substring(idx + 1)]; - }, - lowerBound: '\x00', - upperBound: '\xff' -}; - -var codec = new Codec(); - -function sublevelPouch(db) { - return sublevel(nut(db, precodec, codec), [], ReadStream, db.options); -} - -// based on https://github.com/montagejs/collections -function mangle(key) { - return '$' + key; -} -function unmangle(key) { - return key.substring(1); -} -function _Map() { - this.store = {}; -} -_Map.prototype.get = function (key) { - var mangled = mangle(key); - return this.store[mangled]; -}; -_Map.prototype.set = function (key, value) { - var mangled = mangle(key); - this.store[mangled] = value; - return true; -}; -_Map.prototype.has = function (key) { - var mangled = mangle(key); - return mangled in this.store; -}; -_Map.prototype.delete = function (key) { - var mangled = mangle(key); - var res = mangled in this.store; - delete this.store[mangled]; - return res; -}; -_Map.prototype.forEach = function (cb) { - var keys = Object.keys(this.store); - for (var i = 0, len = keys.length; i < len; i++) { - var key = keys[i]; - var value = this.store[key]; - key = unmangle(key); - cb(value, key); - } -}; - -function _Set(array) { - this.store = new _Map(); - - // init with an array - if (array && Array.isArray(array)) { - for (var i = 0, len = array.length; i < len; i++) { - this.add(array[i]); - } - } -} -_Set.prototype.add = function (key) { - return this.store.set(key, true); -}; -_Set.prototype.has = function (key) { - return this.store.has(key); -}; - -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - -/* istanbul ignore next */ -var PouchPromise = typeof Promise === 'function' ? Promise : lie; - -function isBinaryObject(object) { - return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) || - (typeof Blob !== 'undefined' && object instanceof Blob); -} - -function cloneArrayBuffer(buff) { - if (typeof buff.slice === 'function') { - return buff.slice(0); - } - // IE10-11 slice() polyfill - var target = new ArrayBuffer(buff.byteLength); - var targetArray = new Uint8Array(target); - var sourceArray = new Uint8Array(buff); - targetArray.set(sourceArray); - return target; -} - -function cloneBinaryObject(object) { - if (object instanceof ArrayBuffer) { - return cloneArrayBuffer(object); - } - var size = object.size; - var type = object.type; - // Blob - if (typeof object.slice === 'function') { - return object.slice(0, size, type); - } - // PhantomJS slice() replacement - return object.webkitSlice(0, size, type); -} - -// most of this is borrowed from lodash.isPlainObject: -// https://github.com/fis-components/lodash.isplainobject/ -// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js - -var funcToString = Function.prototype.toString; -var objectCtorString = funcToString.call(Object); - -function isPlainObject(value) { - var proto = Object.getPrototypeOf(value); - /* istanbul ignore if */ - if (proto === null) { // not sure when this happens, but I guess it can - return true; - } - var Ctor = proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} - -function clone$1(object) { - var newObject; - var i; - var len; - - if (!object || typeof object !== 'object') { - return object; - } - - if (Array.isArray(object)) { - newObject = []; - for (i = 0, len = object.length; i < len; i++) { - newObject[i] = clone$1(object[i]); - } - return newObject; - } - - // special case: to avoid inconsistencies between IndexedDB - // and other backends, we automatically stringify Dates - if (object instanceof Date) { - return object.toISOString(); - } - - if (isBinaryObject(object)) { - return cloneBinaryObject(object); - } - - if (!isPlainObject(object)) { - return object; // don't clone objects like Workers - } - - newObject = {}; - for (i in object) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(object, i)) { - var value = clone$1(object[i]); - if (typeof value !== 'undefined') { - newObject[i] = value; - } - } - } - return newObject; -} - -var log = debug('pouchdb:api'); - -// like underscore/lodash _.pick() -function pick(obj, arr) { - var res = {}; - for (var i = 0, len = arr.length; i < len; i++) { - var prop = arr[i]; - if (prop in obj) { - res[prop] = obj[prop]; - } - } - return res; -} - -function isChromeApp() { - return (typeof chrome !== "undefined" && - typeof chrome.storage !== "undefined" && - typeof chrome.storage.local !== "undefined"); -} - -var hasLocal; - -if (isChromeApp()) { - hasLocal = false; -} else { - try { - localStorage.setItem('_pouch_check_localstorage', 1); - hasLocal = !!localStorage.getItem('_pouch_check_localstorage'); - } catch (e) { - hasLocal = false; - } -} - -function hasLocalStorage() { - return hasLocal; -} - -inherits(Changes, events.EventEmitter); - -/* istanbul ignore next */ -function attachBrowserEvents(self) { - if (isChromeApp()) { - chrome.storage.onChanged.addListener(function (e) { - // make sure it's event addressed to us - if (e.db_name != null) { - //object only has oldValue, newValue members - self.emit(e.dbName.newValue); - } - }); - } else if (hasLocalStorage()) { - if (typeof addEventListener !== 'undefined') { - addEventListener("storage", function (e) { - self.emit(e.key); - }); - } else { // old IE - window.attachEvent("storage", function (e) { - self.emit(e.key); - }); - } - } -} - -function Changes() { - events.EventEmitter.call(this); - this._listeners = {}; - - attachBrowserEvents(this); -} -Changes.prototype.addListener = function (dbName, id, db, opts) { - /* istanbul ignore if */ - if (this._listeners[id]) { - return; - } - var self = this; - var inprogress = false; - function eventFunction() { - /* istanbul ignore if */ - if (!self._listeners[id]) { - return; - } - if (inprogress) { - inprogress = 'waiting'; - return; - } - inprogress = true; - var changesOpts = pick(opts, [ - 'style', 'include_docs', 'attachments', 'conflicts', 'filter', - 'doc_ids', 'view', 'since', 'query_params', 'binary' - ]); - - /* istanbul ignore next */ - function onError() { - inprogress = false; - } - - db.changes(changesOpts).on('change', function (c) { - if (c.seq > opts.since && !opts.cancelled) { - opts.since = c.seq; - opts.onChange(c); - } - }).on('complete', function () { - if (inprogress === 'waiting') { - setTimeout(function (){ - eventFunction(); - },0); - } - inprogress = false; - }).on('error', onError); - } - this._listeners[id] = eventFunction; - this.on(dbName, eventFunction); -}; - -Changes.prototype.removeListener = function (dbName, id) { - /* istanbul ignore if */ - if (!(id in this._listeners)) { - return; - } - events.EventEmitter.prototype.removeListener.call(this, dbName, - this._listeners[id]); - delete this._listeners[id]; -}; - - -/* istanbul ignore next */ -Changes.prototype.notifyLocalWindows = function (dbName) { - //do a useless change on a storage thing - //in order to get other windows's listeners to activate - if (isChromeApp()) { - chrome.storage.local.set({dbName: dbName}); - } else if (hasLocalStorage()) { - localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; - } -}; - -Changes.prototype.notify = function (dbName) { - this.emit(dbName); - this.notifyLocalWindows(dbName); -}; - -function guardedConsole(method) { - /* istanbul ignore else */ - if (console !== 'undefined' && method in console) { - var args = Array.prototype.slice.call(arguments, 1); - console[method].apply(console, args); - } -} - -inherits(PouchError, Error); - -function PouchError(opts) { - Error.call(this, opts.reason); - this.status = opts.status; - this.name = opts.error; - this.message = opts.reason; - this.error = true; -} - -PouchError.prototype.toString = function () { - return JSON.stringify({ - status: this.status, - name: this.name, - message: this.message, - reason: this.reason - }); -}; - -var UNAUTHORIZED = new PouchError({ - status: 401, - error: 'unauthorized', - reason: "Name or password is incorrect." -}); - -var MISSING_BULK_DOCS = new PouchError({ - status: 400, - error: 'bad_request', - reason: "Missing JSON list of 'docs'" -}); - -var MISSING_DOC = new PouchError({ - status: 404, - error: 'not_found', - reason: 'missing' -}); - -var REV_CONFLICT = new PouchError({ - status: 409, - error: 'conflict', - reason: 'Document update conflict' -}); - -var INVALID_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: '_id field must contain a string' -}); - -var MISSING_ID = new PouchError({ - status: 412, - error: 'missing_id', - reason: '_id is required for puts' -}); - -var RESERVED_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Only reserved document ids may start with underscore.' -}); - -var NOT_OPEN = new PouchError({ - status: 412, - error: 'precondition_failed', - reason: 'Database not open' -}); - -var UNKNOWN_ERROR = new PouchError({ - status: 500, - error: 'unknown_error', - reason: 'Database encountered an unknown error' -}); - -var BAD_ARG = new PouchError({ - status: 500, - error: 'badarg', - reason: 'Some query argument is invalid' -}); - -var INVALID_REQUEST = new PouchError({ - status: 400, - error: 'invalid_request', - reason: 'Request was invalid' -}); - -var QUERY_PARSE_ERROR = new PouchError({ - status: 400, - error: 'query_parse_error', - reason: 'Some query parameter is invalid' -}); - -var DOC_VALIDATION = new PouchError({ - status: 500, - error: 'doc_validation', - reason: 'Bad special document member' -}); - -var BAD_REQUEST = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Something wrong with the request' -}); - -var NOT_AN_OBJECT = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Document must be a JSON object' -}); - -var DB_MISSING = new PouchError({ - status: 404, - error: 'not_found', - reason: 'Database not found' -}); - -var IDB_ERROR = new PouchError({ - status: 500, - error: 'indexed_db_went_bad', - reason: 'unknown' -}); - -var WSQ_ERROR = new PouchError({ - status: 500, - error: 'web_sql_went_bad', - reason: 'unknown' -}); - -var LDB_ERROR = new PouchError({ - status: 500, - error: 'levelDB_went_went_bad', - reason: 'unknown' -}); - -var FORBIDDEN = new PouchError({ - status: 403, - error: 'forbidden', - reason: 'Forbidden by design doc validate_doc_update function' -}); - -var INVALID_REV = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Invalid rev format' -}); - -var FILE_EXISTS = new PouchError({ - status: 412, - error: 'file_exists', - reason: 'The database could not be created, the file already exists.' -}); - -var MISSING_STUB = new PouchError({ - status: 412, - error: 'missing_stub' -}); - -var INVALID_URL = new PouchError({ - status: 413, - error: 'invalid_url', - reason: 'Provided URL is invalid' -}); - -function createError(error, reason) { - function CustomPouchError(reason) { - // inherit error properties from our parent error manually - // so as to allow proper JSON parsing. - /* jshint ignore:start */ - for (var p in error) { - if (typeof error[p] !== 'function') { - this[p] = error[p]; - } - } - /* jshint ignore:end */ - if (reason !== undefined) { - this.reason = reason; - } - } - CustomPouchError.prototype = PouchError.prototype; - return new CustomPouchError(reason); -} - -function tryFilter(filter, doc, req) { - try { - return !filter(doc, req); - } catch (err) { - var msg = 'Filter function threw: ' + err.toString(); - return createError(BAD_REQUEST, msg); - } -} - -function filterChange(opts) { - var req = {}; - var hasFilter = opts.filter && typeof opts.filter === 'function'; - req.query = opts.query_params; - - return function filter(change) { - if (!change.doc) { - // CSG sends events on the changes feed that don't have documents, - // this hack makes a whole lot of existing code robust. - change.doc = {}; - } - - var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); - - if (typeof filterReturn === 'object') { - return filterReturn; - } - - if (filterReturn) { - return false; - } - - if (!opts.include_docs) { - delete change.doc; - } else if (!opts.attachments) { - for (var att in change.doc._attachments) { - /* istanbul ignore else */ - if (change.doc._attachments.hasOwnProperty(att)) { - change.doc._attachments[att].stub = true; - } - } - } - return true; - }; -} - -// shim for Function.prototype.name, -// for browsers that don't support it like IE - -/* istanbul ignore next */ -function f() {} - -var hasName = f.name; -var res; - -// We dont run coverage in IE -/* istanbul ignore else */ -if (hasName) { - res = function (fun) { - return fun.name; - }; -} else { - res = function (fun) { - return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; - }; -} - -var functionName = res; - -// Determine id an ID is valid -// - invalid IDs begin with an underescore that does not begin '_design' or -// '_local' -// - any other string value is a valid id -// Returns the specific error object for each case -function invalidIdError(id) { - var err; - if (!id) { - err = createError(MISSING_ID); - } else if (typeof id !== 'string') { - err = createError(INVALID_ID); - } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { - err = createError(RESERVED_ID); - } - if (err) { - throw err; - } -} - -// BEGIN Math.uuid.js - -/*! -Math.uuid.js (v1.4) -http://www.broofa.com -mailto:robert@broofa.com - -Copyright (c) 2010 Robert Kieffer -Dual licensed under the MIT and GPL licenses. -*/ - -/* - * Generate a random uuid. - * - * USAGE: Math.uuid(length, radix) - * length - the desired number of characters - * radix - the number of allowable values for each character. - * - * EXAMPLES: - * // No arguments - returns RFC4122, version 4 ID - * >>> Math.uuid() - * "92329D39-6F5C-4520-ABFC-AAB64544E172" - * - * // One argument - returns ID of the specified length - * >>> Math.uuid(15) // 15 character ID (default base=62) - * "VcydxgltxrVZSTV" - * - * // Two arguments - returns ID of the specified length, and radix. - * // (Radix must be <= 62) - * >>> Math.uuid(8, 2) // 8 character ID (base=2) - * "01001010" - * >>> Math.uuid(8, 10) // 8 character ID (base=10) - * "47473046" - * >>> Math.uuid(8, 16) // 8 character ID (base=16) - * "098F4D35" - */ -var chars = ( - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + - 'abcdefghijklmnopqrstuvwxyz' -).split(''); -function getValue(radix) { - return 0 | Math.random() * radix; -} -function uuid(len, radix) { - radix = radix || chars.length; - var out = ''; - var i = -1; - - if (len) { - // Compact form - while (++i < len) { - out += chars[getValue(radix)]; - } - return out; - } - // rfc4122, version 4 form - // Fill in random data. At i==19 set the high bits of clock sequence as - // per rfc4122, sec. 4.1.5 - while (++i < 36) { - switch (i) { - case 8: - case 13: - case 18: - case 23: - out += '-'; - break; - case 19: - out += chars[(getValue(16) & 0x3) | 0x8]; - break; - default: - out += chars[getValue(16)]; - } - } - - return out; -} - -function toObject(array) { - return array.reduce(function (obj, item) { - obj[item] = true; - return obj; - }, {}); -} -// List of top level reserved words for doc -var reservedWords = toObject([ - '_id', - '_rev', - '_attachments', - '_deleted', - '_revisions', - '_revs_info', - '_conflicts', - '_deleted_conflicts', - '_local_seq', - '_rev_tree', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats', - // Specific to Couchbase Sync Gateway - '_removed' -]); - -// List of reserved words that should end up the document -var dataWords = toObject([ - '_attachments', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats' -]); - -function parseRevisionInfo(rev) { - if (!/^\d+\-./.test(rev)) { - return createError(INVALID_REV); - } - var idx = rev.indexOf('-'); - var left = rev.substring(0, idx); - var right = rev.substring(idx + 1); - return { - prefix: parseInt(left, 10), - id: right - }; -} - -function makeRevTreeFromRevisions(revisions, opts) { - var pos = revisions.start - revisions.ids.length + 1; - - var revisionIds = revisions.ids; - var ids = [revisionIds[0], opts, []]; - - for (var i = 1, len = revisionIds.length; i < len; i++) { - ids = [revisionIds[i], {status: 'missing'}, [ids]]; - } - - return [{ - pos: pos, - ids: ids - }]; -} - -// Preprocess documents, parse their revisions, assign an id and a -// revision for new writes that are missing them, etc -function parseDoc(doc, newEdits) { - - var nRevNum; - var newRevId; - var revInfo; - var opts = {status: 'available'}; - if (doc._deleted) { - opts.deleted = true; - } - - if (newEdits) { - if (!doc._id) { - doc._id = uuid(); - } - newRevId = uuid(32, 16).toLowerCase(); - if (doc._rev) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - doc._rev_tree = [{ - pos: revInfo.prefix, - ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]] - }]; - nRevNum = revInfo.prefix + 1; - } else { - doc._rev_tree = [{ - pos: 1, - ids : [newRevId, opts, []] - }]; - nRevNum = 1; - } - } else { - if (doc._revisions) { - doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); - nRevNum = doc._revisions.start; - newRevId = doc._revisions.ids[0]; - } - if (!doc._rev_tree) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - nRevNum = revInfo.prefix; - newRevId = revInfo.id; - doc._rev_tree = [{ - pos: nRevNum, - ids: [newRevId, opts, []] - }]; - } - } - - invalidIdError(doc._id); - - doc._rev = nRevNum + '-' + newRevId; - - var result = {metadata : {}, data : {}}; - for (var key in doc) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(doc, key)) { - var specialKey = key[0] === '_'; - if (specialKey && !reservedWords[key]) { - var error = createError(DOC_VALIDATION, key); - error.message = DOC_VALIDATION.message + ': ' + key; - throw error; - } else if (specialKey && !dataWords[key]) { - result.metadata[key.slice(1)] = doc[key]; - } else { - result.data[key] = doc[key]; - } - } - } - return result; -} - -// We fetch all leafs of the revision tree, and sort them based on tree length -// and whether they were deleted, undeleted documents with the longest revision -// tree (most edits) win -// The final sort algorithm is slightly documented in a sidebar here: -// http://guide.couchdb.org/draft/conflicts.html -function winningRev(metadata) { - var winningId; - var winningPos; - var winningDeleted; - var toVisit = metadata.rev_tree.slice(); - var node; - while ((node = toVisit.pop())) { - var tree = node.ids; - var branches = tree[2]; - var pos = node.pos; - if (branches.length) { // non-leaf - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i]}); - } - continue; - } - var deleted = !!tree[1].deleted; - var id = tree[0]; - // sort by deleted, then pos, then id - if (!winningId || (winningDeleted !== deleted ? winningDeleted : - winningPos !== pos ? winningPos < pos : winningId < id)) { - winningId = id; - winningPos = pos; - winningDeleted = deleted; - } - } - - return winningPos + '-' + winningId; -} - -// Pretty much all below can be combined into a higher order function to -// traverse revisions -// The return value from the callback will be passed as context to all -// children of that node -function traverseRevTree(revs, callback) { - var toVisit = revs.slice(); - - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var branches = tree[2]; - var newCtx = - callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx}); - } - } -} - -function sortByPos(a, b) { - return a.pos - b.pos; -} - -function collectLeaves(revs) { - var leaves = []; - traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) { - if (isLeaf) { - leaves.push({rev: pos + "-" + id, pos: pos, opts: opts}); - } - }); - leaves.sort(sortByPos).reverse(); - for (var i = 0, len = leaves.length; i < len; i++) { - delete leaves[i].pos; - } - return leaves; -} - -// returns revs of all conflicts that is leaves such that -// 1. are not deleted and -// 2. are different than winning revision -function collectConflicts(metadata) { - var win = winningRev(metadata); - var leaves = collectLeaves(metadata.rev_tree); - var conflicts = []; - for (var i = 0, len = leaves.length; i < len; i++) { - var leaf = leaves[i]; - if (leaf.rev !== win && !leaf.opts.deleted) { - conflicts.push(leaf.rev); - } - } - return conflicts; -} - -// compact a tree by marking its non-leafs as missing, -// and return a list of revs to delete -function compactTree(metadata) { - var revs = []; - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - if (opts.status === 'available' && !isLeaf) { - revs.push(pos + '-' + revHash); - opts.status = 'missing'; - } - }); - return revs; -} - -// build up a list of all the paths to the leafs in this revision tree -function rootToLeaf(revs) { - var paths = []; - var toVisit = revs.slice(); - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var id = tree[0]; - var opts = tree[1]; - var branches = tree[2]; - var isLeaf = branches.length === 0; - - var history = node.history ? node.history.slice() : []; - history.push({id: id, opts: opts}); - if (isLeaf) { - paths.push({pos: (pos + 1 - history.length), ids: history}); - } - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], history: history}); - } - } - return paths.reverse(); -} - -// for a better overview of what this is doing, read: -// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl -// -// But for a quick intro, CouchDB uses a revision tree to store a documents -// history, A -> B -> C, when a document has conflicts, that is a branch in the -// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format -// -// KeyTree = [Path ... ] -// Path = {pos: position_from_root, ids: Tree} -// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []] - -function sortByPos$1(a, b) { - return a.pos - b.pos; -} - -// classic binary search -function binarySearch(arr, item, comparator) { - var low = 0; - var high = arr.length; - var mid; - while (low < high) { - mid = (low + high) >>> 1; - if (comparator(arr[mid], item) < 0) { - low = mid + 1; - } else { - high = mid; - } - } - return low; -} - -// assuming the arr is sorted, insert the item in the proper place -function insertSorted(arr, item, comparator) { - var idx = binarySearch(arr, item, comparator); - arr.splice(idx, 0, item); -} - -// Turn a path as a flat array into a tree with a single branch. -// If any should be stemmed from the beginning of the array, that's passed -// in as the second argument -function pathToTree(path, numStemmed) { - var root; - var leaf; - for (var i = numStemmed, len = path.length; i < len; i++) { - var node = path[i]; - var currentLeaf = [node.id, node.opts, []]; - if (leaf) { - leaf[2].push(currentLeaf); - leaf = currentLeaf; - } else { - root = leaf = currentLeaf; - } - } - return root; -} - -// compare the IDs of two trees -function compareTree(a, b) { - return a[0] < b[0] ? -1 : 1; -} - -// Merge two trees together -// The roots of tree1 and tree2 must be the same revision -function mergeTree(in_tree1, in_tree2) { - var queue = [{tree1: in_tree1, tree2: in_tree2}]; - var conflicts = false; - while (queue.length > 0) { - var item = queue.pop(); - var tree1 = item.tree1; - var tree2 = item.tree2; - - if (tree1[1].status || tree2[1].status) { - tree1[1].status = - (tree1[1].status === 'available' || - tree2[1].status === 'available') ? 'available' : 'missing'; - } - - for (var i = 0; i < tree2[2].length; i++) { - if (!tree1[2][0]) { - conflicts = 'new_leaf'; - tree1[2][0] = tree2[2][i]; - continue; - } - - var merged = false; - for (var j = 0; j < tree1[2].length; j++) { - if (tree1[2][j][0] === tree2[2][i][0]) { - queue.push({tree1: tree1[2][j], tree2: tree2[2][i]}); - merged = true; - } - } - if (!merged) { - conflicts = 'new_branch'; - insertSorted(tree1[2], tree2[2][i], compareTree); - } - } - } - return {conflicts: conflicts, tree: in_tree1}; -} - -function doMerge(tree, path, dontExpand) { - var restree = []; - var conflicts = false; - var merged = false; - var res; - - if (!tree.length) { - return {tree: [path], conflicts: 'new_leaf'}; - } - - for (var i = 0, len = tree.length; i < len; i++) { - var branch = tree[i]; - if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { - // Paths start at the same position and have the same root, so they need - // merged - res = mergeTree(branch.ids, path.ids); - restree.push({pos: branch.pos, ids: res.tree}); - conflicts = conflicts || res.conflicts; - merged = true; - } else if (dontExpand !== true) { - // The paths start at a different position, take the earliest path and - // traverse up until it as at the same point from root as the path we - // want to merge. If the keys match we return the longer path with the - // other merged After stemming we dont want to expand the trees - - var t1 = branch.pos < path.pos ? branch : path; - var t2 = branch.pos < path.pos ? path : branch; - var diff = t2.pos - t1.pos; - - var candidateParents = []; - - var trees = []; - trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null}); - while (trees.length > 0) { - var item = trees.pop(); - if (item.diff === 0) { - if (item.ids[0] === t2.ids[0]) { - candidateParents.push(item); - } - continue; - } - var elements = item.ids[2]; - for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { - trees.push({ - ids: elements[j], - diff: item.diff - 1, - parent: item.ids, - parentIdx: j - }); - } - } - - var el = candidateParents[0]; - - if (!el) { - restree.push(branch); - } else { - res = mergeTree(el.ids, t2.ids); - el.parent[2][el.parentIdx] = res.tree; - restree.push({pos: t1.pos, ids: t1.ids}); - conflicts = conflicts || res.conflicts; - merged = true; - } - } else { - restree.push(branch); - } - } - - // We didnt find - if (!merged) { - restree.push(path); - } - - restree.sort(sortByPos$1); - - return { - tree: restree, - conflicts: conflicts || 'internal_node' - }; -} - -// To ensure we dont grow the revision tree infinitely, we stem old revisions -function stem(tree, depth) { - // First we break out the tree into a complete list of root to leaf paths - var paths = rootToLeaf(tree); - var maybeStem = {}; - - var result; - for (var i = 0, len = paths.length; i < len; i++) { - // Then for each path, we cut off the start of the path based on the - // `depth` to stem to, and generate a new set of flat trees - var path = paths[i]; - var stemmed = path.ids; - var numStemmed = Math.max(0, stemmed.length - depth); - var stemmedNode = { - pos: path.pos + numStemmed, - ids: pathToTree(stemmed, numStemmed) - }; - - for (var s = 0; s < numStemmed; s++) { - var rev = (path.pos + s) + '-' + stemmed[s].id; - maybeStem[rev] = true; - } - - // Then we remerge all those flat trees together, ensuring that we dont - // connect trees that would go beyond the depth limit - if (result) { - result = doMerge(result, stemmedNode, true).tree; - } else { - result = [stemmedNode]; - } - } - - traverseRevTree(result, function (isLeaf, pos, revHash) { - // some revisions may have been removed in a branch but not in another - delete maybeStem[pos + '-' + revHash]; - }); - - return { - tree: result, - revs: Object.keys(maybeStem) - }; -} - -function merge(tree, path, depth) { - var newTree = doMerge(tree, path); - var stemmed = stem(newTree.tree, depth); - return { - tree: stemmed.tree, - stemmedRevs: stemmed.revs, - conflicts: newTree.conflicts - }; -} - -// return true if a rev exists in the rev tree, false otherwise -function revExists(revs, rev) { - var toVisit = revs.slice(); - var splitRev = rev.split('-'); - var targetPos = parseInt(splitRev[0], 10); - var targetId = splitRev[1]; - - var node; - while ((node = toVisit.pop())) { - if (node.pos === targetPos && node.ids[0] === targetId) { - return true; - } - var branches = node.ids[2]; - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: node.pos + 1, ids: branches[i]}); - } - } - return false; -} - -function getTrees(node) { - return node.ids; -} - -// check if a specific revision of a doc has been deleted -// - metadata: the metadata object from the doc store -// - rev: (optional) the revision to check. defaults to winning revision -function isDeleted(metadata, rev) { - if (!rev) { - rev = winningRev(metadata); - } - var id = rev.substring(rev.indexOf('-') + 1); - var toVisit = metadata.rev_tree.map(getTrees); - - var tree; - while ((tree = toVisit.pop())) { - if (tree[0] === id) { - return !!tree[1].deleted; - } - toVisit = toVisit.concat(tree[2]); - } -} - -function isLocalId(id) { - return (/^_local/).test(id); -} - -var atob$1 = function (str) { - return atob(str); -}; - -var btoa$1 = function (str) { - return btoa(str); -}; - -// Abstracts constructing a Blob object, so it also works in older -// browsers that don't support the native Blob constructor (e.g. -// old QtWebKit versions, Android < 4.4). -function createBlob(parts, properties) { - /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ - parts = parts || []; - properties = properties || {}; - try { - return new Blob(parts, properties); - } catch (e) { - if (e.name !== "TypeError") { - throw e; - } - var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : - typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : - typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : - WebKitBlobBuilder; - var builder = new Builder(); - for (var i = 0; i < parts.length; i += 1) { - builder.append(parts[i]); - } - return builder.getBlob(properties.type); - } -} - -// From http://stackoverflow.com/questions/14967647/ (continues on next line) -// encode-decode-image-with-base64-breaks-image (2013-04-21) -function binaryStringToArrayBuffer(bin) { - var length = bin.length; - var buf = new ArrayBuffer(length); - var arr = new Uint8Array(buf); - for (var i = 0; i < length; i++) { - arr[i] = bin.charCodeAt(i); - } - return buf; -} - -function binStringToBluffer(binString, type) { - return createBlob([binaryStringToArrayBuffer(binString)], {type: type}); -} - -//Can't find original post, but this is close -//http://stackoverflow.com/questions/6965107/ (continues on next line) -//converting-between-strings-and-arraybuffers -function arrayBufferToBinaryString(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var length = bytes.byteLength; - for (var i = 0; i < length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return binary; -} - -// shim for browsers that don't support it -function readAsBinaryString(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(arrayBufferToBinaryString( - new FileReaderSync().readAsArrayBuffer(blob))); - } - - var reader = new FileReader(); - var hasBinaryString = typeof reader.readAsBinaryString === 'function'; - reader.onloadend = function (e) { - var result = e.target.result || ''; - if (hasBinaryString) { - return callback(result); - } - callback(arrayBufferToBinaryString(result)); - }; - if (hasBinaryString) { - reader.readAsBinaryString(blob); - } else { - reader.readAsArrayBuffer(blob); - } -} - -// simplified API. universal browser support is assumed -function readAsArrayBuffer(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker: - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(new FileReaderSync().readAsArrayBuffer(blob)); - } - - var reader = new FileReader(); - reader.onloadend = function (e) { - var result = e.target.result || new ArrayBuffer(0); - callback(result); - }; - reader.readAsArrayBuffer(blob); -} - -var setImmediateShim = global.setImmediate || global.setTimeout; -var MD5_CHUNK_SIZE = 32768; - -function rawToBase64(raw) { - return btoa$1(raw); -} - -function sliceBlob(blob, start, end) { - if (blob.webkitSlice) { - return blob.webkitSlice(start, end); - } - return blob.slice(start, end); -} - -function appendBlob(buffer, blob, start, end, callback) { - if (start > 0 || end < blob.size) { - // only slice blob if we really need to - blob = sliceBlob(blob, start, end); - } - readAsArrayBuffer(blob, function (arrayBuffer) { - buffer.append(arrayBuffer); - callback(); - }); -} - -function appendString(buffer, string, start, end, callback) { - if (start > 0 || end < string.length) { - // only create a substring if we really need to - string = string.substring(start, end); - } - buffer.appendBinary(string); - callback(); -} - -function binaryMd5(data, callback) { - var inputIsString = typeof data === 'string'; - var len = inputIsString ? data.length : data.size; - var chunkSize = Math.min(MD5_CHUNK_SIZE, len); - var chunks = Math.ceil(len / chunkSize); - var currentChunk = 0; - var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer(); - - var append = inputIsString ? appendString : appendBlob; - - function next() { - setImmediateShim(loadNextChunk); - } - - function done() { - var raw = buffer.end(true); - var base64 = rawToBase64(raw); - callback(base64); - buffer.destroy(); - } - - function loadNextChunk() { - var start = currentChunk * chunkSize; - var end = start + chunkSize; - currentChunk++; - if (currentChunk < chunks) { - append(buffer, data, start, end, next); - } else { - append(buffer, data, start, end, done); - } - } - loadNextChunk(); -} - -function updateDoc(revLimit, prev, docInfo, results, - i, cb, writeDoc, newEdits) { - - if (revExists(prev.rev_tree, docInfo.metadata.rev)) { - results[i] = docInfo; - return cb(); - } - - // sometimes this is pre-calculated. historically not always - var previousWinningRev = prev.winningRev || winningRev(prev); - var previouslyDeleted = 'deleted' in prev ? prev.deleted : - isDeleted(prev, previousWinningRev); - var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted : - isDeleted(docInfo.metadata); - var isRoot = /^1-/.test(docInfo.metadata.rev); - - if (previouslyDeleted && !deleted && newEdits && isRoot) { - var newDoc = docInfo.data; - newDoc._rev = previousWinningRev; - newDoc._id = docInfo.metadata.id; - docInfo = parseDoc(newDoc, newEdits); - } - - var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); - - var inConflict = newEdits && (((previouslyDeleted && deleted) || - (!previouslyDeleted && merged.conflicts !== 'new_leaf') || - (previouslyDeleted && !deleted && merged.conflicts === 'new_branch'))); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[i] = err; - return cb(); - } - - var newRev = docInfo.metadata.rev; - docInfo.metadata.rev_tree = merged.tree; - docInfo.stemmedRevs = merged.stemmedRevs || []; - /* istanbul ignore else */ - if (prev.rev_map) { - docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb - } - - // recalculate - var winningRev$$ = winningRev(docInfo.metadata); - var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$); - - // calculate the total number of documents that were added/removed, - // from the perspective of total_rows/doc_count - var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 : - previouslyDeleted < winningRevIsDeleted ? -1 : 1; - - var newRevIsDeleted; - if (newRev === winningRev$$) { - // if the new rev is the same as the winning rev, we can reuse that value - newRevIsDeleted = winningRevIsDeleted; - } else { - // if they're not the same, then we need to recalculate - newRevIsDeleted = isDeleted(docInfo.metadata, newRev); - } - - writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted, - true, delta, i, cb); -} - -function rootIsMissing(docInfo) { - return docInfo.metadata.rev_tree[0].ids[1].status === 'missing'; -} - -function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, - writeDoc, opts, overallCallback) { - - // Default to 1000 locally - revLimit = revLimit || 1000; - - function insertDoc(docInfo, resultsIdx, callback) { - // Cant insert new deleted documents - var winningRev$$ = winningRev(docInfo.metadata); - var deleted = isDeleted(docInfo.metadata, winningRev$$); - if ('was_delete' in opts && deleted) { - results[resultsIdx] = createError(MISSING_DOC, 'deleted'); - return callback(); - } - - // 4712 - detect whether a new document was inserted with a _rev - var inConflict = newEdits && rootIsMissing(docInfo); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[resultsIdx] = err; - return callback(); - } - - var delta = deleted ? 0 : 1; - - writeDoc(docInfo, winningRev$$, deleted, deleted, false, - delta, resultsIdx, callback); - } - - var newEdits = opts.new_edits; - var idsToDocs = new _Map(); - - var docsDone = 0; - var docsToDo = docInfos.length; - - function checkAllDocsDone() { - if (++docsDone === docsToDo && overallCallback) { - overallCallback(); - } - } - - docInfos.forEach(function (currentDoc, resultsIdx) { - - if (currentDoc._id && isLocalId(currentDoc._id)) { - var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal'; - api[fun](currentDoc, {ctx: tx}, function (err, res) { - results[resultsIdx] = err || res; - checkAllDocsDone(); - }); - return; - } - - var id = currentDoc.metadata.id; - if (idsToDocs.has(id)) { - docsToDo--; // duplicate - idsToDocs.get(id).push([currentDoc, resultsIdx]); - } else { - idsToDocs.set(id, [[currentDoc, resultsIdx]]); - } - }); - - // in the case of new_edits, the user can provide multiple docs - // with the same id. these need to be processed sequentially - idsToDocs.forEach(function (docs, id) { - var numDone = 0; - - function docWritten() { - if (++numDone < docs.length) { - nextDoc(); - } else { - checkAllDocsDone(); - } - } - function nextDoc() { - var value = docs[numDone]; - var currentDoc = value[0]; - var resultsIdx = value[1]; - - if (fetchedDocs.has(id)) { - updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results, - resultsIdx, docWritten, writeDoc, newEdits); - } else { - // Ensure stemming applies to new writes as well - var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); - currentDoc.metadata.rev_tree = merged.tree; - currentDoc.stemmedRevs = merged.stemmedRevs || []; - insertDoc(currentDoc, resultsIdx, docWritten); - } - } - nextDoc(); - }); -} - -function slowJsonParse(str) { - try { - return JSON.parse(str); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.parse(str); - } -} - -function safeJsonParse(str) { - // try/catch is deoptimized in V8, leading to slower - // times than we'd like to have. Most documents are _not_ - // huge, and do not require a slower code path just to parse them. - // We can be pretty sure that a document under 50000 characters - // will not be so deeply nested as to throw a stack overflow error - // (depends on the engine and available memory, though, so this is - // just a hunch). 50000 was chosen based on the average length - // of this string in our test suite, to try to find a number that covers - // most of our test cases (26 over this size, 26378 under it). - if (str.length < 50000) { - return JSON.parse(str); - } - return slowJsonParse(str); -} - -function safeJsonStringify(json) { - try { - return JSON.stringify(json); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.stringify(json); - } -} - -function readAsBlobOrBuffer(storedObject, type) { - // In the browser, we've stored a binary string. This now comes back as a - // browserified Node-style Buffer (implemented as a typed array), - // but we want a Blob instead. - var byteArray = new Uint8Array(storedObject); - return createBlob([byteArray], {type: type}); -} - -// In the browser, we store a binary string -function prepareAttachmentForStorage(attData, cb) { - readAsBinaryString(attData, cb); -} - -function createEmptyBlobOrBuffer(type) { - return createBlob([''], {type: type}); -} - -// similar to an idb or websql transaction object -// designed to be passed around. basically just caches -// things in-memory and then does a big batch() operation -// when you're done - -function getCacheFor(transaction, store) { - var prefix = store.prefix()[0]; - var cache = transaction._cache; - var subCache = cache.get(prefix); - if (!subCache) { - subCache = new _Map(); - cache.set(prefix, subCache); - } - return subCache; -} - -function LevelTransaction() { - this._batch = []; - this._cache = new _Map(); -} - -LevelTransaction.prototype.get = function (store, key, callback) { - var cache = getCacheFor(this, store); - var exists = cache.get(key); - if (exists) { - return process.nextTick(function () { - callback(null, exists); - }); - } else if (exists === null) { // deleted marker - /* istanbul ignore next */ - return process.nextTick(function () { - callback({name: 'NotFoundError'}); - }); - } - store.get(key, function (err, res) { - if (err) { - /* istanbul ignore else */ - if (err.name === 'NotFoundError') { - cache.set(key, null); - } - return callback(err); - } - cache.set(key, res); - callback(null, res); - }); -}; - -LevelTransaction.prototype.batch = function (batch) { - for (var i = 0, len = batch.length; i < len; i++) { - var operation = batch[i]; - - var cache = getCacheFor(this, operation.prefix); - - if (operation.type === 'put') { - cache.set(operation.key, operation.value); - } else { - cache.set(operation.key, null); - } - } - this._batch = this._batch.concat(batch); -}; - -LevelTransaction.prototype.execute = function (db, callback) { - - var keys = new _Set(); - var uniqBatches = []; - - // remove duplicates; last one wins - for (var i = this._batch.length - 1; i >= 0; i--) { - var operation = this._batch[i]; - var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key; - if (keys.has(lookupKey)) { - continue; - } - keys.add(lookupKey); - uniqBatches.push(operation); - } - - db.batch(uniqBatches, callback); -}; - -var DOC_STORE = 'document-store'; -var BY_SEQ_STORE = 'by-sequence'; -var ATTACHMENT_STORE = 'attach-store'; -var BINARY_STORE = 'attach-binary-store'; -var LOCAL_STORE = 'local-store'; -var META_STORE = 'meta-store'; - -// leveldb barks if we try to open a db multiple times -// so we cache opened connections here for initstore() -var dbStores = new _Map(); - -// store the value of update_seq in the by-sequence store the key name will -// never conflict, since the keys in the by-sequence store are integers -var UPDATE_SEQ_KEY = '_local_last_update_seq'; -var DOC_COUNT_KEY = '_local_doc_count'; -var UUID_KEY = '_local_uuid'; - -var MD5_PREFIX = 'md5-'; - -var safeJsonEncoding = { - encode: safeJsonStringify, - decode: safeJsonParse, - buffer: false, - type: 'cheap-json' -}; - -var levelChanges = new Changes(); - -// winningRev and deleted are performance-killers, but -// in newer versions of PouchDB, they are cached on the metadata -function getWinningRev(metadata) { - return 'winningRev' in metadata ? - metadata.winningRev : winningRev(metadata); -} - -function getIsDeleted(metadata, winningRev) { - return 'deleted' in metadata ? - metadata.deleted : isDeleted(metadata, winningRev); -} - -function fetchAttachment(att, stores, opts) { - var type = att.content_type; - return new PouchPromise(function (resolve, reject) { - stores.binaryStore.get(att.digest, function (err, buffer) { - var data; - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return reject(err); - } else { - // empty - if (!opts.binary) { - data = ''; - } else { - data = binStringToBluffer('', type); - } - } - } else { // non-empty - if (opts.binary) { - data = readAsBlobOrBuffer(buffer, type); - } else { - data = buffer.toString('base64'); - } - } - delete att.stub; - delete att.length; - att.data = data; - resolve(); - }); - }); -} - -function fetchAttachments(results, stores, opts) { - var atts = []; - results.forEach(function (row) { - if (!(row.doc && row.doc._attachments)) { - return; - } - var attNames = Object.keys(row.doc._attachments); - attNames.forEach(function (attName) { - var att = row.doc._attachments[attName]; - if (!('data' in att)) { - atts.push(att); - } - }); - }); - - return PouchPromise.all(atts.map(function (att) { - return fetchAttachment(att, stores, opts); - })); -} - -function LevelPouch(opts, callback) { - opts = clone$1(opts); - var api = this; - var instanceId; - var stores = {}; - var revLimit = opts.revs_limit; - var db; - var name = opts.name; - // TODO: this is undocumented and unused probably - /* istanbul ignore else */ - if (typeof opts.createIfMissing === 'undefined') { - opts.createIfMissing = true; - } - - var leveldown = opts.db; - - var dbStore; - var leveldownName = functionName(leveldown); - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - dbStore = new _Map(); - dbStores.set(leveldownName, dbStore); - } - if (dbStore.has(name)) { - db = dbStore.get(name); - afterDBCreated(); - } else { - dbStore.set(name, sublevelPouch(levelup(name, opts, function (err) { - /* istanbul ignore if */ - if (err) { - dbStore.delete(name); - return callback(err); - } - db = dbStore.get(name); - db._docCount = -1; - db._queue = new Deque(); - /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); - } else { - afterDBCreated(); - } - }))); - } - - function afterDBCreated() { - stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding}); - stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'}); - stores.attachmentStore = - db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'}); - stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); - stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); - stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); - }); - }); - }); - }); - }); - } - - function countDocs(callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(new Error('database is closed')); - } - return callback(null, db._docCount); // use cached value - } - - api.type = function () { - return 'leveldb'; - }; - - api._id = function (callback) { - callback(null, instanceId); - }; - - api._info = function (callback) { - var res = { - doc_count: db._docCount, - update_seq: db._updateSeq, - backend_adapter: functionName(leveldown) - }; - return process.nextTick(function () { - callback(null, res); - }); - }; - - function tryCode(fun, args) { - try { - fun.apply(null, args); - } catch (err) { - args[args.length - 1](err); - } - } - - function executeNext() { - var firstTask = db._queue.peekFront(); - - if (firstTask.type === 'read') { - runReadOperation(firstTask); - } else { // write, only do one at a time - runWriteOperation(firstTask); - } - } - - function runReadOperation(firstTask) { - // do multiple reads at once simultaneously, because it's safe - - var readTasks = [firstTask]; - var i = 1; - var nextTask = db._queue.get(i); - while (typeof nextTask !== 'undefined' && nextTask.type === 'read') { - readTasks.push(nextTask); - i++; - nextTask = db._queue.get(i); - } - - var numDone = 0; - - readTasks.forEach(function (readTask) { - var args = readTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - if (++numDone === readTasks.length) { - process.nextTick(function () { - // all read tasks have finished - readTasks.forEach(function () { - db._queue.shift(); - }); - if (db._queue.length) { - executeNext(); - } - }); - } - }); - tryCode(readTask.fun, args); - }); - } - - function runWriteOperation(firstTask) { - var args = firstTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - process.nextTick(function () { - db._queue.shift(); - if (db._queue.length) { - executeNext(); - } - }); - }); - tryCode(firstTask.fun, args); - } - - // all read/write operations to the database are done in a queue, - // similar to how websql/idb works. this avoids problems such - // as e.g. compaction needing to have a lock on the database while - // it updates stuff. in the future we can revisit this. - function writeLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'write' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - // same as the writelock, but multiple can run at once - function readLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'read' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - function formatSeq(n) { - return ('0000000000000000' + n).slice(-16); - } - - function parseSeq(s) { - return parseInt(s, 10); - } - - api._get = readLock(function (id, opts, callback) { - opts = clone$1(opts); - - stores.docStore.get(id, function (err, metadata) { - - if (err || !metadata) { - return callback(createError(MISSING_DOC, 'missing')); - } - - var rev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, rev); - if (deleted && !opts.rev) { - return callback(createError(MISSING_DOC, "deleted")); - } - - rev = opts.rev ? opts.rev : rev; - - var seq = metadata.rev_map[rev]; - - stores.bySeqStore.get(formatSeq(seq), function (err, doc) { - if (!doc) { - return callback(createError(MISSING_DOC)); - } - /* istanbul ignore if */ - if ('_id' in doc && doc._id !== metadata.id) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - doc._id = metadata.id; - if ('_rev' in doc) { - /* istanbul ignore if */ - if (doc._rev !== rev) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - } else { - // we didn't always store this - doc._rev = rev; - } - return callback(null, {doc: doc, metadata: metadata}); - }); - }); - }); - - // not technically part of the spec, but if putAttachment has its own - // method... - api._getAttachment = function (docId, attachId, attachment, opts, callback) { - var digest = attachment.digest; - var type = attachment.content_type; - - stores.binaryStore.get(digest, function (err, attach) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } - // Empty attachment - return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : ''); - } - - if (opts.binary) { - callback(null, readAsBlobOrBuffer(attach, type)); - } else { - callback(null, attach.toString('base64')); - } - }); - }; - - api._bulkDocs = writeLock(function (req, opts, callback) { - var newEdits = opts.new_edits; - var results = new Array(req.docs.length); - var fetchedDocs = new _Map(); - var stemmedRevs = new _Map(); - - var txn = new LevelTransaction(); - var docCountDelta = 0; - var newUpdateSeq = db._updateSeq; - - // parse the docs and give each a sequence number - var userDocs = req.docs; - var docInfos = userDocs.map(function (doc) { - if (doc._id && isLocalId(doc._id)) { - return doc; - } - var newDoc = parseDoc(doc, newEdits); - - if (newDoc.metadata && !newDoc.metadata.rev_map) { - newDoc.metadata.rev_map = {}; - } - - return newDoc; - }); - var infoErrors = docInfos.filter(function (doc) { - return doc.error; - }); - - if (infoErrors.length) { - return callback(infoErrors[0]); - } - - // verify any stub attachments as a precondition test - - function verifyAttachment(digest, callback) { - txn.get(stores.attachmentStore, digest, function (levelErr) { - if (levelErr) { - var err = createError(MISSING_STUB, - 'unknown stub attachment with digest ' + - digest); - callback(err); - } else { - callback(); - } - }); - } - - function verifyAttachments(finish) { - var digests = []; - userDocs.forEach(function (doc) { - if (doc && doc._attachments) { - Object.keys(doc._attachments).forEach(function (filename) { - var att = doc._attachments[filename]; - if (att.stub) { - digests.push(att.digest); - } - }); - } - }); - if (!digests.length) { - return finish(); - } - var numDone = 0; - var err; - - digests.forEach(function (digest) { - verifyAttachment(digest, function (attErr) { - if (attErr && !err) { - err = attErr; - } - - if (++numDone === digests.length) { - finish(err); - } - }); - }); - } - - function fetchExistingDocs(finish) { - var numDone = 0; - var overallErr; - function checkDone() { - if (++numDone === userDocs.length) { - return finish(overallErr); - } - } - - userDocs.forEach(function (doc) { - if (doc._id && isLocalId(doc._id)) { - // skip local docs - return checkDone(); - } - txn.get(stores.docStore, doc._id, function (err, info) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - overallErr = err; - } - } else { - fetchedDocs.set(doc._id, info); - } - checkDone(); - }); - }); - } - - function compact(revsMap, callback) { - var promise = PouchPromise.resolve(); - revsMap.forEach(function (revs, docId) { - // TODO: parallelize, for now need to be sequential to - // pass orphaned attachment tests - promise = promise.then(function () { - return new PouchPromise(function (resolve, reject) { - api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) { - /* istanbul ignore if */ - if (err) { - return reject(err); - } - resolve(); - }); - }); - }); - }); - - promise.then(function () { - callback(); - }, callback); - } - - function autoCompact(callback) { - var revsMap = new _Map(); - fetchedDocs.forEach(function (metadata, docId) { - revsMap.set(docId, compactTree(metadata)); - }); - compact(revsMap, callback); - } - - function finish() { - compact(stemmedRevs, function (error) { - /* istanbul ignore if */ - if (error) { - complete(error); - } - if (api.auto_compaction) { - return autoCompact(complete); - } - complete(); - }); - } - - function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, - isUpdate, delta, resultsIdx, callback2) { - docCountDelta += delta; - - var err = null; - var recv = 0; - - docInfo.metadata.winningRev = winningRev; - docInfo.metadata.deleted = winningRevIsDeleted; - - docInfo.data._id = docInfo.metadata.id; - docInfo.data._rev = docInfo.metadata.rev; - - if (newRevIsDeleted) { - docInfo.data._deleted = true; - } - - if (docInfo.stemmedRevs.length) { - stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs); - } - - var attachments = docInfo.data._attachments ? - Object.keys(docInfo.data._attachments) : - []; - - function attachmentSaved(attachmentErr) { - recv++; - if (!err) { - /* istanbul ignore if */ - if (attachmentErr) { - err = attachmentErr; - callback2(err); - } else if (recv === attachments.length) { - finish(); - } - } - } - - function onMD5Load(doc, key, data, attachmentSaved) { - return function (result) { - saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved); - }; - } - - function doMD5(doc, key, attachmentSaved) { - return function (data) { - binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved)); - }; - } - - for (var i = 0; i < attachments.length; i++) { - var key = attachments[i]; - var att = docInfo.data._attachments[key]; - - if (att.stub) { - // still need to update the refs mapping - var id = docInfo.data._id; - var rev = docInfo.data._rev; - saveAttachmentRefs(id, rev, att.digest, attachmentSaved); - continue; - } - var data; - if (typeof att.data === 'string') { - // input is assumed to be a base64 string - try { - data = atob$1(att.data); - } catch (e) { - callback(createError(BAD_ARG, - 'Attachment is not a valid base64 string')); - return; - } - doMD5(docInfo, key, attachmentSaved)(data); - } else { - prepareAttachmentForStorage(att.data, - doMD5(docInfo, key, attachmentSaved)); - } - } - - function finish() { - var seq = docInfo.metadata.rev_map[docInfo.metadata.rev]; - /* istanbul ignore if */ - if (seq) { - // check that there aren't any existing revisions with the same - // revision id, else we shouldn't do anything - return callback2(); - } - seq = ++newUpdateSeq; - docInfo.metadata.rev_map[docInfo.metadata.rev] = - docInfo.metadata.seq = seq; - var seqKey = formatSeq(seq); - var batch = [{ - key: seqKey, - value: docInfo.data, - prefix: stores.bySeqStore, - type: 'put' - }, { - key: docInfo.metadata.id, - value: docInfo.metadata, - prefix: stores.docStore, - type: 'put' - }]; - txn.batch(batch); - results[resultsIdx] = { - ok: true, - id: docInfo.metadata.id, - rev: winningRev - }; - fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); - callback2(); - } - - if (!attachments.length) { - finish(); - } - } - - // attachments are queued per-digest, otherwise the refs could be - // overwritten by concurrent writes in the same bulkDocs session - var attachmentQueues = {}; - - function saveAttachmentRefs(id, rev, digest, callback) { - - function fetchAtt() { - return new PouchPromise(function (resolve, reject) { - txn.get(stores.attachmentStore, digest, function (err, oldAtt) { - /* istanbul ignore if */ - if (err && err.name !== 'NotFoundError') { - return reject(err); - } - resolve(oldAtt); - }); - }); - } - - function saveAtt(oldAtt) { - var ref = [id, rev].join('@'); - var newAtt = {}; - - if (oldAtt) { - if (oldAtt.refs) { - // only update references if this attachment already has them - // since we cannot migrate old style attachments here without - // doing a full db scan for references - newAtt.refs = oldAtt.refs; - newAtt.refs[ref] = true; - } - } else { - newAtt.refs = {}; - newAtt.refs[ref] = true; - } - - return new PouchPromise(function (resolve) { - txn.batch([{ - type: 'put', - prefix: stores.attachmentStore, - key: digest, - value: newAtt - }]); - resolve(!oldAtt); - }); - } - - // put attachments in a per-digest queue, to avoid two docs with the same - // attachment overwriting each other - var queue = attachmentQueues[digest] || PouchPromise.resolve(); - attachmentQueues[digest] = queue.then(function () { - return fetchAtt().then(saveAtt).then(function (isNewAttachment) { - callback(null, isNewAttachment); - }, callback); - }); - } - - function saveAttachment(docInfo, digest, key, data, callback) { - var att = docInfo.data._attachments[key]; - delete att.data; - att.digest = digest; - att.length = data.length; - var id = docInfo.metadata.id; - var rev = docInfo.metadata.rev; - att.revpos = parseInt(rev, 10); - - saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - // do not try to store empty attachments - if (data.length === 0) { - return callback(err); - } - if (!isNewAttachment) { - // small optimization - don't bother writing it again - return callback(err); - } - txn.batch([{ - type: 'put', - prefix: stores.binaryStore, - key: digest, - value: new Buffer(data, 'binary') - }]); - callback(); - }); - } - - function complete(err) { - /* istanbul ignore if */ - if (err) { - return process.nextTick(function () { - callback(err); - }); - } - txn.batch([ - { - prefix: stores.metaStore, - type: 'put', - key: UPDATE_SEQ_KEY, - value: newUpdateSeq - }, - { - prefix: stores.metaStore, - type: 'put', - key: DOC_COUNT_KEY, - value: db._docCount + docCountDelta - } - ]); - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - db._docCount += docCountDelta; - db._updateSeq = newUpdateSeq; - levelChanges.notify(name); - process.nextTick(function () { - callback(null, results); - }); - }); - } - - if (!docInfos.length) { - return callback(null, []); - } - - verifyAttachments(function (err) { - if (err) { - return callback(err); - } - fetchExistingDocs(function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - processDocs(revLimit, docInfos, api, fetchedDocs, txn, results, - writeDoc, opts, finish); - }); - }); - }); - api._allDocs = readLock(function (opts, callback) { - opts = clone$1(opts); - countDocs(function (err, docCount) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var readstreamOpts = {}; - var skip = opts.skip || 0; - if (opts.startkey) { - readstreamOpts.gte = opts.startkey; - } - if (opts.endkey) { - readstreamOpts.lte = opts.endkey; - } - if (opts.key) { - readstreamOpts.gte = readstreamOpts.lte = opts.key; - } - if (opts.descending) { - readstreamOpts.reverse = true; - // switch start and ends - var tmp = readstreamOpts.lte; - readstreamOpts.lte = readstreamOpts.gte; - readstreamOpts.gte = tmp; - } - var limit; - if (typeof opts.limit === 'number') { - limit = opts.limit; - } - if (limit === 0 || - ('start' in readstreamOpts && 'end' in readstreamOpts && - readstreamOpts.start > readstreamOpts.end)) { - // should return 0 results when start is greater than end. - // normally level would "fix" this for us by reversing the order, - // so short-circuit instead - return callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: [] - }); - } - var results = []; - var docstream = stores.docStore.readStream(readstreamOpts); - - var throughStream = through2.obj(function (entry, _, next) { - var metadata = entry.value; - // winningRev and deleted are performance-killers, but - // in newer versions of PouchDB, they are cached on the metadata - var winningRev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, winningRev); - if (!deleted) { - if (skip-- > 0) { - next(); - return; - } else if (typeof limit === 'number' && limit-- <= 0) { - docstream.unpipe(); - docstream.destroy(); - next(); - return; - } - } else if (opts.deleted !== 'ok') { - next(); - return; - } - function allDocsInner(data) { - var doc = { - id: metadata.id, - key: metadata.id, - value: { - rev: winningRev - } - }; - if (opts.include_docs) { - doc.doc = data; - doc.doc._rev = doc.value.rev; - if (opts.conflicts) { - doc.doc._conflicts = collectConflicts(metadata); - } - for (var att in doc.doc._attachments) { - if (doc.doc._attachments.hasOwnProperty(att)) { - doc.doc._attachments[att].stub = true; - } - } - } - if (opts.inclusive_end === false && metadata.id === opts.endkey) { - return next(); - } else if (deleted) { - if (opts.deleted === 'ok') { - doc.value.deleted = true; - doc.doc = null; - } else { - /* istanbul ignore next */ - return next(); - } - } - results.push(doc); - next(); - } - if (opts.include_docs) { - var seq = metadata.rev_map[winningRev]; - stores.bySeqStore.get(formatSeq(seq), function (err, data) { - allDocsInner(data); - }); - } - else { - allDocsInner(); - } - }, function (next) { - PouchPromise.resolve().then(function () { - if (opts.include_docs && opts.attachments) { - return fetchAttachments(results, stores, opts); - } - }).then(function () { - callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: results - }); - }, callback); - next(); - }).on('unpipe', function () { - throughStream.end(); - }); - - docstream.on('error', callback); - - docstream.pipe(throughStream); - }); - }); - - api._changes = function (opts) { - opts = clone$1(opts); - - if (opts.continuous) { - var id = name + ':' + uuid(); - levelChanges.addListener(name, id, api, opts); - levelChanges.notify(name); - return { - cancel: function () { - levelChanges.removeListener(name, id); - } - }; - } - - var descending = opts.descending; - var results = []; - var lastSeq = opts.since || 0; - var called = 0; - var streamOpts = { - reverse: descending - }; - var limit; - if ('limit' in opts && opts.limit > 0) { - limit = opts.limit; - } - if (!streamOpts.reverse) { - streamOpts.start = formatSeq(opts.since || 0); - } - - var docIds = opts.doc_ids && new _Set(opts.doc_ids); - var filter = filterChange(opts); - var docIdsToMetadata = new _Map(); - - var returnDocs; - if ('return_docs' in opts) { - returnDocs = opts.return_docs; - } else if ('returnDocs' in opts) { - // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release - returnDocs = opts.returnDocs; - } else { - returnDocs = true; - } - - function complete() { - opts.done = true; - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - changeStream.unpipe(throughStream); - changeStream.destroy(); - if (!opts.continuous && !opts.cancelled) { - if (opts.include_docs && opts.attachments) { - fetchAttachments(results, stores, opts).then(function () { - opts.complete(null, {results: results, last_seq: lastSeq}); - }); - } else { - opts.complete(null, {results: results, last_seq: lastSeq}); - } - } - } - var changeStream = stores.bySeqStore.readStream(streamOpts); - var throughStream = through2.obj(function (data, _, next) { - if (limit && called >= limit) { - complete(); - return next(); - } - if (opts.cancelled || opts.done) { - return next(); - } - - var seq = parseSeq(data.key); - var doc = data.value; - - if (seq === opts.since && !descending) { - // couchdb ignores `since` if descending=true - return next(); - } - - if (docIds && !docIds.has(doc._id)) { - return next(); - } - - var metadata; - - function onGetMetadata(metadata) { - var winningRev = getWinningRev(metadata); - - function onGetWinningDoc(winningDoc) { - - var change = opts.processChange(winningDoc, metadata, opts); - change.seq = metadata.seq; - - var filtered = filter(change); - if (typeof filtered === 'object') { - return opts.complete(filtered); - } - - if (filtered) { - called++; - - if (opts.attachments && opts.include_docs) { - // fetch attachment immediately for the benefit - // of live listeners - fetchAttachments([change], stores, opts).then(function () { - opts.onChange(change); - }); - } else { - opts.onChange(change); - } - - if (returnDocs) { - results.push(change); - } - } - next(); - } - - if (metadata.seq !== seq) { - // some other seq is later - return next(); - } - - lastSeq = seq; - - if (winningRev === doc._rev) { - return onGetWinningDoc(doc); - } - - // fetch the winner - - var winningSeq = metadata.rev_map[winningRev]; - - stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) { - onGetWinningDoc(doc); - }); - } - - metadata = docIdsToMetadata.get(doc._id); - if (metadata) { // cached - return onGetMetadata(metadata); - } - // metadata not cached, have to go fetch it - stores.docStore.get(doc._id, function (err, metadata) { - /* istanbul ignore if */ - if (opts.cancelled || opts.done || db.isClosed() || - isLocalId(metadata.id)) { - return next(); - } - docIdsToMetadata.set(doc._id, metadata); - onGetMetadata(metadata); - }); - }, function (next) { - if (opts.cancelled) { - return next(); - } - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - - next(); - }).on('unpipe', function () { - throughStream.end(); - complete(); - }); - changeStream.pipe(throughStream); - return { - cancel: function () { - opts.cancelled = true; - complete(); - } - }; - }; - - api._close = function (callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(createError(NOT_OPEN)); - } - db.close(function (err) { - /* istanbul ignore if */ - if (err) { - callback(err); - } else { - dbStore.delete(name); - callback(); - } - }); - }; - - api._getRevisionTree = function (docId, callback) { - stores.docStore.get(docId, function (err, metadata) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, metadata.rev_tree); - } - }); - }; - - api._doCompaction = writeLock(function (docId, revs, opts, callback) { - api._doCompactionNoLock(docId, revs, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._doCompactionNoLock = function (docId, revs, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - - if (!revs.length) { - return callback(); - } - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.docStore, docId, function (err, metadata) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var seqs = revs.map(function (rev) { - var seq = metadata.rev_map[rev]; - delete metadata.rev_map[rev]; - return seq; - }); - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - var rev = pos + '-' + revHash; - if (revs.indexOf(rev) !== -1) { - opts.status = 'missing'; - } - }); - - var batch = []; - batch.push({ - key: metadata.id, - value: metadata, - type: 'put', - prefix: stores.docStore - }); - - var digestMap = {}; - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === revs.length) { // done - /* istanbul ignore if */ - if (overallErr) { - return callback(overallErr); - } - deleteOrphanedAttachments(); - } - } - - function finish(err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - txn.batch(batch); - if (opts.ctx) { - // don't execute immediately - return callback(); - } - txn.execute(db, callback); - } - - function deleteOrphanedAttachments() { - var possiblyOrphanedAttachments = Object.keys(digestMap); - if (!possiblyOrphanedAttachments.length) { - return finish(); - } - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === possiblyOrphanedAttachments.length) { - finish(overallErr); - } - } - var refsToDelete = new _Map(); - revs.forEach(function (rev) { - refsToDelete.set(docId + '@' + rev, true); - }); - possiblyOrphanedAttachments.forEach(function (digest) { - txn.get(stores.attachmentStore, digest, function (err, attData) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var refs = Object.keys(attData.refs || {}).filter(function (ref) { - return !refsToDelete.has(ref); - }); - var newRefs = {}; - refs.forEach(function (ref) { - newRefs[ref] = true; - }); - if (refs.length) { // not orphaned - batch.push({ - key: digest, - type: 'put', - value: {refs: newRefs}, - prefix: stores.attachmentStore - }); - } else { // orphaned, can safely delete - batch = batch.concat([{ - key: digest, - type: 'del', - prefix: stores.attachmentStore - }, { - key: digest, - type: 'del', - prefix: stores.binaryStore - }]); - } - checkDone(); - }); - }); - } - - seqs.forEach(function (seq) { - batch.push({ - key: formatSeq(seq), - type: 'del', - prefix: stores.bySeqStore - }); - txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var atts = Object.keys(doc._attachments || {}); - atts.forEach(function (attName) { - var digest = doc._attachments[attName].digest; - digestMap[digest] = true; - }); - checkDone(); - }); - }); - }); - }; - - api._getLocal = function (id, callback) { - stores.localStore.get(id, function (err, doc) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, doc); - } - }); - }; - - api._putLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._putLocalNoLock(doc, opts, callback); - } else { - api._putLocalWithLock(doc, opts, callback); - } - }; - - api._putLocalWithLock = writeLock(function (doc, opts, callback) { - api._putLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._putLocalNoLock = function (doc, opts, callback) { - delete doc._revisions; // ignore this, trust the rev - var oldRev = doc._rev; - var id = doc._id; - - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.localStore, id, function (err, resp) { - if (err && oldRev) { - return callback(createError(REV_CONFLICT)); - } - if (resp && resp._rev !== oldRev) { - return callback(createError(REV_CONFLICT)); - } - doc._rev = - oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1'; - var batch = [ - { - type: 'put', - prefix: stores.localStore, - key: id, - value: doc - } - ]; - - txn.batch(batch); - var ret = {ok: true, id: doc._id, rev: doc._rev}; - - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - api._removeLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._removeLocalNoLock(doc, opts, callback); - } else { - api._removeLocalWithLock(doc, opts, callback); - } - }; - - api._removeLocalWithLock = writeLock(function (doc, opts, callback) { - api._removeLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._removeLocalNoLock = function (doc, opts, callback) { - var txn = opts.ctx || new LevelTransaction(); - txn.get(stores.localStore, doc._id, function (err, resp) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } else { - return callback(createError(MISSING_DOC)); - } - } - if (resp._rev !== doc._rev) { - return callback(createError(REV_CONFLICT)); - } - txn.batch([{ - prefix: stores.localStore, - type: 'del', - key: doc._id - }]); - var ret = {ok: true, id: doc._id, rev: '0-0'}; - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - // close and delete open leveldb stores - api._destroy = function (opts, callback) { - var dbStore; - var leveldownName = functionName(leveldown); - /* istanbul ignore else */ - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - return callDestroy(name, callback); - } - - /* istanbul ignore else */ - if (dbStore.has(name)) { - levelChanges.removeAllListeners(name); - - dbStore.get(name).close(function () { - dbStore.delete(name); - callDestroy(name, callback); - }); - } else { - callDestroy(name, callback); - } - }; - function callDestroy(name, cb) { - leveldown.destroy(name, cb); - } -} - -function FruitDownPouch(opts, callback) { - var _opts = jsExtend.extend({ - db: fruitdown - }, opts); - - LevelPouch.call(this, _opts, callback); -} - -// overrides for normal LevelDB behavior on Node -FruitDownPouch.valid = function () { - return !!global.indexedDB; -}; -FruitDownPouch.use_prefix = true; - -function FruitdownPouchPlugin (PouchDB) { - PouchDB.adapter('fruitdown', FruitDownPouch, true); -} - -/* global PouchDB */ - -var PDB = (typeof PouchDB !== 'undefined') ? PouchDB : require('pouchdb'); -if (!PDB) { - guardedConsole('error', 'fruitdown adapter plugin error: ' + - 'Cannot find global "PouchDB" object! ' + - 'Did you remember to include pouchdb.js?'); -} else { - FruitdownPouchPlugin(PDB); -} \ No newline at end of file diff --git a/lib/pouchdb/lib/plugins/localstorage.js b/lib/pouchdb/lib/plugins/localstorage.js deleted file mode 100644 index 1167f1c2..00000000 --- a/lib/pouchdb/lib/plugins/localstorage.js +++ /dev/null @@ -1,3528 +0,0 @@ -'use strict'; - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var levelup = _interopDefault(require('levelup')); -var ltgt = _interopDefault(require('ltgt')); -var events = require('events'); -var events__default = _interopDefault(events); -var inherits = _interopDefault(require('inherits')); -var Codec = _interopDefault(require('level-codec')); -var ReadableStreamCore = _interopDefault(require('readable-stream')); -var through2 = require('through2'); -var getArguments = _interopDefault(require('argsarray')); -var Deque = _interopDefault(require('double-ended-queue')); -var lie = _interopDefault(require('lie')); -var debug = _interopDefault(require('debug')); -var Md5 = _interopDefault(require('spark-md5')); -var vuvuzela = _interopDefault(require('vuvuzela')); -var jsExtend = require('js-extend'); -var localstoragedown = _interopDefault(require('localstorage-down')); - -function isFunction(f) { - return 'function' === typeof f; -} - -function getPrefix(db) { - if (isFunction(db.prefix)) { - return db.prefix(); - } - return db; -} - -function clone(_obj) { - var obj = {}; - for(var k in _obj) { - obj[k] = _obj[k]; - } - return obj; -} - -function nut(db, precodec, codec) { - function encodePrefix(prefix, key, opts1, opts2) { - return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]); - } - - function addEncodings(op, prefix) { - if(prefix && prefix.options) { - op.keyEncoding = - op.keyEncoding || prefix.options.keyEncoding; - op.valueEncoding = - op.valueEncoding || prefix.options.valueEncoding; - } - return op; - } - - db.open(function () { /* no-op */}); - - return { - apply: function (ops, opts, cb) { - opts = opts || {}; - - var batch = []; - var i = -1; - var len = ops.length; - - while (++i < len) { - var op = ops[i]; - addEncodings(op, op.prefix); - op.prefix = getPrefix(op.prefix); - batch.push({ - key: encodePrefix(op.prefix, op.key, opts, op), - value: op.type !== 'del' && codec.encodeValue(op.value, opts, op), - type: op.type - }); - } - db.db.batch(batch, opts, cb); - }, - get: function (key, prefix, opts, cb) { - opts.asBuffer = codec.valueAsBuffer(opts); - return db.db.get( - encodePrefix(prefix, key, opts), - opts, - function (err, value) { - if (err) { - cb(err); - } else { - cb(null, codec.decodeValue(value, opts)); - } - } - ); - }, - createDecoder: function (opts) { - return function (key, value) { - return { - key: codec.decodeKey(precodec.decode(key)[1], opts), - value: codec.decodeValue(value, opts) - }; - }; - }, - isClosed: function isClosed() { - return db.isClosed(); - }, - close: function close(cb) { - return db.close(cb); - }, - iterator: function (_opts) { - var opts = clone(_opts || {}); - var prefix = _opts.prefix || []; - - function encodeKey(key) { - return encodePrefix(prefix, key, opts, {}); - } - - ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound); - - // if these legacy values are in the options, remove them - - opts.prefix = null; - - //************************************************ - //hard coded defaults, for now... - //TODO: pull defaults and encoding out of levelup. - opts.keyAsBuffer = opts.valueAsBuffer = false; - //************************************************ - - - //this is vital, otherwise limit: undefined will - //create an empty stream. - /* istanbul ignore next */ - if ('number' !== typeof opts.limit) { - opts.limit = -1; - } - - opts.keyAsBuffer = precodec.buffer; - opts.valueAsBuffer = codec.valueAsBuffer(opts); - - function wrapIterator(iterator) { - return { - next: function (cb) { - return iterator.next(cb); - }, - end: function (cb) { - iterator.end(cb); - } - }; - } - - return wrapIterator(db.db.iterator(opts)); - } - }; -} - -function NotFoundError(reason) { - Error.call(this, reason); -} - -inherits(NotFoundError, Error); - -NotFoundError.prototype.name = 'NotFoundError'; - -var EventEmitter$1 = events__default.EventEmitter; -var version = "6.5.4"; - -var sublevel = function (nut, prefix, createStream, options) { - var emitter = new EventEmitter$1(); - emitter.sublevels = {}; - emitter.options = options; - - emitter.version = version; - - emitter.methods = {}; - prefix = prefix || []; - - function mergeOpts(opts) { - var o = {}; - var k; - if (options) { - for (k in options) { - if (typeof options[k] !== 'undefined') { - o[k] = options[k]; - } - } - } - if (opts) { - for (k in opts) { - if (typeof opts[k] !== 'undefined') { - o[k] = opts[k]; - } - } - } - return o; - } - - emitter.put = function (key, value, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - nut.apply([{ - key: key, value: value, - prefix: prefix.slice(), type: 'put' - }], mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('put', key, value); - cb(null); - }); - }; - - emitter.prefix = function () { - return prefix.slice(); - }; - - emitter.batch = function (ops, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - ops = ops.map(function (op) { - return { - key: op.key, - value: op.value, - prefix: op.prefix || prefix, - keyEncoding: op.keyEncoding, // * - valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel) - type: op.type - }; - }); - - nut.apply(ops, mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('batch', ops); - cb(null); - }); - }; - - emitter.get = function (key, opts, cb) { - /* istanbul ignore else */ - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - nut.get(key, prefix, mergeOpts(opts), function (err, value) { - if (err) { - cb(new NotFoundError(err)); - } else { - cb(null, value); - } - }); - }; - - emitter.sublevel = function (name, opts) { - return emitter.sublevels[name] = - emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts)); - }; - - emitter.readStream = emitter.createReadStream = function (opts) { - opts = mergeOpts(opts); - opts.prefix = prefix; - var stream; - var it = nut.iterator(opts); - - stream = createStream(opts, nut.createDecoder(opts)); - stream.setIterator(it); - - return stream; - }; - - emitter.close = function (cb) { - nut.close(cb); - }; - - emitter.isOpen = nut.isOpen; - emitter.isClosed = nut.isClosed; - - return emitter; -}; - -/* Copyright (c) 2012-2014 LevelUP contributors - * See list at - * MIT License - */ - -// NOTE: we are fixed to readable-stream@1.0.x for now -// for pure Streams2 across Node versions -var Readable = ReadableStreamCore.Readable; - -function ReadStream(options, makeData) { - if (!(this instanceof ReadStream)) { - return new ReadStream(options, makeData); - } - - Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); - - // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref - - this._waiting = false; - this._options = options; - this._makeData = makeData; -} - -inherits(ReadStream, Readable); - -ReadStream.prototype.setIterator = function (it) { - this._iterator = it; - /* istanbul ignore if */ - if (this._destroyed) { - return it.end(function () {}); - } - /* istanbul ignore if */ - if (this._waiting) { - this._waiting = false; - return this._read(); - } - return this; -}; - -ReadStream.prototype._read = function read() { - var self = this; - /* istanbul ignore if */ - if (self._destroyed) { - return; - } - /* istanbul ignore if */ - if (!self._iterator) { - return this._waiting = true; - } - - self._iterator.next(function (err, key, value) { - if (err || (key === undefined && value === undefined)) { - if (!err && !self._destroyed) { - self.push(null); - } - return self._cleanup(err); - } - - - value = self._makeData(key, value); - if (!self._destroyed) { - self.push(value); - } - }); -}; - -ReadStream.prototype._cleanup = function (err) { - if (this._destroyed) { - return; - } - - this._destroyed = true; - - var self = this; - /* istanbul ignore if */ - if (err) { - self.emit('error', err); - } - - /* istanbul ignore else */ - if (self._iterator) { - self._iterator.end(function () { - self._iterator = null; - self.emit('close'); - }); - } else { - self.emit('close'); - } -}; - -ReadStream.prototype.destroy = function () { - this._cleanup(); -}; - -var precodec = { - encode: function (decodedKey) { - return '\xff' + decodedKey[0] + '\xff' + decodedKey[1]; - }, - decode: function (encodedKeyAsBuffer) { - var str = encodedKeyAsBuffer.toString(); - var idx = str.indexOf('\xff', 1); - return [str.substring(1, idx), str.substring(idx + 1)]; - }, - lowerBound: '\x00', - upperBound: '\xff' -}; - -var codec = new Codec(); - -function sublevelPouch(db) { - return sublevel(nut(db, precodec, codec), [], ReadStream, db.options); -} - -// based on https://github.com/montagejs/collections -function mangle(key) { - return '$' + key; -} -function unmangle(key) { - return key.substring(1); -} -function _Map() { - this.store = {}; -} -_Map.prototype.get = function (key) { - var mangled = mangle(key); - return this.store[mangled]; -}; -_Map.prototype.set = function (key, value) { - var mangled = mangle(key); - this.store[mangled] = value; - return true; -}; -_Map.prototype.has = function (key) { - var mangled = mangle(key); - return mangled in this.store; -}; -_Map.prototype.delete = function (key) { - var mangled = mangle(key); - var res = mangled in this.store; - delete this.store[mangled]; - return res; -}; -_Map.prototype.forEach = function (cb) { - var keys = Object.keys(this.store); - for (var i = 0, len = keys.length; i < len; i++) { - var key = keys[i]; - var value = this.store[key]; - key = unmangle(key); - cb(value, key); - } -}; - -function _Set(array) { - this.store = new _Map(); - - // init with an array - if (array && Array.isArray(array)) { - for (var i = 0, len = array.length; i < len; i++) { - this.add(array[i]); - } - } -} -_Set.prototype.add = function (key) { - return this.store.set(key, true); -}; -_Set.prototype.has = function (key) { - return this.store.has(key); -}; - -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - -/* istanbul ignore next */ -var PouchPromise = typeof Promise === 'function' ? Promise : lie; - -function isBinaryObject(object) { - return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) || - (typeof Blob !== 'undefined' && object instanceof Blob); -} - -function cloneArrayBuffer(buff) { - if (typeof buff.slice === 'function') { - return buff.slice(0); - } - // IE10-11 slice() polyfill - var target = new ArrayBuffer(buff.byteLength); - var targetArray = new Uint8Array(target); - var sourceArray = new Uint8Array(buff); - targetArray.set(sourceArray); - return target; -} - -function cloneBinaryObject(object) { - if (object instanceof ArrayBuffer) { - return cloneArrayBuffer(object); - } - var size = object.size; - var type = object.type; - // Blob - if (typeof object.slice === 'function') { - return object.slice(0, size, type); - } - // PhantomJS slice() replacement - return object.webkitSlice(0, size, type); -} - -// most of this is borrowed from lodash.isPlainObject: -// https://github.com/fis-components/lodash.isplainobject/ -// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js - -var funcToString = Function.prototype.toString; -var objectCtorString = funcToString.call(Object); - -function isPlainObject(value) { - var proto = Object.getPrototypeOf(value); - /* istanbul ignore if */ - if (proto === null) { // not sure when this happens, but I guess it can - return true; - } - var Ctor = proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} - -function clone$1(object) { - var newObject; - var i; - var len; - - if (!object || typeof object !== 'object') { - return object; - } - - if (Array.isArray(object)) { - newObject = []; - for (i = 0, len = object.length; i < len; i++) { - newObject[i] = clone$1(object[i]); - } - return newObject; - } - - // special case: to avoid inconsistencies between IndexedDB - // and other backends, we automatically stringify Dates - if (object instanceof Date) { - return object.toISOString(); - } - - if (isBinaryObject(object)) { - return cloneBinaryObject(object); - } - - if (!isPlainObject(object)) { - return object; // don't clone objects like Workers - } - - newObject = {}; - for (i in object) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(object, i)) { - var value = clone$1(object[i]); - if (typeof value !== 'undefined') { - newObject[i] = value; - } - } - } - return newObject; -} - -var log = debug('pouchdb:api'); - -// like underscore/lodash _.pick() -function pick(obj, arr) { - var res = {}; - for (var i = 0, len = arr.length; i < len; i++) { - var prop = arr[i]; - if (prop in obj) { - res[prop] = obj[prop]; - } - } - return res; -} - -function isChromeApp() { - return (typeof chrome !== "undefined" && - typeof chrome.storage !== "undefined" && - typeof chrome.storage.local !== "undefined"); -} - -var hasLocal; - -if (isChromeApp()) { - hasLocal = false; -} else { - try { - localStorage.setItem('_pouch_check_localstorage', 1); - hasLocal = !!localStorage.getItem('_pouch_check_localstorage'); - } catch (e) { - hasLocal = false; - } -} - -function hasLocalStorage() { - return hasLocal; -} - -inherits(Changes, events.EventEmitter); - -/* istanbul ignore next */ -function attachBrowserEvents(self) { - if (isChromeApp()) { - chrome.storage.onChanged.addListener(function (e) { - // make sure it's event addressed to us - if (e.db_name != null) { - //object only has oldValue, newValue members - self.emit(e.dbName.newValue); - } - }); - } else if (hasLocalStorage()) { - if (typeof addEventListener !== 'undefined') { - addEventListener("storage", function (e) { - self.emit(e.key); - }); - } else { // old IE - window.attachEvent("storage", function (e) { - self.emit(e.key); - }); - } - } -} - -function Changes() { - events.EventEmitter.call(this); - this._listeners = {}; - - attachBrowserEvents(this); -} -Changes.prototype.addListener = function (dbName, id, db, opts) { - /* istanbul ignore if */ - if (this._listeners[id]) { - return; - } - var self = this; - var inprogress = false; - function eventFunction() { - /* istanbul ignore if */ - if (!self._listeners[id]) { - return; - } - if (inprogress) { - inprogress = 'waiting'; - return; - } - inprogress = true; - var changesOpts = pick(opts, [ - 'style', 'include_docs', 'attachments', 'conflicts', 'filter', - 'doc_ids', 'view', 'since', 'query_params', 'binary' - ]); - - /* istanbul ignore next */ - function onError() { - inprogress = false; - } - - db.changes(changesOpts).on('change', function (c) { - if (c.seq > opts.since && !opts.cancelled) { - opts.since = c.seq; - opts.onChange(c); - } - }).on('complete', function () { - if (inprogress === 'waiting') { - setTimeout(function (){ - eventFunction(); - },0); - } - inprogress = false; - }).on('error', onError); - } - this._listeners[id] = eventFunction; - this.on(dbName, eventFunction); -}; - -Changes.prototype.removeListener = function (dbName, id) { - /* istanbul ignore if */ - if (!(id in this._listeners)) { - return; - } - events.EventEmitter.prototype.removeListener.call(this, dbName, - this._listeners[id]); - delete this._listeners[id]; -}; - - -/* istanbul ignore next */ -Changes.prototype.notifyLocalWindows = function (dbName) { - //do a useless change on a storage thing - //in order to get other windows's listeners to activate - if (isChromeApp()) { - chrome.storage.local.set({dbName: dbName}); - } else if (hasLocalStorage()) { - localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; - } -}; - -Changes.prototype.notify = function (dbName) { - this.emit(dbName); - this.notifyLocalWindows(dbName); -}; - -function guardedConsole(method) { - /* istanbul ignore else */ - if (console !== 'undefined' && method in console) { - var args = Array.prototype.slice.call(arguments, 1); - console[method].apply(console, args); - } -} - -inherits(PouchError, Error); - -function PouchError(opts) { - Error.call(this, opts.reason); - this.status = opts.status; - this.name = opts.error; - this.message = opts.reason; - this.error = true; -} - -PouchError.prototype.toString = function () { - return JSON.stringify({ - status: this.status, - name: this.name, - message: this.message, - reason: this.reason - }); -}; - -var UNAUTHORIZED = new PouchError({ - status: 401, - error: 'unauthorized', - reason: "Name or password is incorrect." -}); - -var MISSING_BULK_DOCS = new PouchError({ - status: 400, - error: 'bad_request', - reason: "Missing JSON list of 'docs'" -}); - -var MISSING_DOC = new PouchError({ - status: 404, - error: 'not_found', - reason: 'missing' -}); - -var REV_CONFLICT = new PouchError({ - status: 409, - error: 'conflict', - reason: 'Document update conflict' -}); - -var INVALID_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: '_id field must contain a string' -}); - -var MISSING_ID = new PouchError({ - status: 412, - error: 'missing_id', - reason: '_id is required for puts' -}); - -var RESERVED_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Only reserved document ids may start with underscore.' -}); - -var NOT_OPEN = new PouchError({ - status: 412, - error: 'precondition_failed', - reason: 'Database not open' -}); - -var UNKNOWN_ERROR = new PouchError({ - status: 500, - error: 'unknown_error', - reason: 'Database encountered an unknown error' -}); - -var BAD_ARG = new PouchError({ - status: 500, - error: 'badarg', - reason: 'Some query argument is invalid' -}); - -var INVALID_REQUEST = new PouchError({ - status: 400, - error: 'invalid_request', - reason: 'Request was invalid' -}); - -var QUERY_PARSE_ERROR = new PouchError({ - status: 400, - error: 'query_parse_error', - reason: 'Some query parameter is invalid' -}); - -var DOC_VALIDATION = new PouchError({ - status: 500, - error: 'doc_validation', - reason: 'Bad special document member' -}); - -var BAD_REQUEST = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Something wrong with the request' -}); - -var NOT_AN_OBJECT = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Document must be a JSON object' -}); - -var DB_MISSING = new PouchError({ - status: 404, - error: 'not_found', - reason: 'Database not found' -}); - -var IDB_ERROR = new PouchError({ - status: 500, - error: 'indexed_db_went_bad', - reason: 'unknown' -}); - -var WSQ_ERROR = new PouchError({ - status: 500, - error: 'web_sql_went_bad', - reason: 'unknown' -}); - -var LDB_ERROR = new PouchError({ - status: 500, - error: 'levelDB_went_went_bad', - reason: 'unknown' -}); - -var FORBIDDEN = new PouchError({ - status: 403, - error: 'forbidden', - reason: 'Forbidden by design doc validate_doc_update function' -}); - -var INVALID_REV = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Invalid rev format' -}); - -var FILE_EXISTS = new PouchError({ - status: 412, - error: 'file_exists', - reason: 'The database could not be created, the file already exists.' -}); - -var MISSING_STUB = new PouchError({ - status: 412, - error: 'missing_stub' -}); - -var INVALID_URL = new PouchError({ - status: 413, - error: 'invalid_url', - reason: 'Provided URL is invalid' -}); - -function createError(error, reason) { - function CustomPouchError(reason) { - // inherit error properties from our parent error manually - // so as to allow proper JSON parsing. - /* jshint ignore:start */ - for (var p in error) { - if (typeof error[p] !== 'function') { - this[p] = error[p]; - } - } - /* jshint ignore:end */ - if (reason !== undefined) { - this.reason = reason; - } - } - CustomPouchError.prototype = PouchError.prototype; - return new CustomPouchError(reason); -} - -function tryFilter(filter, doc, req) { - try { - return !filter(doc, req); - } catch (err) { - var msg = 'Filter function threw: ' + err.toString(); - return createError(BAD_REQUEST, msg); - } -} - -function filterChange(opts) { - var req = {}; - var hasFilter = opts.filter && typeof opts.filter === 'function'; - req.query = opts.query_params; - - return function filter(change) { - if (!change.doc) { - // CSG sends events on the changes feed that don't have documents, - // this hack makes a whole lot of existing code robust. - change.doc = {}; - } - - var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); - - if (typeof filterReturn === 'object') { - return filterReturn; - } - - if (filterReturn) { - return false; - } - - if (!opts.include_docs) { - delete change.doc; - } else if (!opts.attachments) { - for (var att in change.doc._attachments) { - /* istanbul ignore else */ - if (change.doc._attachments.hasOwnProperty(att)) { - change.doc._attachments[att].stub = true; - } - } - } - return true; - }; -} - -// shim for Function.prototype.name, -// for browsers that don't support it like IE - -/* istanbul ignore next */ -function f() {} - -var hasName = f.name; -var res; - -// We dont run coverage in IE -/* istanbul ignore else */ -if (hasName) { - res = function (fun) { - return fun.name; - }; -} else { - res = function (fun) { - return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; - }; -} - -var functionName = res; - -// Determine id an ID is valid -// - invalid IDs begin with an underescore that does not begin '_design' or -// '_local' -// - any other string value is a valid id -// Returns the specific error object for each case -function invalidIdError(id) { - var err; - if (!id) { - err = createError(MISSING_ID); - } else if (typeof id !== 'string') { - err = createError(INVALID_ID); - } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { - err = createError(RESERVED_ID); - } - if (err) { - throw err; - } -} - -// BEGIN Math.uuid.js - -/*! -Math.uuid.js (v1.4) -http://www.broofa.com -mailto:robert@broofa.com - -Copyright (c) 2010 Robert Kieffer -Dual licensed under the MIT and GPL licenses. -*/ - -/* - * Generate a random uuid. - * - * USAGE: Math.uuid(length, radix) - * length - the desired number of characters - * radix - the number of allowable values for each character. - * - * EXAMPLES: - * // No arguments - returns RFC4122, version 4 ID - * >>> Math.uuid() - * "92329D39-6F5C-4520-ABFC-AAB64544E172" - * - * // One argument - returns ID of the specified length - * >>> Math.uuid(15) // 15 character ID (default base=62) - * "VcydxgltxrVZSTV" - * - * // Two arguments - returns ID of the specified length, and radix. - * // (Radix must be <= 62) - * >>> Math.uuid(8, 2) // 8 character ID (base=2) - * "01001010" - * >>> Math.uuid(8, 10) // 8 character ID (base=10) - * "47473046" - * >>> Math.uuid(8, 16) // 8 character ID (base=16) - * "098F4D35" - */ -var chars = ( - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + - 'abcdefghijklmnopqrstuvwxyz' -).split(''); -function getValue(radix) { - return 0 | Math.random() * radix; -} -function uuid(len, radix) { - radix = radix || chars.length; - var out = ''; - var i = -1; - - if (len) { - // Compact form - while (++i < len) { - out += chars[getValue(radix)]; - } - return out; - } - // rfc4122, version 4 form - // Fill in random data. At i==19 set the high bits of clock sequence as - // per rfc4122, sec. 4.1.5 - while (++i < 36) { - switch (i) { - case 8: - case 13: - case 18: - case 23: - out += '-'; - break; - case 19: - out += chars[(getValue(16) & 0x3) | 0x8]; - break; - default: - out += chars[getValue(16)]; - } - } - - return out; -} - -function toObject(array) { - return array.reduce(function (obj, item) { - obj[item] = true; - return obj; - }, {}); -} -// List of top level reserved words for doc -var reservedWords = toObject([ - '_id', - '_rev', - '_attachments', - '_deleted', - '_revisions', - '_revs_info', - '_conflicts', - '_deleted_conflicts', - '_local_seq', - '_rev_tree', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats', - // Specific to Couchbase Sync Gateway - '_removed' -]); - -// List of reserved words that should end up the document -var dataWords = toObject([ - '_attachments', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats' -]); - -function parseRevisionInfo(rev) { - if (!/^\d+\-./.test(rev)) { - return createError(INVALID_REV); - } - var idx = rev.indexOf('-'); - var left = rev.substring(0, idx); - var right = rev.substring(idx + 1); - return { - prefix: parseInt(left, 10), - id: right - }; -} - -function makeRevTreeFromRevisions(revisions, opts) { - var pos = revisions.start - revisions.ids.length + 1; - - var revisionIds = revisions.ids; - var ids = [revisionIds[0], opts, []]; - - for (var i = 1, len = revisionIds.length; i < len; i++) { - ids = [revisionIds[i], {status: 'missing'}, [ids]]; - } - - return [{ - pos: pos, - ids: ids - }]; -} - -// Preprocess documents, parse their revisions, assign an id and a -// revision for new writes that are missing them, etc -function parseDoc(doc, newEdits) { - - var nRevNum; - var newRevId; - var revInfo; - var opts = {status: 'available'}; - if (doc._deleted) { - opts.deleted = true; - } - - if (newEdits) { - if (!doc._id) { - doc._id = uuid(); - } - newRevId = uuid(32, 16).toLowerCase(); - if (doc._rev) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - doc._rev_tree = [{ - pos: revInfo.prefix, - ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]] - }]; - nRevNum = revInfo.prefix + 1; - } else { - doc._rev_tree = [{ - pos: 1, - ids : [newRevId, opts, []] - }]; - nRevNum = 1; - } - } else { - if (doc._revisions) { - doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); - nRevNum = doc._revisions.start; - newRevId = doc._revisions.ids[0]; - } - if (!doc._rev_tree) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - nRevNum = revInfo.prefix; - newRevId = revInfo.id; - doc._rev_tree = [{ - pos: nRevNum, - ids: [newRevId, opts, []] - }]; - } - } - - invalidIdError(doc._id); - - doc._rev = nRevNum + '-' + newRevId; - - var result = {metadata : {}, data : {}}; - for (var key in doc) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(doc, key)) { - var specialKey = key[0] === '_'; - if (specialKey && !reservedWords[key]) { - var error = createError(DOC_VALIDATION, key); - error.message = DOC_VALIDATION.message + ': ' + key; - throw error; - } else if (specialKey && !dataWords[key]) { - result.metadata[key.slice(1)] = doc[key]; - } else { - result.data[key] = doc[key]; - } - } - } - return result; -} - -// We fetch all leafs of the revision tree, and sort them based on tree length -// and whether they were deleted, undeleted documents with the longest revision -// tree (most edits) win -// The final sort algorithm is slightly documented in a sidebar here: -// http://guide.couchdb.org/draft/conflicts.html -function winningRev(metadata) { - var winningId; - var winningPos; - var winningDeleted; - var toVisit = metadata.rev_tree.slice(); - var node; - while ((node = toVisit.pop())) { - var tree = node.ids; - var branches = tree[2]; - var pos = node.pos; - if (branches.length) { // non-leaf - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i]}); - } - continue; - } - var deleted = !!tree[1].deleted; - var id = tree[0]; - // sort by deleted, then pos, then id - if (!winningId || (winningDeleted !== deleted ? winningDeleted : - winningPos !== pos ? winningPos < pos : winningId < id)) { - winningId = id; - winningPos = pos; - winningDeleted = deleted; - } - } - - return winningPos + '-' + winningId; -} - -// Pretty much all below can be combined into a higher order function to -// traverse revisions -// The return value from the callback will be passed as context to all -// children of that node -function traverseRevTree(revs, callback) { - var toVisit = revs.slice(); - - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var branches = tree[2]; - var newCtx = - callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx}); - } - } -} - -function sortByPos(a, b) { - return a.pos - b.pos; -} - -function collectLeaves(revs) { - var leaves = []; - traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) { - if (isLeaf) { - leaves.push({rev: pos + "-" + id, pos: pos, opts: opts}); - } - }); - leaves.sort(sortByPos).reverse(); - for (var i = 0, len = leaves.length; i < len; i++) { - delete leaves[i].pos; - } - return leaves; -} - -// returns revs of all conflicts that is leaves such that -// 1. are not deleted and -// 2. are different than winning revision -function collectConflicts(metadata) { - var win = winningRev(metadata); - var leaves = collectLeaves(metadata.rev_tree); - var conflicts = []; - for (var i = 0, len = leaves.length; i < len; i++) { - var leaf = leaves[i]; - if (leaf.rev !== win && !leaf.opts.deleted) { - conflicts.push(leaf.rev); - } - } - return conflicts; -} - -// compact a tree by marking its non-leafs as missing, -// and return a list of revs to delete -function compactTree(metadata) { - var revs = []; - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - if (opts.status === 'available' && !isLeaf) { - revs.push(pos + '-' + revHash); - opts.status = 'missing'; - } - }); - return revs; -} - -// build up a list of all the paths to the leafs in this revision tree -function rootToLeaf(revs) { - var paths = []; - var toVisit = revs.slice(); - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var id = tree[0]; - var opts = tree[1]; - var branches = tree[2]; - var isLeaf = branches.length === 0; - - var history = node.history ? node.history.slice() : []; - history.push({id: id, opts: opts}); - if (isLeaf) { - paths.push({pos: (pos + 1 - history.length), ids: history}); - } - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], history: history}); - } - } - return paths.reverse(); -} - -// for a better overview of what this is doing, read: -// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl -// -// But for a quick intro, CouchDB uses a revision tree to store a documents -// history, A -> B -> C, when a document has conflicts, that is a branch in the -// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format -// -// KeyTree = [Path ... ] -// Path = {pos: position_from_root, ids: Tree} -// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []] - -function sortByPos$1(a, b) { - return a.pos - b.pos; -} - -// classic binary search -function binarySearch(arr, item, comparator) { - var low = 0; - var high = arr.length; - var mid; - while (low < high) { - mid = (low + high) >>> 1; - if (comparator(arr[mid], item) < 0) { - low = mid + 1; - } else { - high = mid; - } - } - return low; -} - -// assuming the arr is sorted, insert the item in the proper place -function insertSorted(arr, item, comparator) { - var idx = binarySearch(arr, item, comparator); - arr.splice(idx, 0, item); -} - -// Turn a path as a flat array into a tree with a single branch. -// If any should be stemmed from the beginning of the array, that's passed -// in as the second argument -function pathToTree(path, numStemmed) { - var root; - var leaf; - for (var i = numStemmed, len = path.length; i < len; i++) { - var node = path[i]; - var currentLeaf = [node.id, node.opts, []]; - if (leaf) { - leaf[2].push(currentLeaf); - leaf = currentLeaf; - } else { - root = leaf = currentLeaf; - } - } - return root; -} - -// compare the IDs of two trees -function compareTree(a, b) { - return a[0] < b[0] ? -1 : 1; -} - -// Merge two trees together -// The roots of tree1 and tree2 must be the same revision -function mergeTree(in_tree1, in_tree2) { - var queue = [{tree1: in_tree1, tree2: in_tree2}]; - var conflicts = false; - while (queue.length > 0) { - var item = queue.pop(); - var tree1 = item.tree1; - var tree2 = item.tree2; - - if (tree1[1].status || tree2[1].status) { - tree1[1].status = - (tree1[1].status === 'available' || - tree2[1].status === 'available') ? 'available' : 'missing'; - } - - for (var i = 0; i < tree2[2].length; i++) { - if (!tree1[2][0]) { - conflicts = 'new_leaf'; - tree1[2][0] = tree2[2][i]; - continue; - } - - var merged = false; - for (var j = 0; j < tree1[2].length; j++) { - if (tree1[2][j][0] === tree2[2][i][0]) { - queue.push({tree1: tree1[2][j], tree2: tree2[2][i]}); - merged = true; - } - } - if (!merged) { - conflicts = 'new_branch'; - insertSorted(tree1[2], tree2[2][i], compareTree); - } - } - } - return {conflicts: conflicts, tree: in_tree1}; -} - -function doMerge(tree, path, dontExpand) { - var restree = []; - var conflicts = false; - var merged = false; - var res; - - if (!tree.length) { - return {tree: [path], conflicts: 'new_leaf'}; - } - - for (var i = 0, len = tree.length; i < len; i++) { - var branch = tree[i]; - if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { - // Paths start at the same position and have the same root, so they need - // merged - res = mergeTree(branch.ids, path.ids); - restree.push({pos: branch.pos, ids: res.tree}); - conflicts = conflicts || res.conflicts; - merged = true; - } else if (dontExpand !== true) { - // The paths start at a different position, take the earliest path and - // traverse up until it as at the same point from root as the path we - // want to merge. If the keys match we return the longer path with the - // other merged After stemming we dont want to expand the trees - - var t1 = branch.pos < path.pos ? branch : path; - var t2 = branch.pos < path.pos ? path : branch; - var diff = t2.pos - t1.pos; - - var candidateParents = []; - - var trees = []; - trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null}); - while (trees.length > 0) { - var item = trees.pop(); - if (item.diff === 0) { - if (item.ids[0] === t2.ids[0]) { - candidateParents.push(item); - } - continue; - } - var elements = item.ids[2]; - for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { - trees.push({ - ids: elements[j], - diff: item.diff - 1, - parent: item.ids, - parentIdx: j - }); - } - } - - var el = candidateParents[0]; - - if (!el) { - restree.push(branch); - } else { - res = mergeTree(el.ids, t2.ids); - el.parent[2][el.parentIdx] = res.tree; - restree.push({pos: t1.pos, ids: t1.ids}); - conflicts = conflicts || res.conflicts; - merged = true; - } - } else { - restree.push(branch); - } - } - - // We didnt find - if (!merged) { - restree.push(path); - } - - restree.sort(sortByPos$1); - - return { - tree: restree, - conflicts: conflicts || 'internal_node' - }; -} - -// To ensure we dont grow the revision tree infinitely, we stem old revisions -function stem(tree, depth) { - // First we break out the tree into a complete list of root to leaf paths - var paths = rootToLeaf(tree); - var maybeStem = {}; - - var result; - for (var i = 0, len = paths.length; i < len; i++) { - // Then for each path, we cut off the start of the path based on the - // `depth` to stem to, and generate a new set of flat trees - var path = paths[i]; - var stemmed = path.ids; - var numStemmed = Math.max(0, stemmed.length - depth); - var stemmedNode = { - pos: path.pos + numStemmed, - ids: pathToTree(stemmed, numStemmed) - }; - - for (var s = 0; s < numStemmed; s++) { - var rev = (path.pos + s) + '-' + stemmed[s].id; - maybeStem[rev] = true; - } - - // Then we remerge all those flat trees together, ensuring that we dont - // connect trees that would go beyond the depth limit - if (result) { - result = doMerge(result, stemmedNode, true).tree; - } else { - result = [stemmedNode]; - } - } - - traverseRevTree(result, function (isLeaf, pos, revHash) { - // some revisions may have been removed in a branch but not in another - delete maybeStem[pos + '-' + revHash]; - }); - - return { - tree: result, - revs: Object.keys(maybeStem) - }; -} - -function merge(tree, path, depth) { - var newTree = doMerge(tree, path); - var stemmed = stem(newTree.tree, depth); - return { - tree: stemmed.tree, - stemmedRevs: stemmed.revs, - conflicts: newTree.conflicts - }; -} - -// return true if a rev exists in the rev tree, false otherwise -function revExists(revs, rev) { - var toVisit = revs.slice(); - var splitRev = rev.split('-'); - var targetPos = parseInt(splitRev[0], 10); - var targetId = splitRev[1]; - - var node; - while ((node = toVisit.pop())) { - if (node.pos === targetPos && node.ids[0] === targetId) { - return true; - } - var branches = node.ids[2]; - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: node.pos + 1, ids: branches[i]}); - } - } - return false; -} - -function getTrees(node) { - return node.ids; -} - -// check if a specific revision of a doc has been deleted -// - metadata: the metadata object from the doc store -// - rev: (optional) the revision to check. defaults to winning revision -function isDeleted(metadata, rev) { - if (!rev) { - rev = winningRev(metadata); - } - var id = rev.substring(rev.indexOf('-') + 1); - var toVisit = metadata.rev_tree.map(getTrees); - - var tree; - while ((tree = toVisit.pop())) { - if (tree[0] === id) { - return !!tree[1].deleted; - } - toVisit = toVisit.concat(tree[2]); - } -} - -function isLocalId(id) { - return (/^_local/).test(id); -} - -var atob$1 = function (str) { - return atob(str); -}; - -var btoa$1 = function (str) { - return btoa(str); -}; - -// Abstracts constructing a Blob object, so it also works in older -// browsers that don't support the native Blob constructor (e.g. -// old QtWebKit versions, Android < 4.4). -function createBlob(parts, properties) { - /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ - parts = parts || []; - properties = properties || {}; - try { - return new Blob(parts, properties); - } catch (e) { - if (e.name !== "TypeError") { - throw e; - } - var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : - typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : - typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : - WebKitBlobBuilder; - var builder = new Builder(); - for (var i = 0; i < parts.length; i += 1) { - builder.append(parts[i]); - } - return builder.getBlob(properties.type); - } -} - -// From http://stackoverflow.com/questions/14967647/ (continues on next line) -// encode-decode-image-with-base64-breaks-image (2013-04-21) -function binaryStringToArrayBuffer(bin) { - var length = bin.length; - var buf = new ArrayBuffer(length); - var arr = new Uint8Array(buf); - for (var i = 0; i < length; i++) { - arr[i] = bin.charCodeAt(i); - } - return buf; -} - -function binStringToBluffer(binString, type) { - return createBlob([binaryStringToArrayBuffer(binString)], {type: type}); -} - -//Can't find original post, but this is close -//http://stackoverflow.com/questions/6965107/ (continues on next line) -//converting-between-strings-and-arraybuffers -function arrayBufferToBinaryString(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var length = bytes.byteLength; - for (var i = 0; i < length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return binary; -} - -// shim for browsers that don't support it -function readAsBinaryString(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(arrayBufferToBinaryString( - new FileReaderSync().readAsArrayBuffer(blob))); - } - - var reader = new FileReader(); - var hasBinaryString = typeof reader.readAsBinaryString === 'function'; - reader.onloadend = function (e) { - var result = e.target.result || ''; - if (hasBinaryString) { - return callback(result); - } - callback(arrayBufferToBinaryString(result)); - }; - if (hasBinaryString) { - reader.readAsBinaryString(blob); - } else { - reader.readAsArrayBuffer(blob); - } -} - -// simplified API. universal browser support is assumed -function readAsArrayBuffer(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker: - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(new FileReaderSync().readAsArrayBuffer(blob)); - } - - var reader = new FileReader(); - reader.onloadend = function (e) { - var result = e.target.result || new ArrayBuffer(0); - callback(result); - }; - reader.readAsArrayBuffer(blob); -} - -var setImmediateShim = global.setImmediate || global.setTimeout; -var MD5_CHUNK_SIZE = 32768; - -function rawToBase64(raw) { - return btoa$1(raw); -} - -function sliceBlob(blob, start, end) { - if (blob.webkitSlice) { - return blob.webkitSlice(start, end); - } - return blob.slice(start, end); -} - -function appendBlob(buffer, blob, start, end, callback) { - if (start > 0 || end < blob.size) { - // only slice blob if we really need to - blob = sliceBlob(blob, start, end); - } - readAsArrayBuffer(blob, function (arrayBuffer) { - buffer.append(arrayBuffer); - callback(); - }); -} - -function appendString(buffer, string, start, end, callback) { - if (start > 0 || end < string.length) { - // only create a substring if we really need to - string = string.substring(start, end); - } - buffer.appendBinary(string); - callback(); -} - -function binaryMd5(data, callback) { - var inputIsString = typeof data === 'string'; - var len = inputIsString ? data.length : data.size; - var chunkSize = Math.min(MD5_CHUNK_SIZE, len); - var chunks = Math.ceil(len / chunkSize); - var currentChunk = 0; - var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer(); - - var append = inputIsString ? appendString : appendBlob; - - function next() { - setImmediateShim(loadNextChunk); - } - - function done() { - var raw = buffer.end(true); - var base64 = rawToBase64(raw); - callback(base64); - buffer.destroy(); - } - - function loadNextChunk() { - var start = currentChunk * chunkSize; - var end = start + chunkSize; - currentChunk++; - if (currentChunk < chunks) { - append(buffer, data, start, end, next); - } else { - append(buffer, data, start, end, done); - } - } - loadNextChunk(); -} - -function updateDoc(revLimit, prev, docInfo, results, - i, cb, writeDoc, newEdits) { - - if (revExists(prev.rev_tree, docInfo.metadata.rev)) { - results[i] = docInfo; - return cb(); - } - - // sometimes this is pre-calculated. historically not always - var previousWinningRev = prev.winningRev || winningRev(prev); - var previouslyDeleted = 'deleted' in prev ? prev.deleted : - isDeleted(prev, previousWinningRev); - var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted : - isDeleted(docInfo.metadata); - var isRoot = /^1-/.test(docInfo.metadata.rev); - - if (previouslyDeleted && !deleted && newEdits && isRoot) { - var newDoc = docInfo.data; - newDoc._rev = previousWinningRev; - newDoc._id = docInfo.metadata.id; - docInfo = parseDoc(newDoc, newEdits); - } - - var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); - - var inConflict = newEdits && (((previouslyDeleted && deleted) || - (!previouslyDeleted && merged.conflicts !== 'new_leaf') || - (previouslyDeleted && !deleted && merged.conflicts === 'new_branch'))); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[i] = err; - return cb(); - } - - var newRev = docInfo.metadata.rev; - docInfo.metadata.rev_tree = merged.tree; - docInfo.stemmedRevs = merged.stemmedRevs || []; - /* istanbul ignore else */ - if (prev.rev_map) { - docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb - } - - // recalculate - var winningRev$$ = winningRev(docInfo.metadata); - var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$); - - // calculate the total number of documents that were added/removed, - // from the perspective of total_rows/doc_count - var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 : - previouslyDeleted < winningRevIsDeleted ? -1 : 1; - - var newRevIsDeleted; - if (newRev === winningRev$$) { - // if the new rev is the same as the winning rev, we can reuse that value - newRevIsDeleted = winningRevIsDeleted; - } else { - // if they're not the same, then we need to recalculate - newRevIsDeleted = isDeleted(docInfo.metadata, newRev); - } - - writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted, - true, delta, i, cb); -} - -function rootIsMissing(docInfo) { - return docInfo.metadata.rev_tree[0].ids[1].status === 'missing'; -} - -function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, - writeDoc, opts, overallCallback) { - - // Default to 1000 locally - revLimit = revLimit || 1000; - - function insertDoc(docInfo, resultsIdx, callback) { - // Cant insert new deleted documents - var winningRev$$ = winningRev(docInfo.metadata); - var deleted = isDeleted(docInfo.metadata, winningRev$$); - if ('was_delete' in opts && deleted) { - results[resultsIdx] = createError(MISSING_DOC, 'deleted'); - return callback(); - } - - // 4712 - detect whether a new document was inserted with a _rev - var inConflict = newEdits && rootIsMissing(docInfo); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[resultsIdx] = err; - return callback(); - } - - var delta = deleted ? 0 : 1; - - writeDoc(docInfo, winningRev$$, deleted, deleted, false, - delta, resultsIdx, callback); - } - - var newEdits = opts.new_edits; - var idsToDocs = new _Map(); - - var docsDone = 0; - var docsToDo = docInfos.length; - - function checkAllDocsDone() { - if (++docsDone === docsToDo && overallCallback) { - overallCallback(); - } - } - - docInfos.forEach(function (currentDoc, resultsIdx) { - - if (currentDoc._id && isLocalId(currentDoc._id)) { - var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal'; - api[fun](currentDoc, {ctx: tx}, function (err, res) { - results[resultsIdx] = err || res; - checkAllDocsDone(); - }); - return; - } - - var id = currentDoc.metadata.id; - if (idsToDocs.has(id)) { - docsToDo--; // duplicate - idsToDocs.get(id).push([currentDoc, resultsIdx]); - } else { - idsToDocs.set(id, [[currentDoc, resultsIdx]]); - } - }); - - // in the case of new_edits, the user can provide multiple docs - // with the same id. these need to be processed sequentially - idsToDocs.forEach(function (docs, id) { - var numDone = 0; - - function docWritten() { - if (++numDone < docs.length) { - nextDoc(); - } else { - checkAllDocsDone(); - } - } - function nextDoc() { - var value = docs[numDone]; - var currentDoc = value[0]; - var resultsIdx = value[1]; - - if (fetchedDocs.has(id)) { - updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results, - resultsIdx, docWritten, writeDoc, newEdits); - } else { - // Ensure stemming applies to new writes as well - var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); - currentDoc.metadata.rev_tree = merged.tree; - currentDoc.stemmedRevs = merged.stemmedRevs || []; - insertDoc(currentDoc, resultsIdx, docWritten); - } - } - nextDoc(); - }); -} - -function slowJsonParse(str) { - try { - return JSON.parse(str); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.parse(str); - } -} - -function safeJsonParse(str) { - // try/catch is deoptimized in V8, leading to slower - // times than we'd like to have. Most documents are _not_ - // huge, and do not require a slower code path just to parse them. - // We can be pretty sure that a document under 50000 characters - // will not be so deeply nested as to throw a stack overflow error - // (depends on the engine and available memory, though, so this is - // just a hunch). 50000 was chosen based on the average length - // of this string in our test suite, to try to find a number that covers - // most of our test cases (26 over this size, 26378 under it). - if (str.length < 50000) { - return JSON.parse(str); - } - return slowJsonParse(str); -} - -function safeJsonStringify(json) { - try { - return JSON.stringify(json); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.stringify(json); - } -} - -function readAsBlobOrBuffer(storedObject, type) { - // In the browser, we've stored a binary string. This now comes back as a - // browserified Node-style Buffer (implemented as a typed array), - // but we want a Blob instead. - var byteArray = new Uint8Array(storedObject); - return createBlob([byteArray], {type: type}); -} - -// In the browser, we store a binary string -function prepareAttachmentForStorage(attData, cb) { - readAsBinaryString(attData, cb); -} - -function createEmptyBlobOrBuffer(type) { - return createBlob([''], {type: type}); -} - -// similar to an idb or websql transaction object -// designed to be passed around. basically just caches -// things in-memory and then does a big batch() operation -// when you're done - -function getCacheFor(transaction, store) { - var prefix = store.prefix()[0]; - var cache = transaction._cache; - var subCache = cache.get(prefix); - if (!subCache) { - subCache = new _Map(); - cache.set(prefix, subCache); - } - return subCache; -} - -function LevelTransaction() { - this._batch = []; - this._cache = new _Map(); -} - -LevelTransaction.prototype.get = function (store, key, callback) { - var cache = getCacheFor(this, store); - var exists = cache.get(key); - if (exists) { - return process.nextTick(function () { - callback(null, exists); - }); - } else if (exists === null) { // deleted marker - /* istanbul ignore next */ - return process.nextTick(function () { - callback({name: 'NotFoundError'}); - }); - } - store.get(key, function (err, res) { - if (err) { - /* istanbul ignore else */ - if (err.name === 'NotFoundError') { - cache.set(key, null); - } - return callback(err); - } - cache.set(key, res); - callback(null, res); - }); -}; - -LevelTransaction.prototype.batch = function (batch) { - for (var i = 0, len = batch.length; i < len; i++) { - var operation = batch[i]; - - var cache = getCacheFor(this, operation.prefix); - - if (operation.type === 'put') { - cache.set(operation.key, operation.value); - } else { - cache.set(operation.key, null); - } - } - this._batch = this._batch.concat(batch); -}; - -LevelTransaction.prototype.execute = function (db, callback) { - - var keys = new _Set(); - var uniqBatches = []; - - // remove duplicates; last one wins - for (var i = this._batch.length - 1; i >= 0; i--) { - var operation = this._batch[i]; - var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key; - if (keys.has(lookupKey)) { - continue; - } - keys.add(lookupKey); - uniqBatches.push(operation); - } - - db.batch(uniqBatches, callback); -}; - -var DOC_STORE = 'document-store'; -var BY_SEQ_STORE = 'by-sequence'; -var ATTACHMENT_STORE = 'attach-store'; -var BINARY_STORE = 'attach-binary-store'; -var LOCAL_STORE = 'local-store'; -var META_STORE = 'meta-store'; - -// leveldb barks if we try to open a db multiple times -// so we cache opened connections here for initstore() -var dbStores = new _Map(); - -// store the value of update_seq in the by-sequence store the key name will -// never conflict, since the keys in the by-sequence store are integers -var UPDATE_SEQ_KEY = '_local_last_update_seq'; -var DOC_COUNT_KEY = '_local_doc_count'; -var UUID_KEY = '_local_uuid'; - -var MD5_PREFIX = 'md5-'; - -var safeJsonEncoding = { - encode: safeJsonStringify, - decode: safeJsonParse, - buffer: false, - type: 'cheap-json' -}; - -var levelChanges = new Changes(); - -// winningRev and deleted are performance-killers, but -// in newer versions of PouchDB, they are cached on the metadata -function getWinningRev(metadata) { - return 'winningRev' in metadata ? - metadata.winningRev : winningRev(metadata); -} - -function getIsDeleted(metadata, winningRev) { - return 'deleted' in metadata ? - metadata.deleted : isDeleted(metadata, winningRev); -} - -function fetchAttachment(att, stores, opts) { - var type = att.content_type; - return new PouchPromise(function (resolve, reject) { - stores.binaryStore.get(att.digest, function (err, buffer) { - var data; - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return reject(err); - } else { - // empty - if (!opts.binary) { - data = ''; - } else { - data = binStringToBluffer('', type); - } - } - } else { // non-empty - if (opts.binary) { - data = readAsBlobOrBuffer(buffer, type); - } else { - data = buffer.toString('base64'); - } - } - delete att.stub; - delete att.length; - att.data = data; - resolve(); - }); - }); -} - -function fetchAttachments(results, stores, opts) { - var atts = []; - results.forEach(function (row) { - if (!(row.doc && row.doc._attachments)) { - return; - } - var attNames = Object.keys(row.doc._attachments); - attNames.forEach(function (attName) { - var att = row.doc._attachments[attName]; - if (!('data' in att)) { - atts.push(att); - } - }); - }); - - return PouchPromise.all(atts.map(function (att) { - return fetchAttachment(att, stores, opts); - })); -} - -function LevelPouch(opts, callback) { - opts = clone$1(opts); - var api = this; - var instanceId; - var stores = {}; - var revLimit = opts.revs_limit; - var db; - var name = opts.name; - // TODO: this is undocumented and unused probably - /* istanbul ignore else */ - if (typeof opts.createIfMissing === 'undefined') { - opts.createIfMissing = true; - } - - var leveldown = opts.db; - - var dbStore; - var leveldownName = functionName(leveldown); - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - dbStore = new _Map(); - dbStores.set(leveldownName, dbStore); - } - if (dbStore.has(name)) { - db = dbStore.get(name); - afterDBCreated(); - } else { - dbStore.set(name, sublevelPouch(levelup(name, opts, function (err) { - /* istanbul ignore if */ - if (err) { - dbStore.delete(name); - return callback(err); - } - db = dbStore.get(name); - db._docCount = -1; - db._queue = new Deque(); - /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); - } else { - afterDBCreated(); - } - }))); - } - - function afterDBCreated() { - stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding}); - stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'}); - stores.attachmentStore = - db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'}); - stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); - stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); - stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); - }); - }); - }); - }); - }); - } - - function countDocs(callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(new Error('database is closed')); - } - return callback(null, db._docCount); // use cached value - } - - api.type = function () { - return 'leveldb'; - }; - - api._id = function (callback) { - callback(null, instanceId); - }; - - api._info = function (callback) { - var res = { - doc_count: db._docCount, - update_seq: db._updateSeq, - backend_adapter: functionName(leveldown) - }; - return process.nextTick(function () { - callback(null, res); - }); - }; - - function tryCode(fun, args) { - try { - fun.apply(null, args); - } catch (err) { - args[args.length - 1](err); - } - } - - function executeNext() { - var firstTask = db._queue.peekFront(); - - if (firstTask.type === 'read') { - runReadOperation(firstTask); - } else { // write, only do one at a time - runWriteOperation(firstTask); - } - } - - function runReadOperation(firstTask) { - // do multiple reads at once simultaneously, because it's safe - - var readTasks = [firstTask]; - var i = 1; - var nextTask = db._queue.get(i); - while (typeof nextTask !== 'undefined' && nextTask.type === 'read') { - readTasks.push(nextTask); - i++; - nextTask = db._queue.get(i); - } - - var numDone = 0; - - readTasks.forEach(function (readTask) { - var args = readTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - if (++numDone === readTasks.length) { - process.nextTick(function () { - // all read tasks have finished - readTasks.forEach(function () { - db._queue.shift(); - }); - if (db._queue.length) { - executeNext(); - } - }); - } - }); - tryCode(readTask.fun, args); - }); - } - - function runWriteOperation(firstTask) { - var args = firstTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - process.nextTick(function () { - db._queue.shift(); - if (db._queue.length) { - executeNext(); - } - }); - }); - tryCode(firstTask.fun, args); - } - - // all read/write operations to the database are done in a queue, - // similar to how websql/idb works. this avoids problems such - // as e.g. compaction needing to have a lock on the database while - // it updates stuff. in the future we can revisit this. - function writeLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'write' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - // same as the writelock, but multiple can run at once - function readLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'read' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - function formatSeq(n) { - return ('0000000000000000' + n).slice(-16); - } - - function parseSeq(s) { - return parseInt(s, 10); - } - - api._get = readLock(function (id, opts, callback) { - opts = clone$1(opts); - - stores.docStore.get(id, function (err, metadata) { - - if (err || !metadata) { - return callback(createError(MISSING_DOC, 'missing')); - } - - var rev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, rev); - if (deleted && !opts.rev) { - return callback(createError(MISSING_DOC, "deleted")); - } - - rev = opts.rev ? opts.rev : rev; - - var seq = metadata.rev_map[rev]; - - stores.bySeqStore.get(formatSeq(seq), function (err, doc) { - if (!doc) { - return callback(createError(MISSING_DOC)); - } - /* istanbul ignore if */ - if ('_id' in doc && doc._id !== metadata.id) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - doc._id = metadata.id; - if ('_rev' in doc) { - /* istanbul ignore if */ - if (doc._rev !== rev) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - } else { - // we didn't always store this - doc._rev = rev; - } - return callback(null, {doc: doc, metadata: metadata}); - }); - }); - }); - - // not technically part of the spec, but if putAttachment has its own - // method... - api._getAttachment = function (docId, attachId, attachment, opts, callback) { - var digest = attachment.digest; - var type = attachment.content_type; - - stores.binaryStore.get(digest, function (err, attach) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } - // Empty attachment - return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : ''); - } - - if (opts.binary) { - callback(null, readAsBlobOrBuffer(attach, type)); - } else { - callback(null, attach.toString('base64')); - } - }); - }; - - api._bulkDocs = writeLock(function (req, opts, callback) { - var newEdits = opts.new_edits; - var results = new Array(req.docs.length); - var fetchedDocs = new _Map(); - var stemmedRevs = new _Map(); - - var txn = new LevelTransaction(); - var docCountDelta = 0; - var newUpdateSeq = db._updateSeq; - - // parse the docs and give each a sequence number - var userDocs = req.docs; - var docInfos = userDocs.map(function (doc) { - if (doc._id && isLocalId(doc._id)) { - return doc; - } - var newDoc = parseDoc(doc, newEdits); - - if (newDoc.metadata && !newDoc.metadata.rev_map) { - newDoc.metadata.rev_map = {}; - } - - return newDoc; - }); - var infoErrors = docInfos.filter(function (doc) { - return doc.error; - }); - - if (infoErrors.length) { - return callback(infoErrors[0]); - } - - // verify any stub attachments as a precondition test - - function verifyAttachment(digest, callback) { - txn.get(stores.attachmentStore, digest, function (levelErr) { - if (levelErr) { - var err = createError(MISSING_STUB, - 'unknown stub attachment with digest ' + - digest); - callback(err); - } else { - callback(); - } - }); - } - - function verifyAttachments(finish) { - var digests = []; - userDocs.forEach(function (doc) { - if (doc && doc._attachments) { - Object.keys(doc._attachments).forEach(function (filename) { - var att = doc._attachments[filename]; - if (att.stub) { - digests.push(att.digest); - } - }); - } - }); - if (!digests.length) { - return finish(); - } - var numDone = 0; - var err; - - digests.forEach(function (digest) { - verifyAttachment(digest, function (attErr) { - if (attErr && !err) { - err = attErr; - } - - if (++numDone === digests.length) { - finish(err); - } - }); - }); - } - - function fetchExistingDocs(finish) { - var numDone = 0; - var overallErr; - function checkDone() { - if (++numDone === userDocs.length) { - return finish(overallErr); - } - } - - userDocs.forEach(function (doc) { - if (doc._id && isLocalId(doc._id)) { - // skip local docs - return checkDone(); - } - txn.get(stores.docStore, doc._id, function (err, info) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - overallErr = err; - } - } else { - fetchedDocs.set(doc._id, info); - } - checkDone(); - }); - }); - } - - function compact(revsMap, callback) { - var promise = PouchPromise.resolve(); - revsMap.forEach(function (revs, docId) { - // TODO: parallelize, for now need to be sequential to - // pass orphaned attachment tests - promise = promise.then(function () { - return new PouchPromise(function (resolve, reject) { - api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) { - /* istanbul ignore if */ - if (err) { - return reject(err); - } - resolve(); - }); - }); - }); - }); - - promise.then(function () { - callback(); - }, callback); - } - - function autoCompact(callback) { - var revsMap = new _Map(); - fetchedDocs.forEach(function (metadata, docId) { - revsMap.set(docId, compactTree(metadata)); - }); - compact(revsMap, callback); - } - - function finish() { - compact(stemmedRevs, function (error) { - /* istanbul ignore if */ - if (error) { - complete(error); - } - if (api.auto_compaction) { - return autoCompact(complete); - } - complete(); - }); - } - - function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, - isUpdate, delta, resultsIdx, callback2) { - docCountDelta += delta; - - var err = null; - var recv = 0; - - docInfo.metadata.winningRev = winningRev; - docInfo.metadata.deleted = winningRevIsDeleted; - - docInfo.data._id = docInfo.metadata.id; - docInfo.data._rev = docInfo.metadata.rev; - - if (newRevIsDeleted) { - docInfo.data._deleted = true; - } - - if (docInfo.stemmedRevs.length) { - stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs); - } - - var attachments = docInfo.data._attachments ? - Object.keys(docInfo.data._attachments) : - []; - - function attachmentSaved(attachmentErr) { - recv++; - if (!err) { - /* istanbul ignore if */ - if (attachmentErr) { - err = attachmentErr; - callback2(err); - } else if (recv === attachments.length) { - finish(); - } - } - } - - function onMD5Load(doc, key, data, attachmentSaved) { - return function (result) { - saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved); - }; - } - - function doMD5(doc, key, attachmentSaved) { - return function (data) { - binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved)); - }; - } - - for (var i = 0; i < attachments.length; i++) { - var key = attachments[i]; - var att = docInfo.data._attachments[key]; - - if (att.stub) { - // still need to update the refs mapping - var id = docInfo.data._id; - var rev = docInfo.data._rev; - saveAttachmentRefs(id, rev, att.digest, attachmentSaved); - continue; - } - var data; - if (typeof att.data === 'string') { - // input is assumed to be a base64 string - try { - data = atob$1(att.data); - } catch (e) { - callback(createError(BAD_ARG, - 'Attachment is not a valid base64 string')); - return; - } - doMD5(docInfo, key, attachmentSaved)(data); - } else { - prepareAttachmentForStorage(att.data, - doMD5(docInfo, key, attachmentSaved)); - } - } - - function finish() { - var seq = docInfo.metadata.rev_map[docInfo.metadata.rev]; - /* istanbul ignore if */ - if (seq) { - // check that there aren't any existing revisions with the same - // revision id, else we shouldn't do anything - return callback2(); - } - seq = ++newUpdateSeq; - docInfo.metadata.rev_map[docInfo.metadata.rev] = - docInfo.metadata.seq = seq; - var seqKey = formatSeq(seq); - var batch = [{ - key: seqKey, - value: docInfo.data, - prefix: stores.bySeqStore, - type: 'put' - }, { - key: docInfo.metadata.id, - value: docInfo.metadata, - prefix: stores.docStore, - type: 'put' - }]; - txn.batch(batch); - results[resultsIdx] = { - ok: true, - id: docInfo.metadata.id, - rev: winningRev - }; - fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); - callback2(); - } - - if (!attachments.length) { - finish(); - } - } - - // attachments are queued per-digest, otherwise the refs could be - // overwritten by concurrent writes in the same bulkDocs session - var attachmentQueues = {}; - - function saveAttachmentRefs(id, rev, digest, callback) { - - function fetchAtt() { - return new PouchPromise(function (resolve, reject) { - txn.get(stores.attachmentStore, digest, function (err, oldAtt) { - /* istanbul ignore if */ - if (err && err.name !== 'NotFoundError') { - return reject(err); - } - resolve(oldAtt); - }); - }); - } - - function saveAtt(oldAtt) { - var ref = [id, rev].join('@'); - var newAtt = {}; - - if (oldAtt) { - if (oldAtt.refs) { - // only update references if this attachment already has them - // since we cannot migrate old style attachments here without - // doing a full db scan for references - newAtt.refs = oldAtt.refs; - newAtt.refs[ref] = true; - } - } else { - newAtt.refs = {}; - newAtt.refs[ref] = true; - } - - return new PouchPromise(function (resolve) { - txn.batch([{ - type: 'put', - prefix: stores.attachmentStore, - key: digest, - value: newAtt - }]); - resolve(!oldAtt); - }); - } - - // put attachments in a per-digest queue, to avoid two docs with the same - // attachment overwriting each other - var queue = attachmentQueues[digest] || PouchPromise.resolve(); - attachmentQueues[digest] = queue.then(function () { - return fetchAtt().then(saveAtt).then(function (isNewAttachment) { - callback(null, isNewAttachment); - }, callback); - }); - } - - function saveAttachment(docInfo, digest, key, data, callback) { - var att = docInfo.data._attachments[key]; - delete att.data; - att.digest = digest; - att.length = data.length; - var id = docInfo.metadata.id; - var rev = docInfo.metadata.rev; - att.revpos = parseInt(rev, 10); - - saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - // do not try to store empty attachments - if (data.length === 0) { - return callback(err); - } - if (!isNewAttachment) { - // small optimization - don't bother writing it again - return callback(err); - } - txn.batch([{ - type: 'put', - prefix: stores.binaryStore, - key: digest, - value: new Buffer(data, 'binary') - }]); - callback(); - }); - } - - function complete(err) { - /* istanbul ignore if */ - if (err) { - return process.nextTick(function () { - callback(err); - }); - } - txn.batch([ - { - prefix: stores.metaStore, - type: 'put', - key: UPDATE_SEQ_KEY, - value: newUpdateSeq - }, - { - prefix: stores.metaStore, - type: 'put', - key: DOC_COUNT_KEY, - value: db._docCount + docCountDelta - } - ]); - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - db._docCount += docCountDelta; - db._updateSeq = newUpdateSeq; - levelChanges.notify(name); - process.nextTick(function () { - callback(null, results); - }); - }); - } - - if (!docInfos.length) { - return callback(null, []); - } - - verifyAttachments(function (err) { - if (err) { - return callback(err); - } - fetchExistingDocs(function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - processDocs(revLimit, docInfos, api, fetchedDocs, txn, results, - writeDoc, opts, finish); - }); - }); - }); - api._allDocs = readLock(function (opts, callback) { - opts = clone$1(opts); - countDocs(function (err, docCount) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var readstreamOpts = {}; - var skip = opts.skip || 0; - if (opts.startkey) { - readstreamOpts.gte = opts.startkey; - } - if (opts.endkey) { - readstreamOpts.lte = opts.endkey; - } - if (opts.key) { - readstreamOpts.gte = readstreamOpts.lte = opts.key; - } - if (opts.descending) { - readstreamOpts.reverse = true; - // switch start and ends - var tmp = readstreamOpts.lte; - readstreamOpts.lte = readstreamOpts.gte; - readstreamOpts.gte = tmp; - } - var limit; - if (typeof opts.limit === 'number') { - limit = opts.limit; - } - if (limit === 0 || - ('start' in readstreamOpts && 'end' in readstreamOpts && - readstreamOpts.start > readstreamOpts.end)) { - // should return 0 results when start is greater than end. - // normally level would "fix" this for us by reversing the order, - // so short-circuit instead - return callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: [] - }); - } - var results = []; - var docstream = stores.docStore.readStream(readstreamOpts); - - var throughStream = through2.obj(function (entry, _, next) { - var metadata = entry.value; - // winningRev and deleted are performance-killers, but - // in newer versions of PouchDB, they are cached on the metadata - var winningRev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, winningRev); - if (!deleted) { - if (skip-- > 0) { - next(); - return; - } else if (typeof limit === 'number' && limit-- <= 0) { - docstream.unpipe(); - docstream.destroy(); - next(); - return; - } - } else if (opts.deleted !== 'ok') { - next(); - return; - } - function allDocsInner(data) { - var doc = { - id: metadata.id, - key: metadata.id, - value: { - rev: winningRev - } - }; - if (opts.include_docs) { - doc.doc = data; - doc.doc._rev = doc.value.rev; - if (opts.conflicts) { - doc.doc._conflicts = collectConflicts(metadata); - } - for (var att in doc.doc._attachments) { - if (doc.doc._attachments.hasOwnProperty(att)) { - doc.doc._attachments[att].stub = true; - } - } - } - if (opts.inclusive_end === false && metadata.id === opts.endkey) { - return next(); - } else if (deleted) { - if (opts.deleted === 'ok') { - doc.value.deleted = true; - doc.doc = null; - } else { - /* istanbul ignore next */ - return next(); - } - } - results.push(doc); - next(); - } - if (opts.include_docs) { - var seq = metadata.rev_map[winningRev]; - stores.bySeqStore.get(formatSeq(seq), function (err, data) { - allDocsInner(data); - }); - } - else { - allDocsInner(); - } - }, function (next) { - PouchPromise.resolve().then(function () { - if (opts.include_docs && opts.attachments) { - return fetchAttachments(results, stores, opts); - } - }).then(function () { - callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: results - }); - }, callback); - next(); - }).on('unpipe', function () { - throughStream.end(); - }); - - docstream.on('error', callback); - - docstream.pipe(throughStream); - }); - }); - - api._changes = function (opts) { - opts = clone$1(opts); - - if (opts.continuous) { - var id = name + ':' + uuid(); - levelChanges.addListener(name, id, api, opts); - levelChanges.notify(name); - return { - cancel: function () { - levelChanges.removeListener(name, id); - } - }; - } - - var descending = opts.descending; - var results = []; - var lastSeq = opts.since || 0; - var called = 0; - var streamOpts = { - reverse: descending - }; - var limit; - if ('limit' in opts && opts.limit > 0) { - limit = opts.limit; - } - if (!streamOpts.reverse) { - streamOpts.start = formatSeq(opts.since || 0); - } - - var docIds = opts.doc_ids && new _Set(opts.doc_ids); - var filter = filterChange(opts); - var docIdsToMetadata = new _Map(); - - var returnDocs; - if ('return_docs' in opts) { - returnDocs = opts.return_docs; - } else if ('returnDocs' in opts) { - // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release - returnDocs = opts.returnDocs; - } else { - returnDocs = true; - } - - function complete() { - opts.done = true; - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - changeStream.unpipe(throughStream); - changeStream.destroy(); - if (!opts.continuous && !opts.cancelled) { - if (opts.include_docs && opts.attachments) { - fetchAttachments(results, stores, opts).then(function () { - opts.complete(null, {results: results, last_seq: lastSeq}); - }); - } else { - opts.complete(null, {results: results, last_seq: lastSeq}); - } - } - } - var changeStream = stores.bySeqStore.readStream(streamOpts); - var throughStream = through2.obj(function (data, _, next) { - if (limit && called >= limit) { - complete(); - return next(); - } - if (opts.cancelled || opts.done) { - return next(); - } - - var seq = parseSeq(data.key); - var doc = data.value; - - if (seq === opts.since && !descending) { - // couchdb ignores `since` if descending=true - return next(); - } - - if (docIds && !docIds.has(doc._id)) { - return next(); - } - - var metadata; - - function onGetMetadata(metadata) { - var winningRev = getWinningRev(metadata); - - function onGetWinningDoc(winningDoc) { - - var change = opts.processChange(winningDoc, metadata, opts); - change.seq = metadata.seq; - - var filtered = filter(change); - if (typeof filtered === 'object') { - return opts.complete(filtered); - } - - if (filtered) { - called++; - - if (opts.attachments && opts.include_docs) { - // fetch attachment immediately for the benefit - // of live listeners - fetchAttachments([change], stores, opts).then(function () { - opts.onChange(change); - }); - } else { - opts.onChange(change); - } - - if (returnDocs) { - results.push(change); - } - } - next(); - } - - if (metadata.seq !== seq) { - // some other seq is later - return next(); - } - - lastSeq = seq; - - if (winningRev === doc._rev) { - return onGetWinningDoc(doc); - } - - // fetch the winner - - var winningSeq = metadata.rev_map[winningRev]; - - stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) { - onGetWinningDoc(doc); - }); - } - - metadata = docIdsToMetadata.get(doc._id); - if (metadata) { // cached - return onGetMetadata(metadata); - } - // metadata not cached, have to go fetch it - stores.docStore.get(doc._id, function (err, metadata) { - /* istanbul ignore if */ - if (opts.cancelled || opts.done || db.isClosed() || - isLocalId(metadata.id)) { - return next(); - } - docIdsToMetadata.set(doc._id, metadata); - onGetMetadata(metadata); - }); - }, function (next) { - if (opts.cancelled) { - return next(); - } - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - - next(); - }).on('unpipe', function () { - throughStream.end(); - complete(); - }); - changeStream.pipe(throughStream); - return { - cancel: function () { - opts.cancelled = true; - complete(); - } - }; - }; - - api._close = function (callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(createError(NOT_OPEN)); - } - db.close(function (err) { - /* istanbul ignore if */ - if (err) { - callback(err); - } else { - dbStore.delete(name); - callback(); - } - }); - }; - - api._getRevisionTree = function (docId, callback) { - stores.docStore.get(docId, function (err, metadata) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, metadata.rev_tree); - } - }); - }; - - api._doCompaction = writeLock(function (docId, revs, opts, callback) { - api._doCompactionNoLock(docId, revs, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._doCompactionNoLock = function (docId, revs, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - - if (!revs.length) { - return callback(); - } - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.docStore, docId, function (err, metadata) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var seqs = revs.map(function (rev) { - var seq = metadata.rev_map[rev]; - delete metadata.rev_map[rev]; - return seq; - }); - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - var rev = pos + '-' + revHash; - if (revs.indexOf(rev) !== -1) { - opts.status = 'missing'; - } - }); - - var batch = []; - batch.push({ - key: metadata.id, - value: metadata, - type: 'put', - prefix: stores.docStore - }); - - var digestMap = {}; - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === revs.length) { // done - /* istanbul ignore if */ - if (overallErr) { - return callback(overallErr); - } - deleteOrphanedAttachments(); - } - } - - function finish(err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - txn.batch(batch); - if (opts.ctx) { - // don't execute immediately - return callback(); - } - txn.execute(db, callback); - } - - function deleteOrphanedAttachments() { - var possiblyOrphanedAttachments = Object.keys(digestMap); - if (!possiblyOrphanedAttachments.length) { - return finish(); - } - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === possiblyOrphanedAttachments.length) { - finish(overallErr); - } - } - var refsToDelete = new _Map(); - revs.forEach(function (rev) { - refsToDelete.set(docId + '@' + rev, true); - }); - possiblyOrphanedAttachments.forEach(function (digest) { - txn.get(stores.attachmentStore, digest, function (err, attData) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var refs = Object.keys(attData.refs || {}).filter(function (ref) { - return !refsToDelete.has(ref); - }); - var newRefs = {}; - refs.forEach(function (ref) { - newRefs[ref] = true; - }); - if (refs.length) { // not orphaned - batch.push({ - key: digest, - type: 'put', - value: {refs: newRefs}, - prefix: stores.attachmentStore - }); - } else { // orphaned, can safely delete - batch = batch.concat([{ - key: digest, - type: 'del', - prefix: stores.attachmentStore - }, { - key: digest, - type: 'del', - prefix: stores.binaryStore - }]); - } - checkDone(); - }); - }); - } - - seqs.forEach(function (seq) { - batch.push({ - key: formatSeq(seq), - type: 'del', - prefix: stores.bySeqStore - }); - txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var atts = Object.keys(doc._attachments || {}); - atts.forEach(function (attName) { - var digest = doc._attachments[attName].digest; - digestMap[digest] = true; - }); - checkDone(); - }); - }); - }); - }; - - api._getLocal = function (id, callback) { - stores.localStore.get(id, function (err, doc) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, doc); - } - }); - }; - - api._putLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._putLocalNoLock(doc, opts, callback); - } else { - api._putLocalWithLock(doc, opts, callback); - } - }; - - api._putLocalWithLock = writeLock(function (doc, opts, callback) { - api._putLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._putLocalNoLock = function (doc, opts, callback) { - delete doc._revisions; // ignore this, trust the rev - var oldRev = doc._rev; - var id = doc._id; - - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.localStore, id, function (err, resp) { - if (err && oldRev) { - return callback(createError(REV_CONFLICT)); - } - if (resp && resp._rev !== oldRev) { - return callback(createError(REV_CONFLICT)); - } - doc._rev = - oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1'; - var batch = [ - { - type: 'put', - prefix: stores.localStore, - key: id, - value: doc - } - ]; - - txn.batch(batch); - var ret = {ok: true, id: doc._id, rev: doc._rev}; - - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - api._removeLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._removeLocalNoLock(doc, opts, callback); - } else { - api._removeLocalWithLock(doc, opts, callback); - } - }; - - api._removeLocalWithLock = writeLock(function (doc, opts, callback) { - api._removeLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._removeLocalNoLock = function (doc, opts, callback) { - var txn = opts.ctx || new LevelTransaction(); - txn.get(stores.localStore, doc._id, function (err, resp) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } else { - return callback(createError(MISSING_DOC)); - } - } - if (resp._rev !== doc._rev) { - return callback(createError(REV_CONFLICT)); - } - txn.batch([{ - prefix: stores.localStore, - type: 'del', - key: doc._id - }]); - var ret = {ok: true, id: doc._id, rev: '0-0'}; - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - // close and delete open leveldb stores - api._destroy = function (opts, callback) { - var dbStore; - var leveldownName = functionName(leveldown); - /* istanbul ignore else */ - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - return callDestroy(name, callback); - } - - /* istanbul ignore else */ - if (dbStore.has(name)) { - levelChanges.removeAllListeners(name); - - dbStore.get(name).close(function () { - dbStore.delete(name); - callDestroy(name, callback); - }); - } else { - callDestroy(name, callback); - } - }; - function callDestroy(name, cb) { - leveldown.destroy(name, cb); - } -} - -function LocalStoragePouch(opts, callback) { - var _opts = jsExtend.extend({ - db: localstoragedown - }, opts); - - LevelPouch.call(this, _opts, callback); -} - -// overrides for normal LevelDB behavior on Node -LocalStoragePouch.valid = function () { - return typeof localStorage !== 'undefined'; -}; -LocalStoragePouch.use_prefix = true; - -function LocalStoragePouchPlugin (PouchDB) { - PouchDB.adapter('localstorage', LocalStoragePouch, true); -} - -/* global PouchDB */ - -var PDB = (typeof PouchDB !== 'undefined') ? PouchDB : require('pouchdb'); -if (!PDB) { - guardedConsole('error', 'localstorage adapter plugin error: ' + - 'Cannot find global "PouchDB" object! ' + - 'Did you remember to include pouchdb.js?'); -} else { - LocalStoragePouchPlugin(PDB); -} \ No newline at end of file diff --git a/lib/pouchdb/lib/plugins/memory.js b/lib/pouchdb/lib/plugins/memory.js deleted file mode 100644 index f77d7b50..00000000 --- a/lib/pouchdb/lib/plugins/memory.js +++ /dev/null @@ -1,3528 +0,0 @@ -'use strict'; - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var levelup = _interopDefault(require('levelup')); -var ltgt = _interopDefault(require('ltgt')); -var events = require('events'); -var events__default = _interopDefault(events); -var inherits = _interopDefault(require('inherits')); -var Codec = _interopDefault(require('level-codec')); -var ReadableStreamCore = _interopDefault(require('readable-stream')); -var through2 = require('through2'); -var getArguments = _interopDefault(require('argsarray')); -var Deque = _interopDefault(require('double-ended-queue')); -var lie = _interopDefault(require('lie')); -var debug = _interopDefault(require('debug')); -var Md5 = _interopDefault(require('spark-md5')); -var vuvuzela = _interopDefault(require('vuvuzela')); -var jsExtend = require('js-extend'); -var memdown = _interopDefault(require('memdown')); - -function isFunction(f) { - return 'function' === typeof f; -} - -function getPrefix(db) { - if (isFunction(db.prefix)) { - return db.prefix(); - } - return db; -} - -function clone(_obj) { - var obj = {}; - for(var k in _obj) { - obj[k] = _obj[k]; - } - return obj; -} - -function nut(db, precodec, codec) { - function encodePrefix(prefix, key, opts1, opts2) { - return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]); - } - - function addEncodings(op, prefix) { - if(prefix && prefix.options) { - op.keyEncoding = - op.keyEncoding || prefix.options.keyEncoding; - op.valueEncoding = - op.valueEncoding || prefix.options.valueEncoding; - } - return op; - } - - db.open(function () { /* no-op */}); - - return { - apply: function (ops, opts, cb) { - opts = opts || {}; - - var batch = []; - var i = -1; - var len = ops.length; - - while (++i < len) { - var op = ops[i]; - addEncodings(op, op.prefix); - op.prefix = getPrefix(op.prefix); - batch.push({ - key: encodePrefix(op.prefix, op.key, opts, op), - value: op.type !== 'del' && codec.encodeValue(op.value, opts, op), - type: op.type - }); - } - db.db.batch(batch, opts, cb); - }, - get: function (key, prefix, opts, cb) { - opts.asBuffer = codec.valueAsBuffer(opts); - return db.db.get( - encodePrefix(prefix, key, opts), - opts, - function (err, value) { - if (err) { - cb(err); - } else { - cb(null, codec.decodeValue(value, opts)); - } - } - ); - }, - createDecoder: function (opts) { - return function (key, value) { - return { - key: codec.decodeKey(precodec.decode(key)[1], opts), - value: codec.decodeValue(value, opts) - }; - }; - }, - isClosed: function isClosed() { - return db.isClosed(); - }, - close: function close(cb) { - return db.close(cb); - }, - iterator: function (_opts) { - var opts = clone(_opts || {}); - var prefix = _opts.prefix || []; - - function encodeKey(key) { - return encodePrefix(prefix, key, opts, {}); - } - - ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound); - - // if these legacy values are in the options, remove them - - opts.prefix = null; - - //************************************************ - //hard coded defaults, for now... - //TODO: pull defaults and encoding out of levelup. - opts.keyAsBuffer = opts.valueAsBuffer = false; - //************************************************ - - - //this is vital, otherwise limit: undefined will - //create an empty stream. - /* istanbul ignore next */ - if ('number' !== typeof opts.limit) { - opts.limit = -1; - } - - opts.keyAsBuffer = precodec.buffer; - opts.valueAsBuffer = codec.valueAsBuffer(opts); - - function wrapIterator(iterator) { - return { - next: function (cb) { - return iterator.next(cb); - }, - end: function (cb) { - iterator.end(cb); - } - }; - } - - return wrapIterator(db.db.iterator(opts)); - } - }; -} - -function NotFoundError(reason) { - Error.call(this, reason); -} - -inherits(NotFoundError, Error); - -NotFoundError.prototype.name = 'NotFoundError'; - -var EventEmitter$1 = events__default.EventEmitter; -var version = "6.5.4"; - -var sublevel = function (nut, prefix, createStream, options) { - var emitter = new EventEmitter$1(); - emitter.sublevels = {}; - emitter.options = options; - - emitter.version = version; - - emitter.methods = {}; - prefix = prefix || []; - - function mergeOpts(opts) { - var o = {}; - var k; - if (options) { - for (k in options) { - if (typeof options[k] !== 'undefined') { - o[k] = options[k]; - } - } - } - if (opts) { - for (k in opts) { - if (typeof opts[k] !== 'undefined') { - o[k] = opts[k]; - } - } - } - return o; - } - - emitter.put = function (key, value, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - nut.apply([{ - key: key, value: value, - prefix: prefix.slice(), type: 'put' - }], mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('put', key, value); - cb(null); - }); - }; - - emitter.prefix = function () { - return prefix.slice(); - }; - - emitter.batch = function (ops, opts, cb) { - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - - ops = ops.map(function (op) { - return { - key: op.key, - value: op.value, - prefix: op.prefix || prefix, - keyEncoding: op.keyEncoding, // * - valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel) - type: op.type - }; - }); - - nut.apply(ops, mergeOpts(opts), function (err) { - /* istanbul ignore next */ - if (err) { - return cb(err); - } - emitter.emit('batch', ops); - cb(null); - }); - }; - - emitter.get = function (key, opts, cb) { - /* istanbul ignore else */ - if ('function' === typeof opts) { - cb = opts; - opts = {}; - } - nut.get(key, prefix, mergeOpts(opts), function (err, value) { - if (err) { - cb(new NotFoundError(err)); - } else { - cb(null, value); - } - }); - }; - - emitter.sublevel = function (name, opts) { - return emitter.sublevels[name] = - emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts)); - }; - - emitter.readStream = emitter.createReadStream = function (opts) { - opts = mergeOpts(opts); - opts.prefix = prefix; - var stream; - var it = nut.iterator(opts); - - stream = createStream(opts, nut.createDecoder(opts)); - stream.setIterator(it); - - return stream; - }; - - emitter.close = function (cb) { - nut.close(cb); - }; - - emitter.isOpen = nut.isOpen; - emitter.isClosed = nut.isClosed; - - return emitter; -}; - -/* Copyright (c) 2012-2014 LevelUP contributors - * See list at - * MIT License - */ - -// NOTE: we are fixed to readable-stream@1.0.x for now -// for pure Streams2 across Node versions -var Readable = ReadableStreamCore.Readable; - -function ReadStream(options, makeData) { - if (!(this instanceof ReadStream)) { - return new ReadStream(options, makeData); - } - - Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); - - // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref - - this._waiting = false; - this._options = options; - this._makeData = makeData; -} - -inherits(ReadStream, Readable); - -ReadStream.prototype.setIterator = function (it) { - this._iterator = it; - /* istanbul ignore if */ - if (this._destroyed) { - return it.end(function () {}); - } - /* istanbul ignore if */ - if (this._waiting) { - this._waiting = false; - return this._read(); - } - return this; -}; - -ReadStream.prototype._read = function read() { - var self = this; - /* istanbul ignore if */ - if (self._destroyed) { - return; - } - /* istanbul ignore if */ - if (!self._iterator) { - return this._waiting = true; - } - - self._iterator.next(function (err, key, value) { - if (err || (key === undefined && value === undefined)) { - if (!err && !self._destroyed) { - self.push(null); - } - return self._cleanup(err); - } - - - value = self._makeData(key, value); - if (!self._destroyed) { - self.push(value); - } - }); -}; - -ReadStream.prototype._cleanup = function (err) { - if (this._destroyed) { - return; - } - - this._destroyed = true; - - var self = this; - /* istanbul ignore if */ - if (err) { - self.emit('error', err); - } - - /* istanbul ignore else */ - if (self._iterator) { - self._iterator.end(function () { - self._iterator = null; - self.emit('close'); - }); - } else { - self.emit('close'); - } -}; - -ReadStream.prototype.destroy = function () { - this._cleanup(); -}; - -var precodec = { - encode: function (decodedKey) { - return '\xff' + decodedKey[0] + '\xff' + decodedKey[1]; - }, - decode: function (encodedKeyAsBuffer) { - var str = encodedKeyAsBuffer.toString(); - var idx = str.indexOf('\xff', 1); - return [str.substring(1, idx), str.substring(idx + 1)]; - }, - lowerBound: '\x00', - upperBound: '\xff' -}; - -var codec = new Codec(); - -function sublevelPouch(db) { - return sublevel(nut(db, precodec, codec), [], ReadStream, db.options); -} - -// based on https://github.com/montagejs/collections -function mangle(key) { - return '$' + key; -} -function unmangle(key) { - return key.substring(1); -} -function _Map() { - this.store = {}; -} -_Map.prototype.get = function (key) { - var mangled = mangle(key); - return this.store[mangled]; -}; -_Map.prototype.set = function (key, value) { - var mangled = mangle(key); - this.store[mangled] = value; - return true; -}; -_Map.prototype.has = function (key) { - var mangled = mangle(key); - return mangled in this.store; -}; -_Map.prototype.delete = function (key) { - var mangled = mangle(key); - var res = mangled in this.store; - delete this.store[mangled]; - return res; -}; -_Map.prototype.forEach = function (cb) { - var keys = Object.keys(this.store); - for (var i = 0, len = keys.length; i < len; i++) { - var key = keys[i]; - var value = this.store[key]; - key = unmangle(key); - cb(value, key); - } -}; - -function _Set(array) { - this.store = new _Map(); - - // init with an array - if (array && Array.isArray(array)) { - for (var i = 0, len = array.length; i < len; i++) { - this.add(array[i]); - } - } -} -_Set.prototype.add = function (key) { - return this.store.set(key, true); -}; -_Set.prototype.has = function (key) { - return this.store.has(key); -}; - -// in the browser, LevelAlt doesn't need the -// pre-2.2.0 LevelDB-specific migrations -var toSublevel = function (name, db, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var localAndMetaStores = function (db, stores, callback) { - process.nextTick(function () { - callback(); - }); -}; - -var migrate = { - toSublevel: toSublevel, - localAndMetaStores: localAndMetaStores -}; - -/* istanbul ignore next */ -var PouchPromise = typeof Promise === 'function' ? Promise : lie; - -function isBinaryObject(object) { - return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) || - (typeof Blob !== 'undefined' && object instanceof Blob); -} - -function cloneArrayBuffer(buff) { - if (typeof buff.slice === 'function') { - return buff.slice(0); - } - // IE10-11 slice() polyfill - var target = new ArrayBuffer(buff.byteLength); - var targetArray = new Uint8Array(target); - var sourceArray = new Uint8Array(buff); - targetArray.set(sourceArray); - return target; -} - -function cloneBinaryObject(object) { - if (object instanceof ArrayBuffer) { - return cloneArrayBuffer(object); - } - var size = object.size; - var type = object.type; - // Blob - if (typeof object.slice === 'function') { - return object.slice(0, size, type); - } - // PhantomJS slice() replacement - return object.webkitSlice(0, size, type); -} - -// most of this is borrowed from lodash.isPlainObject: -// https://github.com/fis-components/lodash.isplainobject/ -// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js - -var funcToString = Function.prototype.toString; -var objectCtorString = funcToString.call(Object); - -function isPlainObject(value) { - var proto = Object.getPrototypeOf(value); - /* istanbul ignore if */ - if (proto === null) { // not sure when this happens, but I guess it can - return true; - } - var Ctor = proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} - -function clone$1(object) { - var newObject; - var i; - var len; - - if (!object || typeof object !== 'object') { - return object; - } - - if (Array.isArray(object)) { - newObject = []; - for (i = 0, len = object.length; i < len; i++) { - newObject[i] = clone$1(object[i]); - } - return newObject; - } - - // special case: to avoid inconsistencies between IndexedDB - // and other backends, we automatically stringify Dates - if (object instanceof Date) { - return object.toISOString(); - } - - if (isBinaryObject(object)) { - return cloneBinaryObject(object); - } - - if (!isPlainObject(object)) { - return object; // don't clone objects like Workers - } - - newObject = {}; - for (i in object) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(object, i)) { - var value = clone$1(object[i]); - if (typeof value !== 'undefined') { - newObject[i] = value; - } - } - } - return newObject; -} - -var log = debug('pouchdb:api'); - -// like underscore/lodash _.pick() -function pick(obj, arr) { - var res = {}; - for (var i = 0, len = arr.length; i < len; i++) { - var prop = arr[i]; - if (prop in obj) { - res[prop] = obj[prop]; - } - } - return res; -} - -function isChromeApp() { - return (typeof chrome !== "undefined" && - typeof chrome.storage !== "undefined" && - typeof chrome.storage.local !== "undefined"); -} - -var hasLocal; - -if (isChromeApp()) { - hasLocal = false; -} else { - try { - localStorage.setItem('_pouch_check_localstorage', 1); - hasLocal = !!localStorage.getItem('_pouch_check_localstorage'); - } catch (e) { - hasLocal = false; - } -} - -function hasLocalStorage() { - return hasLocal; -} - -inherits(Changes, events.EventEmitter); - -/* istanbul ignore next */ -function attachBrowserEvents(self) { - if (isChromeApp()) { - chrome.storage.onChanged.addListener(function (e) { - // make sure it's event addressed to us - if (e.db_name != null) { - //object only has oldValue, newValue members - self.emit(e.dbName.newValue); - } - }); - } else if (hasLocalStorage()) { - if (typeof addEventListener !== 'undefined') { - addEventListener("storage", function (e) { - self.emit(e.key); - }); - } else { // old IE - window.attachEvent("storage", function (e) { - self.emit(e.key); - }); - } - } -} - -function Changes() { - events.EventEmitter.call(this); - this._listeners = {}; - - attachBrowserEvents(this); -} -Changes.prototype.addListener = function (dbName, id, db, opts) { - /* istanbul ignore if */ - if (this._listeners[id]) { - return; - } - var self = this; - var inprogress = false; - function eventFunction() { - /* istanbul ignore if */ - if (!self._listeners[id]) { - return; - } - if (inprogress) { - inprogress = 'waiting'; - return; - } - inprogress = true; - var changesOpts = pick(opts, [ - 'style', 'include_docs', 'attachments', 'conflicts', 'filter', - 'doc_ids', 'view', 'since', 'query_params', 'binary' - ]); - - /* istanbul ignore next */ - function onError() { - inprogress = false; - } - - db.changes(changesOpts).on('change', function (c) { - if (c.seq > opts.since && !opts.cancelled) { - opts.since = c.seq; - opts.onChange(c); - } - }).on('complete', function () { - if (inprogress === 'waiting') { - setTimeout(function (){ - eventFunction(); - },0); - } - inprogress = false; - }).on('error', onError); - } - this._listeners[id] = eventFunction; - this.on(dbName, eventFunction); -}; - -Changes.prototype.removeListener = function (dbName, id) { - /* istanbul ignore if */ - if (!(id in this._listeners)) { - return; - } - events.EventEmitter.prototype.removeListener.call(this, dbName, - this._listeners[id]); - delete this._listeners[id]; -}; - - -/* istanbul ignore next */ -Changes.prototype.notifyLocalWindows = function (dbName) { - //do a useless change on a storage thing - //in order to get other windows's listeners to activate - if (isChromeApp()) { - chrome.storage.local.set({dbName: dbName}); - } else if (hasLocalStorage()) { - localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; - } -}; - -Changes.prototype.notify = function (dbName) { - this.emit(dbName); - this.notifyLocalWindows(dbName); -}; - -function guardedConsole(method) { - /* istanbul ignore else */ - if (console !== 'undefined' && method in console) { - var args = Array.prototype.slice.call(arguments, 1); - console[method].apply(console, args); - } -} - -inherits(PouchError, Error); - -function PouchError(opts) { - Error.call(this, opts.reason); - this.status = opts.status; - this.name = opts.error; - this.message = opts.reason; - this.error = true; -} - -PouchError.prototype.toString = function () { - return JSON.stringify({ - status: this.status, - name: this.name, - message: this.message, - reason: this.reason - }); -}; - -var UNAUTHORIZED = new PouchError({ - status: 401, - error: 'unauthorized', - reason: "Name or password is incorrect." -}); - -var MISSING_BULK_DOCS = new PouchError({ - status: 400, - error: 'bad_request', - reason: "Missing JSON list of 'docs'" -}); - -var MISSING_DOC = new PouchError({ - status: 404, - error: 'not_found', - reason: 'missing' -}); - -var REV_CONFLICT = new PouchError({ - status: 409, - error: 'conflict', - reason: 'Document update conflict' -}); - -var INVALID_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: '_id field must contain a string' -}); - -var MISSING_ID = new PouchError({ - status: 412, - error: 'missing_id', - reason: '_id is required for puts' -}); - -var RESERVED_ID = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Only reserved document ids may start with underscore.' -}); - -var NOT_OPEN = new PouchError({ - status: 412, - error: 'precondition_failed', - reason: 'Database not open' -}); - -var UNKNOWN_ERROR = new PouchError({ - status: 500, - error: 'unknown_error', - reason: 'Database encountered an unknown error' -}); - -var BAD_ARG = new PouchError({ - status: 500, - error: 'badarg', - reason: 'Some query argument is invalid' -}); - -var INVALID_REQUEST = new PouchError({ - status: 400, - error: 'invalid_request', - reason: 'Request was invalid' -}); - -var QUERY_PARSE_ERROR = new PouchError({ - status: 400, - error: 'query_parse_error', - reason: 'Some query parameter is invalid' -}); - -var DOC_VALIDATION = new PouchError({ - status: 500, - error: 'doc_validation', - reason: 'Bad special document member' -}); - -var BAD_REQUEST = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Something wrong with the request' -}); - -var NOT_AN_OBJECT = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Document must be a JSON object' -}); - -var DB_MISSING = new PouchError({ - status: 404, - error: 'not_found', - reason: 'Database not found' -}); - -var IDB_ERROR = new PouchError({ - status: 500, - error: 'indexed_db_went_bad', - reason: 'unknown' -}); - -var WSQ_ERROR = new PouchError({ - status: 500, - error: 'web_sql_went_bad', - reason: 'unknown' -}); - -var LDB_ERROR = new PouchError({ - status: 500, - error: 'levelDB_went_went_bad', - reason: 'unknown' -}); - -var FORBIDDEN = new PouchError({ - status: 403, - error: 'forbidden', - reason: 'Forbidden by design doc validate_doc_update function' -}); - -var INVALID_REV = new PouchError({ - status: 400, - error: 'bad_request', - reason: 'Invalid rev format' -}); - -var FILE_EXISTS = new PouchError({ - status: 412, - error: 'file_exists', - reason: 'The database could not be created, the file already exists.' -}); - -var MISSING_STUB = new PouchError({ - status: 412, - error: 'missing_stub' -}); - -var INVALID_URL = new PouchError({ - status: 413, - error: 'invalid_url', - reason: 'Provided URL is invalid' -}); - -function createError(error, reason) { - function CustomPouchError(reason) { - // inherit error properties from our parent error manually - // so as to allow proper JSON parsing. - /* jshint ignore:start */ - for (var p in error) { - if (typeof error[p] !== 'function') { - this[p] = error[p]; - } - } - /* jshint ignore:end */ - if (reason !== undefined) { - this.reason = reason; - } - } - CustomPouchError.prototype = PouchError.prototype; - return new CustomPouchError(reason); -} - -function tryFilter(filter, doc, req) { - try { - return !filter(doc, req); - } catch (err) { - var msg = 'Filter function threw: ' + err.toString(); - return createError(BAD_REQUEST, msg); - } -} - -function filterChange(opts) { - var req = {}; - var hasFilter = opts.filter && typeof opts.filter === 'function'; - req.query = opts.query_params; - - return function filter(change) { - if (!change.doc) { - // CSG sends events on the changes feed that don't have documents, - // this hack makes a whole lot of existing code robust. - change.doc = {}; - } - - var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req); - - if (typeof filterReturn === 'object') { - return filterReturn; - } - - if (filterReturn) { - return false; - } - - if (!opts.include_docs) { - delete change.doc; - } else if (!opts.attachments) { - for (var att in change.doc._attachments) { - /* istanbul ignore else */ - if (change.doc._attachments.hasOwnProperty(att)) { - change.doc._attachments[att].stub = true; - } - } - } - return true; - }; -} - -// shim for Function.prototype.name, -// for browsers that don't support it like IE - -/* istanbul ignore next */ -function f() {} - -var hasName = f.name; -var res; - -// We dont run coverage in IE -/* istanbul ignore else */ -if (hasName) { - res = function (fun) { - return fun.name; - }; -} else { - res = function (fun) { - return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; - }; -} - -var functionName = res; - -// Determine id an ID is valid -// - invalid IDs begin with an underescore that does not begin '_design' or -// '_local' -// - any other string value is a valid id -// Returns the specific error object for each case -function invalidIdError(id) { - var err; - if (!id) { - err = createError(MISSING_ID); - } else if (typeof id !== 'string') { - err = createError(INVALID_ID); - } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { - err = createError(RESERVED_ID); - } - if (err) { - throw err; - } -} - -// BEGIN Math.uuid.js - -/*! -Math.uuid.js (v1.4) -http://www.broofa.com -mailto:robert@broofa.com - -Copyright (c) 2010 Robert Kieffer -Dual licensed under the MIT and GPL licenses. -*/ - -/* - * Generate a random uuid. - * - * USAGE: Math.uuid(length, radix) - * length - the desired number of characters - * radix - the number of allowable values for each character. - * - * EXAMPLES: - * // No arguments - returns RFC4122, version 4 ID - * >>> Math.uuid() - * "92329D39-6F5C-4520-ABFC-AAB64544E172" - * - * // One argument - returns ID of the specified length - * >>> Math.uuid(15) // 15 character ID (default base=62) - * "VcydxgltxrVZSTV" - * - * // Two arguments - returns ID of the specified length, and radix. - * // (Radix must be <= 62) - * >>> Math.uuid(8, 2) // 8 character ID (base=2) - * "01001010" - * >>> Math.uuid(8, 10) // 8 character ID (base=10) - * "47473046" - * >>> Math.uuid(8, 16) // 8 character ID (base=16) - * "098F4D35" - */ -var chars = ( - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + - 'abcdefghijklmnopqrstuvwxyz' -).split(''); -function getValue(radix) { - return 0 | Math.random() * radix; -} -function uuid(len, radix) { - radix = radix || chars.length; - var out = ''; - var i = -1; - - if (len) { - // Compact form - while (++i < len) { - out += chars[getValue(radix)]; - } - return out; - } - // rfc4122, version 4 form - // Fill in random data. At i==19 set the high bits of clock sequence as - // per rfc4122, sec. 4.1.5 - while (++i < 36) { - switch (i) { - case 8: - case 13: - case 18: - case 23: - out += '-'; - break; - case 19: - out += chars[(getValue(16) & 0x3) | 0x8]; - break; - default: - out += chars[getValue(16)]; - } - } - - return out; -} - -function toObject(array) { - return array.reduce(function (obj, item) { - obj[item] = true; - return obj; - }, {}); -} -// List of top level reserved words for doc -var reservedWords = toObject([ - '_id', - '_rev', - '_attachments', - '_deleted', - '_revisions', - '_revs_info', - '_conflicts', - '_deleted_conflicts', - '_local_seq', - '_rev_tree', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats', - // Specific to Couchbase Sync Gateway - '_removed' -]); - -// List of reserved words that should end up the document -var dataWords = toObject([ - '_attachments', - //replication documents - '_replication_id', - '_replication_state', - '_replication_state_time', - '_replication_state_reason', - '_replication_stats' -]); - -function parseRevisionInfo(rev) { - if (!/^\d+\-./.test(rev)) { - return createError(INVALID_REV); - } - var idx = rev.indexOf('-'); - var left = rev.substring(0, idx); - var right = rev.substring(idx + 1); - return { - prefix: parseInt(left, 10), - id: right - }; -} - -function makeRevTreeFromRevisions(revisions, opts) { - var pos = revisions.start - revisions.ids.length + 1; - - var revisionIds = revisions.ids; - var ids = [revisionIds[0], opts, []]; - - for (var i = 1, len = revisionIds.length; i < len; i++) { - ids = [revisionIds[i], {status: 'missing'}, [ids]]; - } - - return [{ - pos: pos, - ids: ids - }]; -} - -// Preprocess documents, parse their revisions, assign an id and a -// revision for new writes that are missing them, etc -function parseDoc(doc, newEdits) { - - var nRevNum; - var newRevId; - var revInfo; - var opts = {status: 'available'}; - if (doc._deleted) { - opts.deleted = true; - } - - if (newEdits) { - if (!doc._id) { - doc._id = uuid(); - } - newRevId = uuid(32, 16).toLowerCase(); - if (doc._rev) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - doc._rev_tree = [{ - pos: revInfo.prefix, - ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]] - }]; - nRevNum = revInfo.prefix + 1; - } else { - doc._rev_tree = [{ - pos: 1, - ids : [newRevId, opts, []] - }]; - nRevNum = 1; - } - } else { - if (doc._revisions) { - doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); - nRevNum = doc._revisions.start; - newRevId = doc._revisions.ids[0]; - } - if (!doc._rev_tree) { - revInfo = parseRevisionInfo(doc._rev); - if (revInfo.error) { - return revInfo; - } - nRevNum = revInfo.prefix; - newRevId = revInfo.id; - doc._rev_tree = [{ - pos: nRevNum, - ids: [newRevId, opts, []] - }]; - } - } - - invalidIdError(doc._id); - - doc._rev = nRevNum + '-' + newRevId; - - var result = {metadata : {}, data : {}}; - for (var key in doc) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(doc, key)) { - var specialKey = key[0] === '_'; - if (specialKey && !reservedWords[key]) { - var error = createError(DOC_VALIDATION, key); - error.message = DOC_VALIDATION.message + ': ' + key; - throw error; - } else if (specialKey && !dataWords[key]) { - result.metadata[key.slice(1)] = doc[key]; - } else { - result.data[key] = doc[key]; - } - } - } - return result; -} - -// We fetch all leafs of the revision tree, and sort them based on tree length -// and whether they were deleted, undeleted documents with the longest revision -// tree (most edits) win -// The final sort algorithm is slightly documented in a sidebar here: -// http://guide.couchdb.org/draft/conflicts.html -function winningRev(metadata) { - var winningId; - var winningPos; - var winningDeleted; - var toVisit = metadata.rev_tree.slice(); - var node; - while ((node = toVisit.pop())) { - var tree = node.ids; - var branches = tree[2]; - var pos = node.pos; - if (branches.length) { // non-leaf - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i]}); - } - continue; - } - var deleted = !!tree[1].deleted; - var id = tree[0]; - // sort by deleted, then pos, then id - if (!winningId || (winningDeleted !== deleted ? winningDeleted : - winningPos !== pos ? winningPos < pos : winningId < id)) { - winningId = id; - winningPos = pos; - winningDeleted = deleted; - } - } - - return winningPos + '-' + winningId; -} - -// Pretty much all below can be combined into a higher order function to -// traverse revisions -// The return value from the callback will be passed as context to all -// children of that node -function traverseRevTree(revs, callback) { - var toVisit = revs.slice(); - - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var branches = tree[2]; - var newCtx = - callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]); - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx}); - } - } -} - -function sortByPos(a, b) { - return a.pos - b.pos; -} - -function collectLeaves(revs) { - var leaves = []; - traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) { - if (isLeaf) { - leaves.push({rev: pos + "-" + id, pos: pos, opts: opts}); - } - }); - leaves.sort(sortByPos).reverse(); - for (var i = 0, len = leaves.length; i < len; i++) { - delete leaves[i].pos; - } - return leaves; -} - -// returns revs of all conflicts that is leaves such that -// 1. are not deleted and -// 2. are different than winning revision -function collectConflicts(metadata) { - var win = winningRev(metadata); - var leaves = collectLeaves(metadata.rev_tree); - var conflicts = []; - for (var i = 0, len = leaves.length; i < len; i++) { - var leaf = leaves[i]; - if (leaf.rev !== win && !leaf.opts.deleted) { - conflicts.push(leaf.rev); - } - } - return conflicts; -} - -// compact a tree by marking its non-leafs as missing, -// and return a list of revs to delete -function compactTree(metadata) { - var revs = []; - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - if (opts.status === 'available' && !isLeaf) { - revs.push(pos + '-' + revHash); - opts.status = 'missing'; - } - }); - return revs; -} - -// build up a list of all the paths to the leafs in this revision tree -function rootToLeaf(revs) { - var paths = []; - var toVisit = revs.slice(); - var node; - while ((node = toVisit.pop())) { - var pos = node.pos; - var tree = node.ids; - var id = tree[0]; - var opts = tree[1]; - var branches = tree[2]; - var isLeaf = branches.length === 0; - - var history = node.history ? node.history.slice() : []; - history.push({id: id, opts: opts}); - if (isLeaf) { - paths.push({pos: (pos + 1 - history.length), ids: history}); - } - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: pos + 1, ids: branches[i], history: history}); - } - } - return paths.reverse(); -} - -// for a better overview of what this is doing, read: -// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl -// -// But for a quick intro, CouchDB uses a revision tree to store a documents -// history, A -> B -> C, when a document has conflicts, that is a branch in the -// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format -// -// KeyTree = [Path ... ] -// Path = {pos: position_from_root, ids: Tree} -// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []] - -function sortByPos$1(a, b) { - return a.pos - b.pos; -} - -// classic binary search -function binarySearch(arr, item, comparator) { - var low = 0; - var high = arr.length; - var mid; - while (low < high) { - mid = (low + high) >>> 1; - if (comparator(arr[mid], item) < 0) { - low = mid + 1; - } else { - high = mid; - } - } - return low; -} - -// assuming the arr is sorted, insert the item in the proper place -function insertSorted(arr, item, comparator) { - var idx = binarySearch(arr, item, comparator); - arr.splice(idx, 0, item); -} - -// Turn a path as a flat array into a tree with a single branch. -// If any should be stemmed from the beginning of the array, that's passed -// in as the second argument -function pathToTree(path, numStemmed) { - var root; - var leaf; - for (var i = numStemmed, len = path.length; i < len; i++) { - var node = path[i]; - var currentLeaf = [node.id, node.opts, []]; - if (leaf) { - leaf[2].push(currentLeaf); - leaf = currentLeaf; - } else { - root = leaf = currentLeaf; - } - } - return root; -} - -// compare the IDs of two trees -function compareTree(a, b) { - return a[0] < b[0] ? -1 : 1; -} - -// Merge two trees together -// The roots of tree1 and tree2 must be the same revision -function mergeTree(in_tree1, in_tree2) { - var queue = [{tree1: in_tree1, tree2: in_tree2}]; - var conflicts = false; - while (queue.length > 0) { - var item = queue.pop(); - var tree1 = item.tree1; - var tree2 = item.tree2; - - if (tree1[1].status || tree2[1].status) { - tree1[1].status = - (tree1[1].status === 'available' || - tree2[1].status === 'available') ? 'available' : 'missing'; - } - - for (var i = 0; i < tree2[2].length; i++) { - if (!tree1[2][0]) { - conflicts = 'new_leaf'; - tree1[2][0] = tree2[2][i]; - continue; - } - - var merged = false; - for (var j = 0; j < tree1[2].length; j++) { - if (tree1[2][j][0] === tree2[2][i][0]) { - queue.push({tree1: tree1[2][j], tree2: tree2[2][i]}); - merged = true; - } - } - if (!merged) { - conflicts = 'new_branch'; - insertSorted(tree1[2], tree2[2][i], compareTree); - } - } - } - return {conflicts: conflicts, tree: in_tree1}; -} - -function doMerge(tree, path, dontExpand) { - var restree = []; - var conflicts = false; - var merged = false; - var res; - - if (!tree.length) { - return {tree: [path], conflicts: 'new_leaf'}; - } - - for (var i = 0, len = tree.length; i < len; i++) { - var branch = tree[i]; - if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) { - // Paths start at the same position and have the same root, so they need - // merged - res = mergeTree(branch.ids, path.ids); - restree.push({pos: branch.pos, ids: res.tree}); - conflicts = conflicts || res.conflicts; - merged = true; - } else if (dontExpand !== true) { - // The paths start at a different position, take the earliest path and - // traverse up until it as at the same point from root as the path we - // want to merge. If the keys match we return the longer path with the - // other merged After stemming we dont want to expand the trees - - var t1 = branch.pos < path.pos ? branch : path; - var t2 = branch.pos < path.pos ? path : branch; - var diff = t2.pos - t1.pos; - - var candidateParents = []; - - var trees = []; - trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null}); - while (trees.length > 0) { - var item = trees.pop(); - if (item.diff === 0) { - if (item.ids[0] === t2.ids[0]) { - candidateParents.push(item); - } - continue; - } - var elements = item.ids[2]; - for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) { - trees.push({ - ids: elements[j], - diff: item.diff - 1, - parent: item.ids, - parentIdx: j - }); - } - } - - var el = candidateParents[0]; - - if (!el) { - restree.push(branch); - } else { - res = mergeTree(el.ids, t2.ids); - el.parent[2][el.parentIdx] = res.tree; - restree.push({pos: t1.pos, ids: t1.ids}); - conflicts = conflicts || res.conflicts; - merged = true; - } - } else { - restree.push(branch); - } - } - - // We didnt find - if (!merged) { - restree.push(path); - } - - restree.sort(sortByPos$1); - - return { - tree: restree, - conflicts: conflicts || 'internal_node' - }; -} - -// To ensure we dont grow the revision tree infinitely, we stem old revisions -function stem(tree, depth) { - // First we break out the tree into a complete list of root to leaf paths - var paths = rootToLeaf(tree); - var maybeStem = {}; - - var result; - for (var i = 0, len = paths.length; i < len; i++) { - // Then for each path, we cut off the start of the path based on the - // `depth` to stem to, and generate a new set of flat trees - var path = paths[i]; - var stemmed = path.ids; - var numStemmed = Math.max(0, stemmed.length - depth); - var stemmedNode = { - pos: path.pos + numStemmed, - ids: pathToTree(stemmed, numStemmed) - }; - - for (var s = 0; s < numStemmed; s++) { - var rev = (path.pos + s) + '-' + stemmed[s].id; - maybeStem[rev] = true; - } - - // Then we remerge all those flat trees together, ensuring that we dont - // connect trees that would go beyond the depth limit - if (result) { - result = doMerge(result, stemmedNode, true).tree; - } else { - result = [stemmedNode]; - } - } - - traverseRevTree(result, function (isLeaf, pos, revHash) { - // some revisions may have been removed in a branch but not in another - delete maybeStem[pos + '-' + revHash]; - }); - - return { - tree: result, - revs: Object.keys(maybeStem) - }; -} - -function merge(tree, path, depth) { - var newTree = doMerge(tree, path); - var stemmed = stem(newTree.tree, depth); - return { - tree: stemmed.tree, - stemmedRevs: stemmed.revs, - conflicts: newTree.conflicts - }; -} - -// return true if a rev exists in the rev tree, false otherwise -function revExists(revs, rev) { - var toVisit = revs.slice(); - var splitRev = rev.split('-'); - var targetPos = parseInt(splitRev[0], 10); - var targetId = splitRev[1]; - - var node; - while ((node = toVisit.pop())) { - if (node.pos === targetPos && node.ids[0] === targetId) { - return true; - } - var branches = node.ids[2]; - for (var i = 0, len = branches.length; i < len; i++) { - toVisit.push({pos: node.pos + 1, ids: branches[i]}); - } - } - return false; -} - -function getTrees(node) { - return node.ids; -} - -// check if a specific revision of a doc has been deleted -// - metadata: the metadata object from the doc store -// - rev: (optional) the revision to check. defaults to winning revision -function isDeleted(metadata, rev) { - if (!rev) { - rev = winningRev(metadata); - } - var id = rev.substring(rev.indexOf('-') + 1); - var toVisit = metadata.rev_tree.map(getTrees); - - var tree; - while ((tree = toVisit.pop())) { - if (tree[0] === id) { - return !!tree[1].deleted; - } - toVisit = toVisit.concat(tree[2]); - } -} - -function isLocalId(id) { - return (/^_local/).test(id); -} - -var atob$1 = function (str) { - return atob(str); -}; - -var btoa$1 = function (str) { - return btoa(str); -}; - -// Abstracts constructing a Blob object, so it also works in older -// browsers that don't support the native Blob constructor (e.g. -// old QtWebKit versions, Android < 4.4). -function createBlob(parts, properties) { - /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ - parts = parts || []; - properties = properties || {}; - try { - return new Blob(parts, properties); - } catch (e) { - if (e.name !== "TypeError") { - throw e; - } - var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : - typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : - typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : - WebKitBlobBuilder; - var builder = new Builder(); - for (var i = 0; i < parts.length; i += 1) { - builder.append(parts[i]); - } - return builder.getBlob(properties.type); - } -} - -// From http://stackoverflow.com/questions/14967647/ (continues on next line) -// encode-decode-image-with-base64-breaks-image (2013-04-21) -function binaryStringToArrayBuffer(bin) { - var length = bin.length; - var buf = new ArrayBuffer(length); - var arr = new Uint8Array(buf); - for (var i = 0; i < length; i++) { - arr[i] = bin.charCodeAt(i); - } - return buf; -} - -function binStringToBluffer(binString, type) { - return createBlob([binaryStringToArrayBuffer(binString)], {type: type}); -} - -//Can't find original post, but this is close -//http://stackoverflow.com/questions/6965107/ (continues on next line) -//converting-between-strings-and-arraybuffers -function arrayBufferToBinaryString(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var length = bytes.byteLength; - for (var i = 0; i < length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return binary; -} - -// shim for browsers that don't support it -function readAsBinaryString(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(arrayBufferToBinaryString( - new FileReaderSync().readAsArrayBuffer(blob))); - } - - var reader = new FileReader(); - var hasBinaryString = typeof reader.readAsBinaryString === 'function'; - reader.onloadend = function (e) { - var result = e.target.result || ''; - if (hasBinaryString) { - return callback(result); - } - callback(arrayBufferToBinaryString(result)); - }; - if (hasBinaryString) { - reader.readAsBinaryString(blob); - } else { - reader.readAsArrayBuffer(blob); - } -} - -// simplified API. universal browser support is assumed -function readAsArrayBuffer(blob, callback) { - if (typeof FileReader === 'undefined') { - // fix for Firefox in a web worker: - // https://bugzilla.mozilla.org/show_bug.cgi?id=901097 - return callback(new FileReaderSync().readAsArrayBuffer(blob)); - } - - var reader = new FileReader(); - reader.onloadend = function (e) { - var result = e.target.result || new ArrayBuffer(0); - callback(result); - }; - reader.readAsArrayBuffer(blob); -} - -var setImmediateShim = global.setImmediate || global.setTimeout; -var MD5_CHUNK_SIZE = 32768; - -function rawToBase64(raw) { - return btoa$1(raw); -} - -function sliceBlob(blob, start, end) { - if (blob.webkitSlice) { - return blob.webkitSlice(start, end); - } - return blob.slice(start, end); -} - -function appendBlob(buffer, blob, start, end, callback) { - if (start > 0 || end < blob.size) { - // only slice blob if we really need to - blob = sliceBlob(blob, start, end); - } - readAsArrayBuffer(blob, function (arrayBuffer) { - buffer.append(arrayBuffer); - callback(); - }); -} - -function appendString(buffer, string, start, end, callback) { - if (start > 0 || end < string.length) { - // only create a substring if we really need to - string = string.substring(start, end); - } - buffer.appendBinary(string); - callback(); -} - -function binaryMd5(data, callback) { - var inputIsString = typeof data === 'string'; - var len = inputIsString ? data.length : data.size; - var chunkSize = Math.min(MD5_CHUNK_SIZE, len); - var chunks = Math.ceil(len / chunkSize); - var currentChunk = 0; - var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer(); - - var append = inputIsString ? appendString : appendBlob; - - function next() { - setImmediateShim(loadNextChunk); - } - - function done() { - var raw = buffer.end(true); - var base64 = rawToBase64(raw); - callback(base64); - buffer.destroy(); - } - - function loadNextChunk() { - var start = currentChunk * chunkSize; - var end = start + chunkSize; - currentChunk++; - if (currentChunk < chunks) { - append(buffer, data, start, end, next); - } else { - append(buffer, data, start, end, done); - } - } - loadNextChunk(); -} - -function updateDoc(revLimit, prev, docInfo, results, - i, cb, writeDoc, newEdits) { - - if (revExists(prev.rev_tree, docInfo.metadata.rev)) { - results[i] = docInfo; - return cb(); - } - - // sometimes this is pre-calculated. historically not always - var previousWinningRev = prev.winningRev || winningRev(prev); - var previouslyDeleted = 'deleted' in prev ? prev.deleted : - isDeleted(prev, previousWinningRev); - var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted : - isDeleted(docInfo.metadata); - var isRoot = /^1-/.test(docInfo.metadata.rev); - - if (previouslyDeleted && !deleted && newEdits && isRoot) { - var newDoc = docInfo.data; - newDoc._rev = previousWinningRev; - newDoc._id = docInfo.metadata.id; - docInfo = parseDoc(newDoc, newEdits); - } - - var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit); - - var inConflict = newEdits && (((previouslyDeleted && deleted) || - (!previouslyDeleted && merged.conflicts !== 'new_leaf') || - (previouslyDeleted && !deleted && merged.conflicts === 'new_branch'))); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[i] = err; - return cb(); - } - - var newRev = docInfo.metadata.rev; - docInfo.metadata.rev_tree = merged.tree; - docInfo.stemmedRevs = merged.stemmedRevs || []; - /* istanbul ignore else */ - if (prev.rev_map) { - docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb - } - - // recalculate - var winningRev$$ = winningRev(docInfo.metadata); - var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$); - - // calculate the total number of documents that were added/removed, - // from the perspective of total_rows/doc_count - var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 : - previouslyDeleted < winningRevIsDeleted ? -1 : 1; - - var newRevIsDeleted; - if (newRev === winningRev$$) { - // if the new rev is the same as the winning rev, we can reuse that value - newRevIsDeleted = winningRevIsDeleted; - } else { - // if they're not the same, then we need to recalculate - newRevIsDeleted = isDeleted(docInfo.metadata, newRev); - } - - writeDoc(docInfo, winningRev$$, winningRevIsDeleted, newRevIsDeleted, - true, delta, i, cb); -} - -function rootIsMissing(docInfo) { - return docInfo.metadata.rev_tree[0].ids[1].status === 'missing'; -} - -function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results, - writeDoc, opts, overallCallback) { - - // Default to 1000 locally - revLimit = revLimit || 1000; - - function insertDoc(docInfo, resultsIdx, callback) { - // Cant insert new deleted documents - var winningRev$$ = winningRev(docInfo.metadata); - var deleted = isDeleted(docInfo.metadata, winningRev$$); - if ('was_delete' in opts && deleted) { - results[resultsIdx] = createError(MISSING_DOC, 'deleted'); - return callback(); - } - - // 4712 - detect whether a new document was inserted with a _rev - var inConflict = newEdits && rootIsMissing(docInfo); - - if (inConflict) { - var err = createError(REV_CONFLICT); - results[resultsIdx] = err; - return callback(); - } - - var delta = deleted ? 0 : 1; - - writeDoc(docInfo, winningRev$$, deleted, deleted, false, - delta, resultsIdx, callback); - } - - var newEdits = opts.new_edits; - var idsToDocs = new _Map(); - - var docsDone = 0; - var docsToDo = docInfos.length; - - function checkAllDocsDone() { - if (++docsDone === docsToDo && overallCallback) { - overallCallback(); - } - } - - docInfos.forEach(function (currentDoc, resultsIdx) { - - if (currentDoc._id && isLocalId(currentDoc._id)) { - var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal'; - api[fun](currentDoc, {ctx: tx}, function (err, res) { - results[resultsIdx] = err || res; - checkAllDocsDone(); - }); - return; - } - - var id = currentDoc.metadata.id; - if (idsToDocs.has(id)) { - docsToDo--; // duplicate - idsToDocs.get(id).push([currentDoc, resultsIdx]); - } else { - idsToDocs.set(id, [[currentDoc, resultsIdx]]); - } - }); - - // in the case of new_edits, the user can provide multiple docs - // with the same id. these need to be processed sequentially - idsToDocs.forEach(function (docs, id) { - var numDone = 0; - - function docWritten() { - if (++numDone < docs.length) { - nextDoc(); - } else { - checkAllDocsDone(); - } - } - function nextDoc() { - var value = docs[numDone]; - var currentDoc = value[0]; - var resultsIdx = value[1]; - - if (fetchedDocs.has(id)) { - updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results, - resultsIdx, docWritten, writeDoc, newEdits); - } else { - // Ensure stemming applies to new writes as well - var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit); - currentDoc.metadata.rev_tree = merged.tree; - currentDoc.stemmedRevs = merged.stemmedRevs || []; - insertDoc(currentDoc, resultsIdx, docWritten); - } - } - nextDoc(); - }); -} - -function slowJsonParse(str) { - try { - return JSON.parse(str); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.parse(str); - } -} - -function safeJsonParse(str) { - // try/catch is deoptimized in V8, leading to slower - // times than we'd like to have. Most documents are _not_ - // huge, and do not require a slower code path just to parse them. - // We can be pretty sure that a document under 50000 characters - // will not be so deeply nested as to throw a stack overflow error - // (depends on the engine and available memory, though, so this is - // just a hunch). 50000 was chosen based on the average length - // of this string in our test suite, to try to find a number that covers - // most of our test cases (26 over this size, 26378 under it). - if (str.length < 50000) { - return JSON.parse(str); - } - return slowJsonParse(str); -} - -function safeJsonStringify(json) { - try { - return JSON.stringify(json); - } catch (e) { - /* istanbul ignore next */ - return vuvuzela.stringify(json); - } -} - -function readAsBlobOrBuffer(storedObject, type) { - // In the browser, we've stored a binary string. This now comes back as a - // browserified Node-style Buffer (implemented as a typed array), - // but we want a Blob instead. - var byteArray = new Uint8Array(storedObject); - return createBlob([byteArray], {type: type}); -} - -// In the browser, we store a binary string -function prepareAttachmentForStorage(attData, cb) { - readAsBinaryString(attData, cb); -} - -function createEmptyBlobOrBuffer(type) { - return createBlob([''], {type: type}); -} - -// similar to an idb or websql transaction object -// designed to be passed around. basically just caches -// things in-memory and then does a big batch() operation -// when you're done - -function getCacheFor(transaction, store) { - var prefix = store.prefix()[0]; - var cache = transaction._cache; - var subCache = cache.get(prefix); - if (!subCache) { - subCache = new _Map(); - cache.set(prefix, subCache); - } - return subCache; -} - -function LevelTransaction() { - this._batch = []; - this._cache = new _Map(); -} - -LevelTransaction.prototype.get = function (store, key, callback) { - var cache = getCacheFor(this, store); - var exists = cache.get(key); - if (exists) { - return process.nextTick(function () { - callback(null, exists); - }); - } else if (exists === null) { // deleted marker - /* istanbul ignore next */ - return process.nextTick(function () { - callback({name: 'NotFoundError'}); - }); - } - store.get(key, function (err, res) { - if (err) { - /* istanbul ignore else */ - if (err.name === 'NotFoundError') { - cache.set(key, null); - } - return callback(err); - } - cache.set(key, res); - callback(null, res); - }); -}; - -LevelTransaction.prototype.batch = function (batch) { - for (var i = 0, len = batch.length; i < len; i++) { - var operation = batch[i]; - - var cache = getCacheFor(this, operation.prefix); - - if (operation.type === 'put') { - cache.set(operation.key, operation.value); - } else { - cache.set(operation.key, null); - } - } - this._batch = this._batch.concat(batch); -}; - -LevelTransaction.prototype.execute = function (db, callback) { - - var keys = new _Set(); - var uniqBatches = []; - - // remove duplicates; last one wins - for (var i = this._batch.length - 1; i >= 0; i--) { - var operation = this._batch[i]; - var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key; - if (keys.has(lookupKey)) { - continue; - } - keys.add(lookupKey); - uniqBatches.push(operation); - } - - db.batch(uniqBatches, callback); -}; - -var DOC_STORE = 'document-store'; -var BY_SEQ_STORE = 'by-sequence'; -var ATTACHMENT_STORE = 'attach-store'; -var BINARY_STORE = 'attach-binary-store'; -var LOCAL_STORE = 'local-store'; -var META_STORE = 'meta-store'; - -// leveldb barks if we try to open a db multiple times -// so we cache opened connections here for initstore() -var dbStores = new _Map(); - -// store the value of update_seq in the by-sequence store the key name will -// never conflict, since the keys in the by-sequence store are integers -var UPDATE_SEQ_KEY = '_local_last_update_seq'; -var DOC_COUNT_KEY = '_local_doc_count'; -var UUID_KEY = '_local_uuid'; - -var MD5_PREFIX = 'md5-'; - -var safeJsonEncoding = { - encode: safeJsonStringify, - decode: safeJsonParse, - buffer: false, - type: 'cheap-json' -}; - -var levelChanges = new Changes(); - -// winningRev and deleted are performance-killers, but -// in newer versions of PouchDB, they are cached on the metadata -function getWinningRev(metadata) { - return 'winningRev' in metadata ? - metadata.winningRev : winningRev(metadata); -} - -function getIsDeleted(metadata, winningRev) { - return 'deleted' in metadata ? - metadata.deleted : isDeleted(metadata, winningRev); -} - -function fetchAttachment(att, stores, opts) { - var type = att.content_type; - return new PouchPromise(function (resolve, reject) { - stores.binaryStore.get(att.digest, function (err, buffer) { - var data; - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return reject(err); - } else { - // empty - if (!opts.binary) { - data = ''; - } else { - data = binStringToBluffer('', type); - } - } - } else { // non-empty - if (opts.binary) { - data = readAsBlobOrBuffer(buffer, type); - } else { - data = buffer.toString('base64'); - } - } - delete att.stub; - delete att.length; - att.data = data; - resolve(); - }); - }); -} - -function fetchAttachments(results, stores, opts) { - var atts = []; - results.forEach(function (row) { - if (!(row.doc && row.doc._attachments)) { - return; - } - var attNames = Object.keys(row.doc._attachments); - attNames.forEach(function (attName) { - var att = row.doc._attachments[attName]; - if (!('data' in att)) { - atts.push(att); - } - }); - }); - - return PouchPromise.all(atts.map(function (att) { - return fetchAttachment(att, stores, opts); - })); -} - -function LevelPouch(opts, callback) { - opts = clone$1(opts); - var api = this; - var instanceId; - var stores = {}; - var revLimit = opts.revs_limit; - var db; - var name = opts.name; - // TODO: this is undocumented and unused probably - /* istanbul ignore else */ - if (typeof opts.createIfMissing === 'undefined') { - opts.createIfMissing = true; - } - - var leveldown = opts.db; - - var dbStore; - var leveldownName = functionName(leveldown); - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - dbStore = new _Map(); - dbStores.set(leveldownName, dbStore); - } - if (dbStore.has(name)) { - db = dbStore.get(name); - afterDBCreated(); - } else { - dbStore.set(name, sublevelPouch(levelup(name, opts, function (err) { - /* istanbul ignore if */ - if (err) { - dbStore.delete(name); - return callback(err); - } - db = dbStore.get(name); - db._docCount = -1; - db._queue = new Deque(); - /* istanbul ignore else */ - if (opts.migrate) { // migration for leveldown - migrate.toSublevel(name, db, afterDBCreated); - } else { - afterDBCreated(); - } - }))); - } - - function afterDBCreated() { - stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding}); - stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'}); - stores.attachmentStore = - db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'}); - stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'}); - stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'}); - stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'}); - migrate.localAndMetaStores(db, stores, function () { - stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) { - if (typeof db._updateSeq === 'undefined') { - db._updateSeq = value || 0; - } - stores.metaStore.get(DOC_COUNT_KEY, function (err, value) { - db._docCount = !err ? value : 0; - stores.metaStore.get(UUID_KEY, function (err, value) { - instanceId = !err ? value : uuid(); - stores.metaStore.put(UUID_KEY, instanceId, function () { - process.nextTick(function () { - callback(null, api); - }); - }); - }); - }); - }); - }); - } - - function countDocs(callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(new Error('database is closed')); - } - return callback(null, db._docCount); // use cached value - } - - api.type = function () { - return 'leveldb'; - }; - - api._id = function (callback) { - callback(null, instanceId); - }; - - api._info = function (callback) { - var res = { - doc_count: db._docCount, - update_seq: db._updateSeq, - backend_adapter: functionName(leveldown) - }; - return process.nextTick(function () { - callback(null, res); - }); - }; - - function tryCode(fun, args) { - try { - fun.apply(null, args); - } catch (err) { - args[args.length - 1](err); - } - } - - function executeNext() { - var firstTask = db._queue.peekFront(); - - if (firstTask.type === 'read') { - runReadOperation(firstTask); - } else { // write, only do one at a time - runWriteOperation(firstTask); - } - } - - function runReadOperation(firstTask) { - // do multiple reads at once simultaneously, because it's safe - - var readTasks = [firstTask]; - var i = 1; - var nextTask = db._queue.get(i); - while (typeof nextTask !== 'undefined' && nextTask.type === 'read') { - readTasks.push(nextTask); - i++; - nextTask = db._queue.get(i); - } - - var numDone = 0; - - readTasks.forEach(function (readTask) { - var args = readTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - if (++numDone === readTasks.length) { - process.nextTick(function () { - // all read tasks have finished - readTasks.forEach(function () { - db._queue.shift(); - }); - if (db._queue.length) { - executeNext(); - } - }); - } - }); - tryCode(readTask.fun, args); - }); - } - - function runWriteOperation(firstTask) { - var args = firstTask.args; - var callback = args[args.length - 1]; - args[args.length - 1] = getArguments(function (cbArgs) { - callback.apply(null, cbArgs); - process.nextTick(function () { - db._queue.shift(); - if (db._queue.length) { - executeNext(); - } - }); - }); - tryCode(firstTask.fun, args); - } - - // all read/write operations to the database are done in a queue, - // similar to how websql/idb works. this avoids problems such - // as e.g. compaction needing to have a lock on the database while - // it updates stuff. in the future we can revisit this. - function writeLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'write' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - // same as the writelock, but multiple can run at once - function readLock(fun) { - return getArguments(function (args) { - db._queue.push({ - fun: fun, - args: args, - type: 'read' - }); - - if (db._queue.length === 1) { - process.nextTick(executeNext); - } - }); - } - - function formatSeq(n) { - return ('0000000000000000' + n).slice(-16); - } - - function parseSeq(s) { - return parseInt(s, 10); - } - - api._get = readLock(function (id, opts, callback) { - opts = clone$1(opts); - - stores.docStore.get(id, function (err, metadata) { - - if (err || !metadata) { - return callback(createError(MISSING_DOC, 'missing')); - } - - var rev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, rev); - if (deleted && !opts.rev) { - return callback(createError(MISSING_DOC, "deleted")); - } - - rev = opts.rev ? opts.rev : rev; - - var seq = metadata.rev_map[rev]; - - stores.bySeqStore.get(formatSeq(seq), function (err, doc) { - if (!doc) { - return callback(createError(MISSING_DOC)); - } - /* istanbul ignore if */ - if ('_id' in doc && doc._id !== metadata.id) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - doc._id = metadata.id; - if ('_rev' in doc) { - /* istanbul ignore if */ - if (doc._rev !== rev) { - // this failing implies something very wrong - return callback(new Error('wrong doc returned')); - } - } else { - // we didn't always store this - doc._rev = rev; - } - return callback(null, {doc: doc, metadata: metadata}); - }); - }); - }); - - // not technically part of the spec, but if putAttachment has its own - // method... - api._getAttachment = function (docId, attachId, attachment, opts, callback) { - var digest = attachment.digest; - var type = attachment.content_type; - - stores.binaryStore.get(digest, function (err, attach) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } - // Empty attachment - return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : ''); - } - - if (opts.binary) { - callback(null, readAsBlobOrBuffer(attach, type)); - } else { - callback(null, attach.toString('base64')); - } - }); - }; - - api._bulkDocs = writeLock(function (req, opts, callback) { - var newEdits = opts.new_edits; - var results = new Array(req.docs.length); - var fetchedDocs = new _Map(); - var stemmedRevs = new _Map(); - - var txn = new LevelTransaction(); - var docCountDelta = 0; - var newUpdateSeq = db._updateSeq; - - // parse the docs and give each a sequence number - var userDocs = req.docs; - var docInfos = userDocs.map(function (doc) { - if (doc._id && isLocalId(doc._id)) { - return doc; - } - var newDoc = parseDoc(doc, newEdits); - - if (newDoc.metadata && !newDoc.metadata.rev_map) { - newDoc.metadata.rev_map = {}; - } - - return newDoc; - }); - var infoErrors = docInfos.filter(function (doc) { - return doc.error; - }); - - if (infoErrors.length) { - return callback(infoErrors[0]); - } - - // verify any stub attachments as a precondition test - - function verifyAttachment(digest, callback) { - txn.get(stores.attachmentStore, digest, function (levelErr) { - if (levelErr) { - var err = createError(MISSING_STUB, - 'unknown stub attachment with digest ' + - digest); - callback(err); - } else { - callback(); - } - }); - } - - function verifyAttachments(finish) { - var digests = []; - userDocs.forEach(function (doc) { - if (doc && doc._attachments) { - Object.keys(doc._attachments).forEach(function (filename) { - var att = doc._attachments[filename]; - if (att.stub) { - digests.push(att.digest); - } - }); - } - }); - if (!digests.length) { - return finish(); - } - var numDone = 0; - var err; - - digests.forEach(function (digest) { - verifyAttachment(digest, function (attErr) { - if (attErr && !err) { - err = attErr; - } - - if (++numDone === digests.length) { - finish(err); - } - }); - }); - } - - function fetchExistingDocs(finish) { - var numDone = 0; - var overallErr; - function checkDone() { - if (++numDone === userDocs.length) { - return finish(overallErr); - } - } - - userDocs.forEach(function (doc) { - if (doc._id && isLocalId(doc._id)) { - // skip local docs - return checkDone(); - } - txn.get(stores.docStore, doc._id, function (err, info) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - overallErr = err; - } - } else { - fetchedDocs.set(doc._id, info); - } - checkDone(); - }); - }); - } - - function compact(revsMap, callback) { - var promise = PouchPromise.resolve(); - revsMap.forEach(function (revs, docId) { - // TODO: parallelize, for now need to be sequential to - // pass orphaned attachment tests - promise = promise.then(function () { - return new PouchPromise(function (resolve, reject) { - api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) { - /* istanbul ignore if */ - if (err) { - return reject(err); - } - resolve(); - }); - }); - }); - }); - - promise.then(function () { - callback(); - }, callback); - } - - function autoCompact(callback) { - var revsMap = new _Map(); - fetchedDocs.forEach(function (metadata, docId) { - revsMap.set(docId, compactTree(metadata)); - }); - compact(revsMap, callback); - } - - function finish() { - compact(stemmedRevs, function (error) { - /* istanbul ignore if */ - if (error) { - complete(error); - } - if (api.auto_compaction) { - return autoCompact(complete); - } - complete(); - }); - } - - function writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted, - isUpdate, delta, resultsIdx, callback2) { - docCountDelta += delta; - - var err = null; - var recv = 0; - - docInfo.metadata.winningRev = winningRev; - docInfo.metadata.deleted = winningRevIsDeleted; - - docInfo.data._id = docInfo.metadata.id; - docInfo.data._rev = docInfo.metadata.rev; - - if (newRevIsDeleted) { - docInfo.data._deleted = true; - } - - if (docInfo.stemmedRevs.length) { - stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs); - } - - var attachments = docInfo.data._attachments ? - Object.keys(docInfo.data._attachments) : - []; - - function attachmentSaved(attachmentErr) { - recv++; - if (!err) { - /* istanbul ignore if */ - if (attachmentErr) { - err = attachmentErr; - callback2(err); - } else if (recv === attachments.length) { - finish(); - } - } - } - - function onMD5Load(doc, key, data, attachmentSaved) { - return function (result) { - saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved); - }; - } - - function doMD5(doc, key, attachmentSaved) { - return function (data) { - binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved)); - }; - } - - for (var i = 0; i < attachments.length; i++) { - var key = attachments[i]; - var att = docInfo.data._attachments[key]; - - if (att.stub) { - // still need to update the refs mapping - var id = docInfo.data._id; - var rev = docInfo.data._rev; - saveAttachmentRefs(id, rev, att.digest, attachmentSaved); - continue; - } - var data; - if (typeof att.data === 'string') { - // input is assumed to be a base64 string - try { - data = atob$1(att.data); - } catch (e) { - callback(createError(BAD_ARG, - 'Attachment is not a valid base64 string')); - return; - } - doMD5(docInfo, key, attachmentSaved)(data); - } else { - prepareAttachmentForStorage(att.data, - doMD5(docInfo, key, attachmentSaved)); - } - } - - function finish() { - var seq = docInfo.metadata.rev_map[docInfo.metadata.rev]; - /* istanbul ignore if */ - if (seq) { - // check that there aren't any existing revisions with the same - // revision id, else we shouldn't do anything - return callback2(); - } - seq = ++newUpdateSeq; - docInfo.metadata.rev_map[docInfo.metadata.rev] = - docInfo.metadata.seq = seq; - var seqKey = formatSeq(seq); - var batch = [{ - key: seqKey, - value: docInfo.data, - prefix: stores.bySeqStore, - type: 'put' - }, { - key: docInfo.metadata.id, - value: docInfo.metadata, - prefix: stores.docStore, - type: 'put' - }]; - txn.batch(batch); - results[resultsIdx] = { - ok: true, - id: docInfo.metadata.id, - rev: winningRev - }; - fetchedDocs.set(docInfo.metadata.id, docInfo.metadata); - callback2(); - } - - if (!attachments.length) { - finish(); - } - } - - // attachments are queued per-digest, otherwise the refs could be - // overwritten by concurrent writes in the same bulkDocs session - var attachmentQueues = {}; - - function saveAttachmentRefs(id, rev, digest, callback) { - - function fetchAtt() { - return new PouchPromise(function (resolve, reject) { - txn.get(stores.attachmentStore, digest, function (err, oldAtt) { - /* istanbul ignore if */ - if (err && err.name !== 'NotFoundError') { - return reject(err); - } - resolve(oldAtt); - }); - }); - } - - function saveAtt(oldAtt) { - var ref = [id, rev].join('@'); - var newAtt = {}; - - if (oldAtt) { - if (oldAtt.refs) { - // only update references if this attachment already has them - // since we cannot migrate old style attachments here without - // doing a full db scan for references - newAtt.refs = oldAtt.refs; - newAtt.refs[ref] = true; - } - } else { - newAtt.refs = {}; - newAtt.refs[ref] = true; - } - - return new PouchPromise(function (resolve) { - txn.batch([{ - type: 'put', - prefix: stores.attachmentStore, - key: digest, - value: newAtt - }]); - resolve(!oldAtt); - }); - } - - // put attachments in a per-digest queue, to avoid two docs with the same - // attachment overwriting each other - var queue = attachmentQueues[digest] || PouchPromise.resolve(); - attachmentQueues[digest] = queue.then(function () { - return fetchAtt().then(saveAtt).then(function (isNewAttachment) { - callback(null, isNewAttachment); - }, callback); - }); - } - - function saveAttachment(docInfo, digest, key, data, callback) { - var att = docInfo.data._attachments[key]; - delete att.data; - att.digest = digest; - att.length = data.length; - var id = docInfo.metadata.id; - var rev = docInfo.metadata.rev; - att.revpos = parseInt(rev, 10); - - saveAttachmentRefs(id, rev, digest, function (err, isNewAttachment) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - // do not try to store empty attachments - if (data.length === 0) { - return callback(err); - } - if (!isNewAttachment) { - // small optimization - don't bother writing it again - return callback(err); - } - txn.batch([{ - type: 'put', - prefix: stores.binaryStore, - key: digest, - value: new Buffer(data, 'binary') - }]); - callback(); - }); - } - - function complete(err) { - /* istanbul ignore if */ - if (err) { - return process.nextTick(function () { - callback(err); - }); - } - txn.batch([ - { - prefix: stores.metaStore, - type: 'put', - key: UPDATE_SEQ_KEY, - value: newUpdateSeq - }, - { - prefix: stores.metaStore, - type: 'put', - key: DOC_COUNT_KEY, - value: db._docCount + docCountDelta - } - ]); - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - db._docCount += docCountDelta; - db._updateSeq = newUpdateSeq; - levelChanges.notify(name); - process.nextTick(function () { - callback(null, results); - }); - }); - } - - if (!docInfos.length) { - return callback(null, []); - } - - verifyAttachments(function (err) { - if (err) { - return callback(err); - } - fetchExistingDocs(function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - processDocs(revLimit, docInfos, api, fetchedDocs, txn, results, - writeDoc, opts, finish); - }); - }); - }); - api._allDocs = readLock(function (opts, callback) { - opts = clone$1(opts); - countDocs(function (err, docCount) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var readstreamOpts = {}; - var skip = opts.skip || 0; - if (opts.startkey) { - readstreamOpts.gte = opts.startkey; - } - if (opts.endkey) { - readstreamOpts.lte = opts.endkey; - } - if (opts.key) { - readstreamOpts.gte = readstreamOpts.lte = opts.key; - } - if (opts.descending) { - readstreamOpts.reverse = true; - // switch start and ends - var tmp = readstreamOpts.lte; - readstreamOpts.lte = readstreamOpts.gte; - readstreamOpts.gte = tmp; - } - var limit; - if (typeof opts.limit === 'number') { - limit = opts.limit; - } - if (limit === 0 || - ('start' in readstreamOpts && 'end' in readstreamOpts && - readstreamOpts.start > readstreamOpts.end)) { - // should return 0 results when start is greater than end. - // normally level would "fix" this for us by reversing the order, - // so short-circuit instead - return callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: [] - }); - } - var results = []; - var docstream = stores.docStore.readStream(readstreamOpts); - - var throughStream = through2.obj(function (entry, _, next) { - var metadata = entry.value; - // winningRev and deleted are performance-killers, but - // in newer versions of PouchDB, they are cached on the metadata - var winningRev = getWinningRev(metadata); - var deleted = getIsDeleted(metadata, winningRev); - if (!deleted) { - if (skip-- > 0) { - next(); - return; - } else if (typeof limit === 'number' && limit-- <= 0) { - docstream.unpipe(); - docstream.destroy(); - next(); - return; - } - } else if (opts.deleted !== 'ok') { - next(); - return; - } - function allDocsInner(data) { - var doc = { - id: metadata.id, - key: metadata.id, - value: { - rev: winningRev - } - }; - if (opts.include_docs) { - doc.doc = data; - doc.doc._rev = doc.value.rev; - if (opts.conflicts) { - doc.doc._conflicts = collectConflicts(metadata); - } - for (var att in doc.doc._attachments) { - if (doc.doc._attachments.hasOwnProperty(att)) { - doc.doc._attachments[att].stub = true; - } - } - } - if (opts.inclusive_end === false && metadata.id === opts.endkey) { - return next(); - } else if (deleted) { - if (opts.deleted === 'ok') { - doc.value.deleted = true; - doc.doc = null; - } else { - /* istanbul ignore next */ - return next(); - } - } - results.push(doc); - next(); - } - if (opts.include_docs) { - var seq = metadata.rev_map[winningRev]; - stores.bySeqStore.get(formatSeq(seq), function (err, data) { - allDocsInner(data); - }); - } - else { - allDocsInner(); - } - }, function (next) { - PouchPromise.resolve().then(function () { - if (opts.include_docs && opts.attachments) { - return fetchAttachments(results, stores, opts); - } - }).then(function () { - callback(null, { - total_rows: docCount, - offset: opts.skip, - rows: results - }); - }, callback); - next(); - }).on('unpipe', function () { - throughStream.end(); - }); - - docstream.on('error', callback); - - docstream.pipe(throughStream); - }); - }); - - api._changes = function (opts) { - opts = clone$1(opts); - - if (opts.continuous) { - var id = name + ':' + uuid(); - levelChanges.addListener(name, id, api, opts); - levelChanges.notify(name); - return { - cancel: function () { - levelChanges.removeListener(name, id); - } - }; - } - - var descending = opts.descending; - var results = []; - var lastSeq = opts.since || 0; - var called = 0; - var streamOpts = { - reverse: descending - }; - var limit; - if ('limit' in opts && opts.limit > 0) { - limit = opts.limit; - } - if (!streamOpts.reverse) { - streamOpts.start = formatSeq(opts.since || 0); - } - - var docIds = opts.doc_ids && new _Set(opts.doc_ids); - var filter = filterChange(opts); - var docIdsToMetadata = new _Map(); - - var returnDocs; - if ('return_docs' in opts) { - returnDocs = opts.return_docs; - } else if ('returnDocs' in opts) { - // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release - returnDocs = opts.returnDocs; - } else { - returnDocs = true; - } - - function complete() { - opts.done = true; - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - changeStream.unpipe(throughStream); - changeStream.destroy(); - if (!opts.continuous && !opts.cancelled) { - if (opts.include_docs && opts.attachments) { - fetchAttachments(results, stores, opts).then(function () { - opts.complete(null, {results: results, last_seq: lastSeq}); - }); - } else { - opts.complete(null, {results: results, last_seq: lastSeq}); - } - } - } - var changeStream = stores.bySeqStore.readStream(streamOpts); - var throughStream = through2.obj(function (data, _, next) { - if (limit && called >= limit) { - complete(); - return next(); - } - if (opts.cancelled || opts.done) { - return next(); - } - - var seq = parseSeq(data.key); - var doc = data.value; - - if (seq === opts.since && !descending) { - // couchdb ignores `since` if descending=true - return next(); - } - - if (docIds && !docIds.has(doc._id)) { - return next(); - } - - var metadata; - - function onGetMetadata(metadata) { - var winningRev = getWinningRev(metadata); - - function onGetWinningDoc(winningDoc) { - - var change = opts.processChange(winningDoc, metadata, opts); - change.seq = metadata.seq; - - var filtered = filter(change); - if (typeof filtered === 'object') { - return opts.complete(filtered); - } - - if (filtered) { - called++; - - if (opts.attachments && opts.include_docs) { - // fetch attachment immediately for the benefit - // of live listeners - fetchAttachments([change], stores, opts).then(function () { - opts.onChange(change); - }); - } else { - opts.onChange(change); - } - - if (returnDocs) { - results.push(change); - } - } - next(); - } - - if (metadata.seq !== seq) { - // some other seq is later - return next(); - } - - lastSeq = seq; - - if (winningRev === doc._rev) { - return onGetWinningDoc(doc); - } - - // fetch the winner - - var winningSeq = metadata.rev_map[winningRev]; - - stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) { - onGetWinningDoc(doc); - }); - } - - metadata = docIdsToMetadata.get(doc._id); - if (metadata) { // cached - return onGetMetadata(metadata); - } - // metadata not cached, have to go fetch it - stores.docStore.get(doc._id, function (err, metadata) { - /* istanbul ignore if */ - if (opts.cancelled || opts.done || db.isClosed() || - isLocalId(metadata.id)) { - return next(); - } - docIdsToMetadata.set(doc._id, metadata); - onGetMetadata(metadata); - }); - }, function (next) { - if (opts.cancelled) { - return next(); - } - if (returnDocs && opts.limit) { - /* istanbul ignore if */ - if (opts.limit < results.length) { - results.length = opts.limit; - } - } - - next(); - }).on('unpipe', function () { - throughStream.end(); - complete(); - }); - changeStream.pipe(throughStream); - return { - cancel: function () { - opts.cancelled = true; - complete(); - } - }; - }; - - api._close = function (callback) { - /* istanbul ignore if */ - if (db.isClosed()) { - return callback(createError(NOT_OPEN)); - } - db.close(function (err) { - /* istanbul ignore if */ - if (err) { - callback(err); - } else { - dbStore.delete(name); - callback(); - } - }); - }; - - api._getRevisionTree = function (docId, callback) { - stores.docStore.get(docId, function (err, metadata) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, metadata.rev_tree); - } - }); - }; - - api._doCompaction = writeLock(function (docId, revs, opts, callback) { - api._doCompactionNoLock(docId, revs, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._doCompactionNoLock = function (docId, revs, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - - if (!revs.length) { - return callback(); - } - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.docStore, docId, function (err, metadata) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - var seqs = revs.map(function (rev) { - var seq = metadata.rev_map[rev]; - delete metadata.rev_map[rev]; - return seq; - }); - traverseRevTree(metadata.rev_tree, function (isLeaf, pos, - revHash, ctx, opts) { - var rev = pos + '-' + revHash; - if (revs.indexOf(rev) !== -1) { - opts.status = 'missing'; - } - }); - - var batch = []; - batch.push({ - key: metadata.id, - value: metadata, - type: 'put', - prefix: stores.docStore - }); - - var digestMap = {}; - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === revs.length) { // done - /* istanbul ignore if */ - if (overallErr) { - return callback(overallErr); - } - deleteOrphanedAttachments(); - } - } - - function finish(err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - txn.batch(batch); - if (opts.ctx) { - // don't execute immediately - return callback(); - } - txn.execute(db, callback); - } - - function deleteOrphanedAttachments() { - var possiblyOrphanedAttachments = Object.keys(digestMap); - if (!possiblyOrphanedAttachments.length) { - return finish(); - } - var numDone = 0; - var overallErr; - function checkDone(err) { - /* istanbul ignore if */ - if (err) { - overallErr = err; - } - if (++numDone === possiblyOrphanedAttachments.length) { - finish(overallErr); - } - } - var refsToDelete = new _Map(); - revs.forEach(function (rev) { - refsToDelete.set(docId + '@' + rev, true); - }); - possiblyOrphanedAttachments.forEach(function (digest) { - txn.get(stores.attachmentStore, digest, function (err, attData) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var refs = Object.keys(attData.refs || {}).filter(function (ref) { - return !refsToDelete.has(ref); - }); - var newRefs = {}; - refs.forEach(function (ref) { - newRefs[ref] = true; - }); - if (refs.length) { // not orphaned - batch.push({ - key: digest, - type: 'put', - value: {refs: newRefs}, - prefix: stores.attachmentStore - }); - } else { // orphaned, can safely delete - batch = batch.concat([{ - key: digest, - type: 'del', - prefix: stores.attachmentStore - }, { - key: digest, - type: 'del', - prefix: stores.binaryStore - }]); - } - checkDone(); - }); - }); - } - - seqs.forEach(function (seq) { - batch.push({ - key: formatSeq(seq), - type: 'del', - prefix: stores.bySeqStore - }); - txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) { - /* istanbul ignore if */ - if (err) { - if (err.name === 'NotFoundError') { - return checkDone(); - } else { - return checkDone(err); - } - } - var atts = Object.keys(doc._attachments || {}); - atts.forEach(function (attName) { - var digest = doc._attachments[attName].digest; - digestMap[digest] = true; - }); - checkDone(); - }); - }); - }); - }; - - api._getLocal = function (id, callback) { - stores.localStore.get(id, function (err, doc) { - if (err) { - callback(createError(MISSING_DOC)); - } else { - callback(null, doc); - } - }); - }; - - api._putLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._putLocalNoLock(doc, opts, callback); - } else { - api._putLocalWithLock(doc, opts, callback); - } - }; - - api._putLocalWithLock = writeLock(function (doc, opts, callback) { - api._putLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._putLocalNoLock = function (doc, opts, callback) { - delete doc._revisions; // ignore this, trust the rev - var oldRev = doc._rev; - var id = doc._id; - - var txn = opts.ctx || new LevelTransaction(); - - txn.get(stores.localStore, id, function (err, resp) { - if (err && oldRev) { - return callback(createError(REV_CONFLICT)); - } - if (resp && resp._rev !== oldRev) { - return callback(createError(REV_CONFLICT)); - } - doc._rev = - oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1'; - var batch = [ - { - type: 'put', - prefix: stores.localStore, - key: id, - value: doc - } - ]; - - txn.batch(batch); - var ret = {ok: true, id: doc._id, rev: doc._rev}; - - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - api._removeLocal = function (doc, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - if (opts.ctx) { - api._removeLocalNoLock(doc, opts, callback); - } else { - api._removeLocalWithLock(doc, opts, callback); - } - }; - - api._removeLocalWithLock = writeLock(function (doc, opts, callback) { - api._removeLocalNoLock(doc, opts, callback); - }); - - // the NoLock version is for use by bulkDocs - api._removeLocalNoLock = function (doc, opts, callback) { - var txn = opts.ctx || new LevelTransaction(); - txn.get(stores.localStore, doc._id, function (err, resp) { - if (err) { - /* istanbul ignore if */ - if (err.name !== 'NotFoundError') { - return callback(err); - } else { - return callback(createError(MISSING_DOC)); - } - } - if (resp._rev !== doc._rev) { - return callback(createError(REV_CONFLICT)); - } - txn.batch([{ - prefix: stores.localStore, - type: 'del', - key: doc._id - }]); - var ret = {ok: true, id: doc._id, rev: '0-0'}; - if (opts.ctx) { - // don't execute immediately - return callback(null, ret); - } - txn.execute(db, function (err) { - /* istanbul ignore if */ - if (err) { - return callback(err); - } - callback(null, ret); - }); - }); - }; - - // close and delete open leveldb stores - api._destroy = function (opts, callback) { - var dbStore; - var leveldownName = functionName(leveldown); - /* istanbul ignore else */ - if (dbStores.has(leveldownName)) { - dbStore = dbStores.get(leveldownName); - } else { - return callDestroy(name, callback); - } - - /* istanbul ignore else */ - if (dbStore.has(name)) { - levelChanges.removeAllListeners(name); - - dbStore.get(name).close(function () { - dbStore.delete(name); - callDestroy(name, callback); - }); - } else { - callDestroy(name, callback); - } - }; - function callDestroy(name, cb) { - leveldown.destroy(name, cb); - } -} - -function MemDownPouch(opts, callback) { - var _opts = jsExtend.extend({ - db: memdown - }, opts); - - LevelPouch.call(this, _opts, callback); -} - -// overrides for normal LevelDB behavior on Node -MemDownPouch.valid = function () { - return true; -}; -MemDownPouch.use_prefix = false; - -function MemoryPouchPlugin (PouchDB) { - PouchDB.adapter('memory', MemDownPouch, true); -} - -/* global PouchDB */ - -var PDB = (typeof PouchDB !== 'undefined') ? PouchDB : require('pouchdb'); -if (!PDB) { - guardedConsole('error', 'memory adapter plugin error: ' + - 'Cannot find global "PouchDB" object! ' + - 'Did you remember to include pouchdb.js?'); -} else { - MemoryPouchPlugin(PDB); -} \ No newline at end of file diff --git a/lib/pouchdb/package.json b/lib/pouchdb/package.json index abb8e45b..794463c1 100644 --- a/lib/pouchdb/package.json +++ b/lib/pouchdb/package.json @@ -1,9 +1,9 @@ { "name": "pouchdb", - "version": "6.0.4", + "version": "6.0.6", "description": "PouchDB is a pocket-sized database", "main": "./lib/index.js", - "jsnext:main": "./src/index.js", + "jsnext:main": "./lib/index.es.js", "author": "Dale Harvey ", "license": "Apache-2.0", "repository": "https://github.com/pouchdb/pouchdb", @@ -14,32 +14,9 @@ "dist", "extras" ], - "dependencies": { - "argsarray": "0.0.1", - "debug": "2.2.0", - "double-ended-queue": "2.1.0-0", - "es6-promise-pool": "2.4.4", - "fruitdown": "1.0.2", - "inherits": "2.0.1", - "js-extend": "1.0.1", - "level-codec": "6.2.0", - "level-write-stream": "1.0.0", - "leveldown": "1.4.6", - "levelup": "1.3.2", - "lie": "3.1.0", - "localstorage-down": "0.6.6", - "ltgt": "2.1.2", - "memdown": "1.2.0", - "pull-stream": "3.4.5", - "readable-stream": "1.0.33", - "request": "2.74.0", - "scope-eval": "0.0.3", - "spark-md5": "2.0.2", - "through2": "2.0.1", - "vuvuzela": "1.0.3" - }, "browser": { "./lib/index.js": "./lib/index-browser.js", + "./lib/index.es.js": "./lib/index-browser.es.js", "./src/pouchdb.js": "./src/pouchdb-browser.js" }, "jspm": { @@ -55,5 +32,25 @@ "db", "couchdb", "pouchdb" - ] + ], + "dependencies": { + "argsarray": "0.0.1", + "debug": "2.2.0", + "double-ended-queue": "2.1.0-0", + "es6-promise-pool": "2.4.4", + "inherits": "2.0.3", + "js-extend": "1.0.1", + "level-codec": "6.2.0", + "level-write-stream": "1.0.0", + "leveldown": "1.5.0", + "levelup": "1.3.2", + "lie": "3.1.0", + "ltgt": "2.1.2", + "readable-stream": "1.0.33", + "request": "2.74.0", + "scope-eval": "0.0.3", + "spark-md5": "2.0.2", + "through2": "2.0.1", + "vuvuzela": "1.0.3" + } } diff --git a/lib/pouchdb/src/pouchdb-browser.js b/lib/pouchdb/src/pouchdb-browser.js index a1f10c71..535c0787 100644 --- a/lib/pouchdb/src/pouchdb-browser.js +++ b/lib/pouchdb/src/pouchdb-browser.js @@ -1 +1,5 @@ -export * from 'pouchdb-browser'; +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. +import PouchDB from 'pouchdb-browser/src/index'; +export default PouchDB; \ No newline at end of file diff --git a/lib/pouchdb/src/pouchdb.js b/lib/pouchdb/src/pouchdb.js index 043fd1f3..b45409cd 100644 --- a/lib/pouchdb/src/pouchdb.js +++ b/lib/pouchdb/src/pouchdb.js @@ -1 +1,5 @@ -export * from 'pouchdb-node'; \ No newline at end of file +// Pull from src because pouchdb-node/pouchdb-browser themselves +// are aggressively optimized and jsnext:main would normally give us this +// aggressive bundle. +import PouchDB from 'pouchdb-node/src/index'; +export default PouchDB; \ No newline at end of file diff --git a/lib/prism-element/.bower.json b/lib/prism-element/.bower.json index b5088350..54ed55ee 100644 --- a/lib/prism-element/.bower.json +++ b/lib/prism-element/.bower.json @@ -39,6 +39,6 @@ "commit": "5f742212fac3b391f964fb9dd35cf351301bec9b" }, "_source": "git://github.com/PolymerElements/prism-element.git", - "_target": "^1.0.0", + "_target": "^1.1.0", "_originalSource": "PolymerElements/prism-element" } \ No newline at end of file diff --git a/lib/sw-toolbox/.bower.json b/lib/sw-toolbox/.bower.json index 397674ad..d5ad5423 100644 --- a/lib/sw-toolbox/.bower.json +++ b/lib/sw-toolbox/.bower.json @@ -12,12 +12,12 @@ "gulpfile.js" ], "homepage": "https://github.com/GoogleChrome/sw-toolbox", - "version": "3.2.1", - "_release": "3.2.1", + "version": "3.3.0", + "_release": "3.3.0", "_resolution": { "type": "version", - "tag": "v3.2.1", - "commit": "2a979f3b20a15264e162636bf998e9c45b8f9e39" + "tag": "v3.3.0", + "commit": "f2bd806f1f3c857b17ce84aba2d6aa636793b292" }, "_source": "https://github.com/GoogleChrome/sw-toolbox.git", "_target": "^3.1.1", diff --git a/lib/sw-toolbox/companion.js b/lib/sw-toolbox/companion.js new file mode 100644 index 00000000..a332ecc3 --- /dev/null +++ b/lib/sw-toolbox/companion.js @@ -0,0 +1,23 @@ +/* + Copyright 2016 Google Inc. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +(function() { + 'use strict'; + var workerScript = document.currentScript && document.currentScript.dataset.serviceWorker; + + if (workerScript && 'serviceWorker' in navigator) { + navigator.serviceWorker.register(workerScript); + } +})(); diff --git a/lib/sw-toolbox/docs/_data/releases.yml b/lib/sw-toolbox/docs/_data/releases.yml new file mode 100644 index 00000000..5310c862 --- /dev/null +++ b/lib/sw-toolbox/docs/_data/releases.yml @@ -0,0 +1 @@ +# Auto-generated from the npm-publish-scripts module diff --git a/lib/sw-toolbox/docs/api.md b/lib/sw-toolbox/docs/api.md new file mode 100644 index 00000000..9e9e3e65 --- /dev/null +++ b/lib/sw-toolbox/docs/api.md @@ -0,0 +1,103 @@ +--- +layout: index +title: "API" +navigation_weight: 1 +--- + +## Options + +All options can be specified globally via properties of `toolbox.options`. +Any individual options can be configured on a per-handler basis, via the `Object` passed as the +third parameter to `toolbox.router` methods. + +### debug [Boolean] +Determines whether extra information is logged to the browser's console. + +_Default_: `false` + +### networkTimeoutSeconds [Number] +A timeout that applies to the `toolbox.networkFirst` built-in handler. +If `networkTimeoutSeconds` is set, then any network requests that take longer than that amount of time +will automatically fall back to the cached response if one exists. When +`networkTimeoutSeconds` is not set, the browser's native networking timeout logic applies. + +_Default_: `null` + +### cache [Object] +Various properties of `cache` control the behavior of the default cache when set via +`toolbox.options.cache`, or the cache used by a specific request handler. + +### cache.name [String] +The name of the [`Cache`](https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache) +used to store [`Response`](https://fetch.spec.whatwg.org/#response-class) objects. Using a unique name +allows you to customize the cache's maximum size and age of entries. + +_Default_: Generated at runtime based on the service worker's `registration.scope` value. + +### cache.maxEntries [Number] +Imposes a least-recently used cache expiration policy +on entries cached via the various built-in handlers. You can use this with a cache that's dedicated +to storing entries for a dynamic set of resources with no natural limit. Setting `cache.maxEntries` to, e.g., +`10` would mean that after the 11th entry is cached, the least-recently used entry would be +automatically deleted. The cache should never end up growing beyond `cache.maxEntries` entries. +This option will only take effect if `cache.name` is also set. +It can be used alone or in conjunction with `cache.maxAgeSeconds`. + +_Default_: `null` + +### cache.maxAgeSeconds [Number] +Imposes a maximum age for cache entries, in seconds. +You can use this with a cache that's dedicated to storing entries for a dynamic set of resources +with no natural limit. Setting `cache.maxAgeSeconds` to, e.g., `60 * 60 * 24` would mean that any +entries older than a day would automatically be deleted. +This option will only take effect if `cache.name` is also set. +It can be used alone or in conjunction with `cache.maxEntries`. + +_Default_: `null` + +## Handlers + +There are five built-in handlers to cover the most common network strategies. For more information about offline strategies see the [Offline Cookbook](http://jakearchibald.com/2014/offline-cookbook/). + +### `toolbox.networkFirst` +Try to handle the request by fetching from the network. If it succeeds, store the response in the cache. Otherwise, try to fulfill the request from the cache. This is the strategy to use for basic read-through caching. It's also good for API requests where you always want the freshest data when it is available but would rather have stale data than no data. + +### `toolbox.cacheFirst` +If the request matches a cache entry, respond with that. Otherwise try to fetch the resource from the network. If the network request succeeds, update the cache. This option is good for resources that don't change, or have some other update mechanism. + +### `toolbox.fastest` +Request the resource from both the cache and the network in parallel. Respond with whichever returns first. Usually this will be the cached version, if there is one. On the one hand this strategy will always make a network request, even if the resource is cached. On the other hand, if/when the network request completes the cache is updated, so that future cache reads will be more up-to-date. + +### `toolbox.cacheOnly` +Resolve the request from the cache, or fail. This option is good for when you need to guarantee that no network request will be made, for example saving battery on mobile. + +### `toolbox.networkOnly` +Handle the request by trying to fetch the URL from the network. If the fetch fails, fail the request. Essentially the same as not creating a route for the URL at all. + +

Methods

+ +### `toolbox.router.get(urlPattern, handler, options)` +### `toolbox.router.post(urlPattern, handler, options)` +### `toolbox.router.put(urlPattern, handler, options)` +### `toolbox.router.delete(urlPattern, handler, options)` +### `toolbox.router.head(urlPattern, handler, options)` +Create a route that causes requests for URLs matching `urlPattern` to be resolved by calling `handler`. Matches requests using the GET, POST, PUT, DELETE or HEAD HTTP methods respectively. + +- `urlPattern` - an Express style route. See the docs for the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module for the full syntax +- `handler` - a request handler, as [described above](#using-request-handlers) +- `options` - an object containing options for the route. This options object will be passed to the request handler. The `origin` option is specific to the router methods, and can be either an exact string or a Regexp against which the origin of the Request must match for the route to be used. + +### `toolbox.router.any(urlPattern, handler, options)` +Like `toolbox.router.get`, etc., but matches any HTTP method. + +### `toolbox.router.default` +Takes a function to use as the request handler for any GET request that does not match a route. + +### `toolbox.precache(arrayOfURLs)` +Add each URL in arrayOfURLs to the list of resources that should be cached during the service worker install step. Note that this needs to be called before the install event is triggered, so you should do it on the first run of your script. + +### `toolbox.cache(url, options)` +Causes the resource at `url` to be added to the cache and returns a Promise that resolves with void. The `options` parameter supports the `debug` and `cache` [global options](#global-options). + +### `toolbox.uncache(url, options)` +Causes the resource at `url` to be removed from the cache and returns a Promise that resolves to true if the cache entry is deleted. The `options` parameter supports the `debug` and `cache` [global options](#global-options). diff --git a/lib/sw-toolbox/docs/cache-expiration-options/app.js b/lib/sw-toolbox/docs/cache-expiration-options/app.js deleted file mode 100644 index 28acc85d..00000000 --- a/lib/sw-toolbox/docs/cache-expiration-options/app.js +++ /dev/null @@ -1,55 +0,0 @@ -/* eslint-env browser */ -'use strict'; - -// Please register for your own YouTube API key! -// https://developers.google.com/youtube/v3/getting-started#before-you-start -const API_KEY = 'AIzaSyC4trKMxwT42TUFHmikCc4xxQTWWxq5S0g'; -const API_URL = 'https://www.googleapis.com/youtube/v3/search'; - -function serializeUrlParams(params) { - return Object.keys(params).map(key => { - return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); - }).join('&'); -} - -function youtubeSearch(searchTerm, maxResults) { - let params = { - part: 'snippet', - maxResults: maxResults, - order: 'date', - key: API_KEY, - q: searchTerm - }; - - let url = new URL(API_URL); - url.search = serializeUrlParams(params); - - return fetch(url).then(response => { - if (response.ok) { - return response.json(); - } - throw new Error(`${response.status}: ${response.statusText}`); - }).then(function(json) { - return json.items; - }); -} - -document.querySelector('#search').addEventListener('submit', event => { - event.preventDefault(); - - var results = document.querySelector('#results'); - while (results.firstChild) { - results.removeChild(results.firstChild); - } - - let searchTerm = document.querySelector('#searchTerm').value; - let maxResults = document.querySelector('#maxResults').value; - - youtubeSearch(searchTerm, maxResults).then(videos => { - videos.forEach(video => { - let img = document.createElement('img'); - img.src = video.snippet.thumbnails.medium.url; - results.appendChild(img); - }); - }).catch(error => console.warn('YouTube search failed due to', error)); -}); diff --git a/lib/sw-toolbox/docs/cache-expiration-options/index.html b/lib/sw-toolbox/docs/cache-expiration-options/index.html deleted file mode 100644 index 8cd56ba6..00000000 --- a/lib/sw-toolbox/docs/cache-expiration-options/index.html +++ /dev/null @@ -1,75 +0,0 @@ - - - Cache Expiration Demo - - - - - - -

Cache Expiration Demo

- -

Background

-

- The service worker in this example - demonstrates using the maxCacheEntries and maxCacheAgeSeconds - options. It uses a dedicated cache to hold YouTube video thumbnails. That - dedicated cache will purge entries once they're older than 30 seconds, and store at most 10 - entries. It uses the cacheFirst strategy, so any responses that are still in the - cache will be used directly, without going against the network. -

- -

- While this example uses both maxCacheEntries and maxCacheAgeSeconds, - it's possible to use each of those options independently. -

- -

- The cache used for YouTube thumbnail URLs is separate from the "default" cache, which is - used for all other requests, like YouTube API responses and this page's CSS, JavaScript, and - HTML. The page doesn't impose any upper limit on the size of that default cache, and we can - use a networkFirst strategy for it. -

- -

- Creating a dedicated cache with expiration options for dynamic, unbounded requests is a useful - pattern to follow. If we just used the default cache without imposing a cache expiration, - then that cache would grow in size as more and more searches were performed, needlessly - consuming disk space for old thumbnails that are likely no longer needed. -

- -

Live Demo

-

- Try increasing the number of thumbnails returned, or changing the search term, and then - observe the cache expirations logged in the developer console. -

- - -
- - - - - diff --git a/lib/sw-toolbox/docs/cache-expiration-options/service-worker.js b/lib/sw-toolbox/docs/cache-expiration-options/service-worker.js deleted file mode 100644 index 6da94628..00000000 --- a/lib/sw-toolbox/docs/cache-expiration-options/service-worker.js +++ /dev/null @@ -1,38 +0,0 @@ -(global => { - 'use strict'; - - // Load the sw-tookbox library. - importScripts('../../sw-toolbox.js'); - - // Turn on debug logging, visible in the Developer Tools' console. - global.toolbox.options.debug = true; - - // Set up a handler for HTTP GET requests: - // - /\.ytimg\.com\// will match any requests whose URL contains 'ytimg.com'. - // A narrower RegExp could be used, but just checking for ytimg.com anywhere - // in the URL should be fine for this sample. - // - toolbox.cacheFirst let us to use the predefined cache strategy for those - // requests. - global.toolbox.router.get(/\.ytimg\.com\//, global.toolbox.cacheFirst, { - // Use a dedicated cache for the responses, separate from the default cache. - cache: { - name: 'youtube-thumbnails', - // Store up to 10 entries in that cache. - maxEntries: 10, - // Expire any entries that are older than 30 seconds. - maxAgeSeconds: 30 - } - }); - - // By default, all requests that don't match our custom handler will use the - // toolbox.networkFirst cache strategy, and their responses will be stored in - // the default cache. - global.toolbox.router.default = global.toolbox.networkFirst; - - // Boilerplate to ensure our service worker takes control of the page as soon - // as possible. - global.addEventListener('install', - event => event.waitUntil(global.skipWaiting())); - global.addEventListener('activate', - event => event.waitUntil(global.clients.claim())); -})(self); diff --git a/lib/sw-toolbox/docs/cache-expiration-options/styles.css b/lib/sw-toolbox/docs/cache-expiration-options/styles.css deleted file mode 100644 index 699f63ac..00000000 --- a/lib/sw-toolbox/docs/cache-expiration-options/styles.css +++ /dev/null @@ -1,10 +0,0 @@ -#results { - display: flex; - flex-direction: row; - flex-wrap: wrap; -} - -#results > img { - margin: 4px; - width: 320px; -} diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.eot deleted file mode 100644 index 5d20d916..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.svg deleted file mode 100644 index 3ed7be4b..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.woff deleted file mode 100644 index 1205787b..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Bold-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.eot deleted file mode 100644 index 1f639a15..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.svg deleted file mode 100644 index 6a2607b9..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.woff deleted file mode 100644 index ed760c06..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-BoldItalic-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.eot deleted file mode 100644 index 0c8a0ae0..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.svg deleted file mode 100644 index e1075dcc..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.svg +++ /dev/null @@ -1,1830 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.woff deleted file mode 100644 index ff652e64..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Italic-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.eot deleted file mode 100644 index 14868406..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.svg deleted file mode 100644 index 11a472ca..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.svg +++ /dev/null @@ -1,1831 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.woff deleted file mode 100644 index e7860748..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Light-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.eot deleted file mode 100644 index 8f445929..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.svg deleted file mode 100644 index 431d7e35..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.svg +++ /dev/null @@ -1,1835 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.woff deleted file mode 100644 index 43e8b9e6..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-LightItalic-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.eot b/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.eot deleted file mode 100644 index 6bbc3cf5..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.eot and /dev/null differ diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.svg b/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.svg deleted file mode 100644 index 25a39523..00000000 --- a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.svg +++ /dev/null @@ -1,1831 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.woff b/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.woff deleted file mode 100644 index e231183d..00000000 Binary files a/lib/sw-toolbox/docs/fonts/OpenSans-Regular-webfont.woff and /dev/null differ diff --git a/lib/sw-toolbox/docs/index.html b/lib/sw-toolbox/docs/index.html deleted file mode 100644 index 105adb56..00000000 --- a/lib/sw-toolbox/docs/index.html +++ /dev/null @@ -1,94 +0,0 @@ - - - - - JSDoc: Home - - - - - - - - - - -
- -

Home

- - - - - - - - -

- - - - - - - - - - - - - - - -
-

Service Worker Toolbox

Build Status Dependency Status devDependency Status

-
-

A collection of tools for service workers

-
-

Service Worker Toolbox provides some simple helpers for use in creating your own service workers. Specifically, it provides common caching patterns and an expressive approach to using those strategies for runtime requests. If you're not sure what service workers are or what they are for, start with the explainer doc.

-

Install

Service Worker Toolbox is available through Bower, npm or direct from GitHub:

-

bower install --save sw-toolbox

-

npm install --save sw-toolbox

-

git clone https://github.com/GoogleChrome/sw-toolbox.git

-

Register your service worker

From your registering page, register your service worker in the normal way. For example:

-
navigator.serviceWorker.register('my-service-worker.js');

As implemented in Chrome 40 or later, a service worker must exist at the root of the scope that you intend it to control, or higher. So if you want all of the pages under /myapp/ to be controlled by the worker, the worker script itself must be served from either / or /myapp/. The default scope is the containing path of the service worker script.

-

For even lower friction you can instead include the Service Worker Toolbox companion script in your HTML as shown below. Be aware that this is not customizable. If you need to do anything fancier than registering with a default scope, you'll need to use the standard registration.

-
<script src="/path/to/sw-toolbox/companion.js" data-service-worker="my-service-worker.js"></script>

Add Service Worker Toolbox to your service worker script

In your service worker you just need to use importScripts to load Service Worker Toolbox

-
importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup

Use the toolbox

To understand how to use the toolbox read the usage and api documentation.

-

Support

If you’ve found an error in this library, please file an issue at: https://github.com/GoogleChrome/sw-toolbox/issues.

-

Patches are encouraged, and may be submitted by forking this project and submitting a pull request through GitHub.

-

License

Copyright 2015 Google, Inc.

-

Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. You may -obtain a copy of the License at

-

http://www.apache.org/licenses/LICENSE-2.0

-

Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License.

-
- - - - - - -
- - - -
- -
- Documentation generated by JSDoc 3.4.0 on Thu Jun 09 2016 13:34:34 GMT+0100 (BST) -
- - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/index.md b/lib/sw-toolbox/docs/index.md new file mode 100644 index 00000000..19f12545 --- /dev/null +++ b/lib/sw-toolbox/docs/index.md @@ -0,0 +1,11 @@ +--- +layout: index +title: "SW Toolbox" +navigation_weight: 0 +--- + +# Why + +# Install + +# Usage diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/components/footer.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/footer.html new file mode 100644 index 00000000..85d924f4 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/footer.html @@ -0,0 +1,27 @@ + diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html new file mode 100644 index 00000000..fb520093 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html @@ -0,0 +1,31 @@ +{% if include.docsPath %} + {% capture docsUrl %}{{ project_root_url }}{{ include.docsPath }}{% endcapture %} +
  • + + {{ include.text }} + +
  • + + {% capture filename %}{{ page.url | split: "/" | last }}{% endcapture %} + {% capture currentUrl %}{{ page.url | remove: filename | remove: "//" }}{% endcapture %} + {% capture filteredDocsUrl %}{{ docsUrl | append: "/" }}{% endcapture %} + + {% if filteredDocsUrl == currentUrl and page.jsdocNav %} +
  • +
      + {% for navGroupHash in page.jsdocNav %} + {% for navGroup in navGroupHash %} +
    • {{ navGroup[0] }}
    • +
    • +
        + {% for navGroupItem in navGroup[1] %} +
      • {{ navGroupItem }}
      • + {% endfor %} +
      +
    • + {% endfor %} + {% endfor %} +
    +
  • + {% endif %} +{% endif %} diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer.html new file mode 100644 index 00000000..567564ab --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/nav-drawer.html @@ -0,0 +1,31 @@ +{% include variables.html %} + diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/components/site-header.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/site-header.html new file mode 100644 index 00000000..f09a4988 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/components/site-header.html @@ -0,0 +1,15 @@ + diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/html-head.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/html-head.html new file mode 100644 index 00000000..6ff1c35a --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/html-head.html @@ -0,0 +1,21 @@ +{% include variables.html %} + + + + + + {% if page.title %}{{ page.title | escape }}{% else %}{{ project_title | escape }}{% endif %} + + + + + + + + + + {% if page.layout == 'jsdoc' %} + + + {% endif %} + diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/github.svg b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/github.svg new file mode 100644 index 00000000..14625a56 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/github.svg @@ -0,0 +1,16 @@ + + + + Shape + Created with Sketch. + + + + + + + + + + + \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/gplus.svg b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/gplus.svg new file mode 100644 index 00000000..19320e7e --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/gplus.svg @@ -0,0 +1,22 @@ + +image/svg+xml \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/menu.svg b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/menu.svg new file mode 100644 index 00000000..3521f19a --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/menu.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/twitter.svg b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/twitter.svg new file mode 100644 index 00000000..30aa3148 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/svgs/twitter.svg @@ -0,0 +1,24 @@ + +image/svg+xml \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/_includes/variables.html b/lib/sw-toolbox/docs/jekyll-theme/_includes/variables.html new file mode 100644 index 00000000..978e21c7 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_includes/variables.html @@ -0,0 +1,25 @@ +{% if site.data.customize.project_title %} + {% assign project_title = site.data.customize.project_title %} +{% elsif site.github.project_title %} + {% assign project_title = site.github.project_title %} +{% endif %} + +{% if jekyll.environment == 'development' %} + {% assign project_root_url = '' %} +{% else %} + {% assign project_root_url = site.github.url | replace: 'http://', '//'%} +{% endif %} + +{% if site.data.customize.project_owner %} + {% assign project_owner = site.data.customize.project_owner %} + {% assign project_owner_url = site.data.customize.project_owner_url %} +{% elsif site.github.owner_name %} + {% assign project_owner = site.github.owner_name %} + {% assign project_owner_url = site.github.owner_url %} +{% endif %} + +{% if site.data.customize.project_tagline %} + {% assign project_tagline = site.data.customize.project_tagline %} +{% elsif site.github.project_tagline %} + {% assign project_tagline = site.github.project_tagline %} +{% endif %} diff --git a/lib/sw-toolbox/docs/jekyll-theme/_layouts/default.html b/lib/sw-toolbox/docs/jekyll-theme/_layouts/default.html new file mode 100644 index 00000000..6819ed31 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_layouts/default.html @@ -0,0 +1,14 @@ + + + + {% include html-head.html %} + + + + {{ content }} + + + + + + diff --git a/lib/sw-toolbox/docs/jekyll-theme/_layouts/index.html b/lib/sw-toolbox/docs/jekyll-theme/_layouts/index.html new file mode 100644 index 00000000..9ec6f1d5 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_layouts/index.html @@ -0,0 +1,14 @@ +--- +layout: default +--- +{% include variables.html %} + +{% include components/site-header.html title=project_title subtitle=project_tagline %} + +{% include components/nav-drawer.html %} + +
    + {{ content }} +
    + +{% include components/footer.html made_by='variables.project_owner' made_by_url='varaibles.project_owner_url' %} diff --git a/lib/sw-toolbox/docs/jekyll-theme/_layouts/jsdoc.html b/lib/sw-toolbox/docs/jekyll-theme/_layouts/jsdoc.html new file mode 100644 index 00000000..6094063d --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/_layouts/jsdoc.html @@ -0,0 +1,14 @@ +--- +layout: default +--- +{% include variables.html %} + +{% include components/site-header.html title=project_title subtitle=project_tagline %} + +{% include components/nav-drawer.html %} + +
    + {{ content }} +
    + +{% include components/footer.html made_by='variables.project_owner' made_by_url='varaibles.project_owner_url' %} diff --git a/lib/sw-toolbox/docs/jekyll-theme/scripts/detabinator.js b/lib/sw-toolbox/docs/jekyll-theme/scripts/detabinator.js new file mode 100644 index 00000000..a67325c1 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/scripts/detabinator.js @@ -0,0 +1,70 @@ +/** + * + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Usage: + * const detabinator = new Detabinator(element); + * detabinator.inert = true; // Sets all focusable children of element to tabindex=-1 + * detabinator.inert = false; // Restores all focusable children of element + * Limitations: Doesn't support Shadow DOM v0 :P + */ + +class Detabinator { + constructor(element) { + if (!element) { + throw new Error('Missing required argument. new Detabinator needs an element reference'); + } + this._inert = false; + this._focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex], [contenteditable]'; + this._focusableElements = Array.from( + element.querySelectorAll(this._focusableElementsString) + ); + } + + get inert() { + return this._inert; + } + + set inert(isInert) { + if (this._inert === isInert) { + return; + } + + this._inert = isInert; + + this._focusableElements.forEach((child) => { + if (isInert) { + // If the child has an explict tabindex save it + if (child.hasAttribute('tabindex')) { + child.__savedTabindex = child.tabIndex; + } + // Set ALL focusable children to tabindex -1 + child.setAttribute('tabindex', -1); + } else { + // If the child has a saved tabindex, restore it + // Because the value could be 0, explicitly check that it's not false + if (child.__savedTabindex === 0 || child.__savedTabindex) { + return child.setAttribute('tabindex', child.__savedTabindex); + } else { + // Remove tabindex from ANY REMAINING children + child.removeAttribute('tabindex'); + } + } + }); + } +} diff --git a/lib/sw-toolbox/docs/jekyll-theme/scripts/side-nav.js b/lib/sw-toolbox/docs/jekyll-theme/scripts/side-nav.js new file mode 100644 index 00000000..b3d9f5d3 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/scripts/side-nav.js @@ -0,0 +1,146 @@ +/** + * + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +class SideNav { + constructor () { + this.showButtonEl = document.querySelector('.js-menu-show'); + this.hideButtonEl = document.querySelector('.js-menu-hide'); + this.sideNavEl = document.querySelector('.js-side-nav'); + this.sideNavContainerEl = document.querySelector('.js-side-nav-container'); + // Control whether the container's children can be focused + // Set initial state to inert since the drawer is offscreen + this.detabinator = new Detabinator(this.sideNavContainerEl); + this.detabinator.inert = true; + + this.showSideNav = this.showSideNav.bind(this); + this.hideSideNav = this.hideSideNav.bind(this); + this.blockClicks = this.blockClicks.bind(this); + this.onTouchStart = this.onTouchStart.bind(this); + this.onTouchMove = this.onTouchMove.bind(this); + this.onTouchEnd = this.onTouchEnd.bind(this); + this.onTransitionEnd = this.onTransitionEnd.bind(this); + this.update = this.update.bind(this); + + this.startX = 0; + this.currentX = 0; + this.touchingSideNav = false; + + this.supportsPassive = undefined; + this.addEventListeners(); + } + + // apply passive event listening if it's supported + applyPassive () { + if (this.supportsPassive !== undefined) { + return this.supportsPassive ? {passive: true} : false; + } + // feature detect + let isSupported = false; + try { + document.addEventListener('test', null, {get passive () { + isSupported = true; + }}); + } catch (e) { } + this.supportsPassive = isSupported; + return this.applyPassive(); + } + + addEventListeners () { + this.showButtonEl.addEventListener('click', this.showSideNav); + this.hideButtonEl.addEventListener('click', this.hideSideNav); + this.sideNavEl.addEventListener('click', this.hideSideNav); + this.sideNavContainerEl.addEventListener('click', this.blockClicks); + + this.sideNavEl.addEventListener('touchstart', this.onTouchStart, this.applyPassive()); + this.sideNavEl.addEventListener('touchmove', this.onTouchMove, this.applyPassive()); + this.sideNavEl.addEventListener('touchend', this.onTouchEnd); + } + + onTouchStart (evt) { + if (!this.sideNavEl.classList.contains('side-nav--visible')) + return; + + this.startX = evt.touches[0].pageX; + this.currentX = this.startX; + + this.touchingSideNav = true; + requestAnimationFrame(this.update); + } + + onTouchMove (evt) { + if (!this.touchingSideNav) + return; + + this.currentX = evt.touches[0].pageX; + const translateX = Math.min(0, this.currentX - this.startX); + + if (translateX < 0) { + evt.preventDefault(); + } + } + + onTouchEnd (evt) { + if (!this.touchingSideNav) + return; + + this.touchingSideNav = false; + + const translateX = Math.min(0, this.currentX - this.startX); + this.sideNavContainerEl.style.transform = ''; + + if (translateX < 0) { + this.hideSideNav(); + } + } + + update () { + if (!this.touchingSideNav) + return; + + requestAnimationFrame(this.update); + + const translateX = Math.min(0, this.currentX - this.startX); + this.sideNavContainerEl.style.transform = `translateX(${translateX}px)`; + } + + blockClicks (evt) { + evt.stopPropagation(); + } + + onTransitionEnd (evt) { + this.sideNavEl.classList.remove('side-nav--animatable'); + this.sideNavEl.removeEventListener('transitionend', this.onTransitionEnd); + } + + showSideNav () { + this.sideNavEl.classList.add('side-nav--animatable'); + this.sideNavEl.classList.add('side-nav--visible'); + this.detabinator.inert = false; + this.sideNavEl.addEventListener('transitionend', this.onTransitionEnd); + } + + hideSideNav () { + this.sideNavEl.classList.add('side-nav--animatable'); + this.sideNavEl.classList.remove('side-nav--visible'); + this.detabinator.inert = true; + this.sideNavEl.addEventListener('transitionend', this.onTransitionEnd); + } +} + +new SideNav(); diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/components/code-styles.css b/lib/sw-toolbox/docs/jekyll-theme/styles/components/code-styles.css new file mode 100644 index 00000000..08ce23d7 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/components/code-styles.css @@ -0,0 +1 @@ +code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}figure.highlight{margin:0}code,code[class*=language-],pre,pre[class*=language-]{background-color:rgba(0,0,0,.06);border-radius:3px;white-space:pre-wrap;text-shadow:none}pre,pre[class*=language-]{padding:16px}code,code[class*=language-]{display:inline-block;font-size:12px}code[class*=language-],pre[class*=language-]{color:rgba(0,0,0,.87)}code:after,code:before,code[class*=language-]:after,code[class*=language-]:before{letter-spacing:-.2em;content:"\00a0"}pre[class*=language-] code[class*=language-],pre code{width:100%;font-size:inherit;background-color:transparent;padding:0;box-sizing:border-box;word-break:break-word}pre code:after,pre code:before{content:none}.token.attr-name,.token.builtin,.token.selector,.token.string{color:#e91e63}.token.boolean,.token.constant,.token.number,.token.property,.token.symbol,.token.tag{color:#9d1db3}.token.atrule,.token.attr-value,.token.keyword{color:#00bcd4}.token.cr:before,.token.lf:before{display:none}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url,.token.variable{color:#9d1db3;background:none}.token.function{color:#009688} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/components/footer.css b/lib/sw-toolbox/docs/jekyll-theme/styles/components/footer.css new file mode 100644 index 00000000..b2ffebd4 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/components/footer.css @@ -0,0 +1 @@ +footer{height:120px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:stretch;align-items:stretch;-ms-flex-pack:center;justify-content:center;background-color:#212121;color:var(--callout-text-color);padding:32px 40px;font-size:12px}footer a{color:inherit;text-decoration:none}footer .footer-links,footer .social-btns{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;list-style:none;padding:0;margin:14px 0}footer .social-btn{margin:0 40px}footer .social-btn>svg{width:24px;height:24px} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/components/nav-drawer.css b/lib/sw-toolbox/docs/jekyll-theme/styles/components/nav-drawer.css new file mode 100644 index 00000000..83fcc3cb --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/components/nav-drawer.css @@ -0,0 +1 @@ +.side-nav{position:fixed;left:0;top:0;width:100%;height:100%;overflow:hidden;pointer-events:none}.side-nav--visible{pointer-events:auto}.side-nav:before{content:'';display:block;position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,.4);opacity:0;will-change:opacity;transition:opacity .3s cubic-bezier(0,0,.3,1)}.side-nav__container{position:relative;width:90%;max-width:260px;background:#fff;height:100%;box-shadow:2px 0 12px rgba(0,0,0,.4);transform:translateX(-102%);display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;will-change:transform}.side-nav--animatable .side-nav__container{transition:transform .13s cubic-bezier(0,0,.3,1)}.side-nav--visible.side-nav--animatable .side-nav__container{transition:transform .33s cubic-bezier(0,0,.3,1)}.side-nav--visible:before{opacity:1}.side-nav--visible .side-nav__container{transform:none}.side-nav__hide{position:absolute;left:16px;top:16px;background:none;border:none;color:#fff;width:24px;height:24px;padding:0;margin:0} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/components/page-header.css b/lib/sw-toolbox/docs/jekyll-theme/styles/components/page-header.css new file mode 100644 index 00000000..87181dc7 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/components/page-header.css @@ -0,0 +1 @@ +.page-header{height:64px;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;background-color:#37474f;color:#fff;padding:0}.page-header .menu-btn{width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.page-header .menu-btn svg{width:24px;height:24px}.page-header h1{width:100%;font-size:13px;line-height:64px;margin:0;padding-right:40px} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/components/site-header.css b/lib/sw-toolbox/docs/jekyll-theme/styles/components/site-header.css new file mode 100644 index 00000000..59db3b73 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/components/site-header.css @@ -0,0 +1 @@ +.site-header{height:288px;position:relative;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background-color:#37474f;color:#fff;padding:0}.site-header,.site-header__heading{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.site-header__heading{text-align:center}.site-header__heading h1,.site-header__heading h2{margin:0;padding:0}.site-header__heading h2{opacity:.6}.site-header .menu-btn{position:absolute;top:0;left:0;width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.site-header .menu-btn svg{width:24px;height:24px} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/details.css b/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/details.css new file mode 100644 index 00000000..12bd86f6 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/details.css @@ -0,0 +1 @@ +.is-jsdoc-page .details dd,.is-jsdoc-page .details dt{display:inline-block;margin:0}.is-jsdoc-page .details dd ul{list-style:none;margin:0;padding:0} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/method.css b/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/method.css new file mode 100644 index 00000000..4dbb3fdf --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/jsdoc/method.css @@ -0,0 +1 @@ +.jsdoc-method p{margin-bottom:8px}.jsdoc-params-heading,.jsdoc-returns-heading{margin:0;padding:8px;background-color:#37474f;color:#fff}.jsdoc-method{margin-bottom:64px} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/main.css b/lib/sw-toolbox/docs/jekyll-theme/styles/main.css new file mode 100644 index 00000000..c91df49b --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/styles/main.css @@ -0,0 +1 @@ +@font-face{font-family:Roboto;font-style:normal;font-weight:300;src:local('Roboto Light'),local('Roboto-Light'),url(https://fonts.gstatic.com/s/roboto/v15/Hgo13k-tfSpn0qi1SFdUfaCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:400;src:local('Roboto'),local('Roboto-Regular'),url(https://fonts.gstatic.com/s/roboto/v15/zN7GBFwfMP4uA6AR0HCoLQ.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:500;src:local('Roboto Medium'),local('Roboto-Medium'),url(https://fonts.gstatic.com/s/roboto/v15/RxZJdnzeo3R5zSexge8UUaCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:700;src:local('Roboto Bold'),local('Roboto-Bold'),url(https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOKCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}.page-header{height:64px;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;background-color:#37474f;color:#fff;padding:0}.page-header .menu-btn{width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.page-header .menu-btn svg{width:24px;height:24px}.page-header h1{width:100%;font-size:13px;line-height:64px;margin:0;padding-right:40px}.site-header{height:288px;position:relative;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background-color:#37474f;color:#fff;padding:0}.site-header,.site-header__heading{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.site-header__heading{text-align:center}.site-header__heading h1,.site-header__heading h2{margin:0;padding:0}.site-header__heading h2{opacity:.6}.site-header .menu-btn{position:absolute;top:0;left:0;width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.site-header .menu-btn svg{width:24px;height:24px}footer{height:120px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:stretch;align-items:stretch;-ms-flex-pack:center;justify-content:center;background-color:#212121;color:#fff;padding:32px 40px;font-size:12px}footer a{color:inherit;text-decoration:none}footer .footer-links,footer .social-btns{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;list-style:none;padding:0;margin:14px 0}footer .social-btn{margin:0 40px}footer .social-btn>svg{width:24px;height:24px}code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}figure.highlight{margin:0}code,code[class*=language-],pre,pre[class*=language-]{background-color:rgba(0,0,0,.06);border-radius:3px;white-space:pre-wrap;text-shadow:none}pre,pre[class*=language-]{padding:16px}code,code[class*=language-]{display:inline-block;font-size:12px}code[class*=language-],pre[class*=language-]{color:rgba(0,0,0,.87)}code:after,code:before,code[class*=language-]:after,code[class*=language-]:before{letter-spacing:-.2em;content:"\00a0"}pre[class*=language-] code[class*=language-],pre code{width:100%;font-size:inherit;background-color:transparent;padding:0;box-sizing:border-box;word-break:break-word}pre code:after,pre code:before{content:none}.token.attr-name,.token.builtin,.token.selector,.token.string{color:#e91e63}.token.boolean,.token.constant,.token.number,.token.property,.token.symbol,.token.tag{color:#9d1db3}.token.atrule,.token.attr-value,.token.keyword{color:#00bcd4}.token.cr:before,.token.lf:before{display:none}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url,.token.variable{color:#9d1db3;background:none}.token.function{color:#009688}body,html{width:100%;margin:0;padding:0}body{font-family:Roboto,sans-serif;font-weight:400;line-height:2em;color:#757575}main{max-width:720px;padding:40px;box-sizing:border-box;margin-left:auto;margin-right:auto}p{margin-top:0;margin-bottom:32px}a{color:#37474f;text-decoration:none;font-weight:500}.button,button{display:inline-block;min-width:64px;height:36px;color:#fff;background-color:#37474f;border:none;padding:0 16px;font-size:14px;font-weight:500;text-transform:uppercase;letter-spacing:0;text-align:center;line-height:36px;cursor:pointer}ol,ul{padding-left:20px;line-height:24px}h1{text-transform:uppercase}h1,h2{font-size:16px;font-weight:500;padding-right:60px;margin:40px 0}h3{margin:24px 0}h3,h4{font-size:15px;line-height:25px;font-weight:500;padding-right:60px}h4{margin-top:24px;margin-bottom:16px}h5{margin-bottom:8px}h5,h6{font-size:12px;line-height:25px;font-weight:700;padding-right:60px;margin-top:24px}h6{margin-bottom:0}table{width:100%;margin-bottom:8px}table,td,th{border-style:solid;border-width:1px;border-collapse:collapse}td{padding:4px}td code{background:inherit}.u-center{text-align:center}.side-nav__container ul{padding:0;margin:0 0 0 16px;list-style-type:none}.side-nav__container>ul{margin:0}.side-nav__container ul li.side-nav__title,.side-nav__container ul li a{display:block;padding:12px 16px}.side-nav__container .subheading{display:block;padding:0 16px} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/variables/colors.css b/lib/sw-toolbox/docs/jekyll-theme/styles/variables/colors.css new file mode 100644 index 00000000..e69de29b diff --git a/lib/sw-toolbox/docs/jekyll-theme/styles/variables/dimens.css b/lib/sw-toolbox/docs/jekyll-theme/styles/variables/dimens.css new file mode 100644 index 00000000..e69de29b diff --git a/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.css b/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.css new file mode 100644 index 00000000..12218df2 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.css @@ -0,0 +1 @@ +code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help} \ No newline at end of file diff --git a/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.js b/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.js new file mode 100644 index 00000000..7a5a86a5 --- /dev/null +++ b/lib/sw-toolbox/docs/jekyll-theme/third_party/prism/prism.js @@ -0,0 +1,9 @@ +/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+bash+git+markdown */ +var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/e.length)break e;if(!(v instanceof a)){u.lastIndex=0;var b=u.exec(v),k=1;if(!b&&h&&m!=r.length-1){if(u.lastIndex=y,b=u.exec(e),!b)break;for(var w=b.index+(g?b[1].length:0),_=b.index+b[0].length,A=m,S=y,P=r.length;P>A&&_>S;++A)S+=(r[A].matchedStr||r[A]).length,w>=S&&(++m,y=S);if(r[m]instanceof a||r[A-1].greedy)continue;k=A-m,v=e.slice(y,S),b.index-=y}if(b){g&&(f=b[1].length);var w=b.index+f,b=b[0].slice(f),_=w+b.length,x=v.slice(0,w),O=v.slice(_),j=[m,k];x&&j.push(x);var N=new a(l,c?n.tokenize(b,c):b,d,b,h);j.push(N),O&&j.push(O),Array.prototype.splice.apply(r,j)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var i={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}n.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=(o?" ":"")+s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+o+">"+i.content+""},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,i=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),i&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(n.highlightAll):window.setTimeout(n.highlightAll,16):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); +Prism.languages.markup={comment://,prolog:/<\?[\w\W]+?\?>/,doctype://,cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,inside:{punctuation:/[=>"']/}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},Prism.hooks.add("wrap",function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))}),Prism.languages.xml=Prism.languages.markup,Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup; +Prism.languages.css={comment:/\/\*[\w\W]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^\{\}\s][^\{\};]*?(?=\s*\{)/,string:/("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,property:/(\b|\B)[\w-]+(?=\s*:)/i,important:/\B!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},Prism.languages.css.atrule.inside.rest=Prism.util.clone(Prism.languages.css),Prism.languages.markup&&(Prism.languages.insertBefore("markup","tag",{style:{pattern:/()[\w\W]*?(?=<\/style>)/i,lookbehind:!0,inside:Prism.languages.css,alias:"language-css"}}),Prism.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|').*?\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:Prism.languages.markup.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:Prism.languages.css}},alias:"language-css"}},Prism.languages.markup.tag)); +Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0}],string:{pattern:/(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(true|false)\b/,"function":/[a-z0-9_]+(?=\()/i,number:/\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/}; +Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,"function":/[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^\/])\/(?!\/)(\[.+?]|\\.|[^\/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0,greedy:!0}}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\\\|\\?[^\\])*?`/,greedy:!0,inside:{interpolation:{pattern:/\$\{[^}]+\}/,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/()[\w\W]*?(?=<\/script>)/i,lookbehind:!0,inside:Prism.languages.javascript,alias:"language-javascript"}}),Prism.languages.js=Prism.languages.javascript; +!function(e){var t={variable:[{pattern:/\$?\(\([\w\W]+?\)\)/,inside:{variable:[{pattern:/(^\$\(\([\w\W]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/,operator:/--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\([^)]+\)|`[^`]+`/,inside:{variable:/^\$\(|^`|\)$|`$/}},/\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i]};e.languages.bash={shebang:{pattern:/^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/,alias:"important"},comment:{pattern:/(^|[^"{\\])#.*/,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g,lookbehind:!0,greedy:!0,inside:t},{pattern:/(["'])(?:\\\\|\\?[^\\])*?\1/g,greedy:!0,inside:t}],variable:t.variable,"function":{pattern:/(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/,lookbehind:!0},keyword:{pattern:/(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/,lookbehind:!0},"boolean":{pattern:/(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/,lookbehind:!0},operator:/&&?|\|\|?|==?|!=?|<<>|<=?|>=?|=~/,punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];]/};var a=t.variable[1].inside;a["function"]=e.languages.bash["function"],a.keyword=e.languages.bash.keyword,a.boolean=e.languages.bash.boolean,a.operator=e.languages.bash.operator,a.punctuation=e.languages.bash.punctuation}(Prism); +Prism.languages.git={comment:/^#.*/m,deleted:/^[-–].*/m,inserted:/^\+.*/m,string:/("|')(\\?.)*?\1/m,command:{pattern:/^.*\$ git .*$/m,inside:{parameter:/\s(--|-)\w+/m}},coord:/^@@.*@@$/m,commit_sha1:/^commit \w{40}$/m}; +Prism.languages.markdown=Prism.languages.extend("markup",{}),Prism.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},code:[{pattern:/^(?: {4}|\t).+/m,alias:"keyword"},{pattern:/``.+?``|`[^`\n]+`/,alias:"keyword"}],title:[{pattern:/\w+.*(?:\r?\n|\r)(?:==+|--+)/,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:/(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^\*\*|^__|\*\*$|__$/}},italic:{pattern:/(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^[*_]|[*_]$/}},url:{pattern:/!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/,inside:{variable:{pattern:/(!?\[)[^\]]+(?=\]$)/,lookbehind:!0},string:{pattern:/"(?:\\.|[^"\\])*"(?=\)$)/}}}}),Prism.languages.markdown.bold.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.italic.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.bold.inside.italic=Prism.util.clone(Prism.languages.markdown.italic),Prism.languages.markdown.italic.inside.bold=Prism.util.clone(Prism.languages.markdown.bold); diff --git a/lib/sw-toolbox/docs/recipes.md b/lib/sw-toolbox/docs/recipes.md new file mode 100644 index 00000000..b430f327 --- /dev/null +++ b/lib/sw-toolbox/docs/recipes.md @@ -0,0 +1,16 @@ +--- +layout: index +title: "SW Toolbox Recipes" +navigation_weight: 3 +--- + +
      +
    • +

      Cache Expiration

      +

      + Demonstrates using the maxEntries and maxAgeSeconds options + to limit the number and age of entries stored in a cache dedicated to images fetched + from an API. +

      +
    • +
    diff --git a/lib/sw-toolbox/docs/scripts/linenumber.js b/lib/sw-toolbox/docs/scripts/linenumber.js deleted file mode 100644 index 8d52f7ea..00000000 --- a/lib/sw-toolbox/docs/scripts/linenumber.js +++ /dev/null @@ -1,25 +0,0 @@ -/*global document */ -(function() { - var source = document.getElementsByClassName('prettyprint source linenums'); - var i = 0; - var lineNumber = 0; - var lineId; - var lines; - var totalLines; - var anchorHash; - - if (source && source[0]) { - anchorHash = document.location.hash.substring(1); - lines = source[0].getElementsByTagName('li'); - totalLines = lines.length; - - for (; i < totalLines; i++) { - lineNumber++; - lineId = 'line' + lineNumber; - lines[i].id = lineId; - if (lineId === anchorHash) { - lines[i].className += ' selected'; - } - } - } -})(); diff --git a/lib/sw-toolbox/docs/scripts/prettify/Apache-License-2.0.txt b/lib/sw-toolbox/docs/scripts/prettify/Apache-License-2.0.txt deleted file mode 100644 index d6456956..00000000 --- a/lib/sw-toolbox/docs/scripts/prettify/Apache-License-2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/lib/sw-toolbox/docs/scripts/prettify/lang-css.js b/lib/sw-toolbox/docs/scripts/prettify/lang-css.js deleted file mode 100644 index 041e1f59..00000000 --- a/lib/sw-toolbox/docs/scripts/prettify/lang-css.js +++ /dev/null @@ -1,2 +0,0 @@ -PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", -/^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); diff --git a/lib/sw-toolbox/docs/scripts/prettify/prettify.js b/lib/sw-toolbox/docs/scripts/prettify/prettify.js deleted file mode 100644 index eef5ad7e..00000000 --- a/lib/sw-toolbox/docs/scripts/prettify/prettify.js +++ /dev/null @@ -1,28 +0,0 @@ -var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; -(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= -[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), -l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, -q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, -q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, -"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), -a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} -for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], -"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], -H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], -J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ -I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), -["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", -/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), -["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", -hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= -!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p p:first-child, -.props td.description > p:first-child -{ - margin-top: 0; - padding-top: 0; -} - -.params td.description > p:last-child, -.props td.description > p:last-child -{ - margin-bottom: 0; - padding-bottom: 0; -} - -.disabled { - color: #454545; -} diff --git a/lib/sw-toolbox/docs/styles/prettify-jsdoc.css b/lib/sw-toolbox/docs/styles/prettify-jsdoc.css deleted file mode 100644 index 5a2526e3..00000000 --- a/lib/sw-toolbox/docs/styles/prettify-jsdoc.css +++ /dev/null @@ -1,111 +0,0 @@ -/* JSDoc prettify.js theme */ - -/* plain text */ -.pln { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* string content */ -.str { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a keyword */ -.kwd { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a comment */ -.com { - font-weight: normal; - font-style: italic; -} - -/* a type name */ -.typ { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* a literal value */ -.lit { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* punctuation */ -.pun { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* lisp open bracket */ -.opn { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* lisp close bracket */ -.clo { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a markup tag name */ -.tag { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a markup attribute name */ -.atn { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a markup attribute value */ -.atv { - color: #006400; - font-weight: normal; - font-style: normal; -} - -/* a declaration */ -.dec { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* a variable name */ -.var { - color: #000000; - font-weight: normal; - font-style: normal; -} - -/* a function name */ -.fun { - color: #000000; - font-weight: bold; - font-style: normal; -} - -/* Specify class=linenums on a pre to get line numbering */ -ol.linenums { - margin-top: 0; - margin-bottom: 0; -} diff --git a/lib/sw-toolbox/docs/styles/prettify-tomorrow.css b/lib/sw-toolbox/docs/styles/prettify-tomorrow.css deleted file mode 100644 index b6f92a78..00000000 --- a/lib/sw-toolbox/docs/styles/prettify-tomorrow.css +++ /dev/null @@ -1,132 +0,0 @@ -/* Tomorrow Theme */ -/* Original theme - https://github.com/chriskempson/tomorrow-theme */ -/* Pretty printing styles. Used with prettify.js. */ -/* SPAN elements with the classes below are added by prettyprint. */ -/* plain text */ -.pln { - color: #4d4d4c; } - -@media screen { - /* string content */ - .str { - color: #718c00; } - - /* a keyword */ - .kwd { - color: #8959a8; } - - /* a comment */ - .com { - color: #8e908c; } - - /* a type name */ - .typ { - color: #4271ae; } - - /* a literal value */ - .lit { - color: #f5871f; } - - /* punctuation */ - .pun { - color: #4d4d4c; } - - /* lisp open bracket */ - .opn { - color: #4d4d4c; } - - /* lisp close bracket */ - .clo { - color: #4d4d4c; } - - /* a markup tag name */ - .tag { - color: #c82829; } - - /* a markup attribute name */ - .atn { - color: #f5871f; } - - /* a markup attribute value */ - .atv { - color: #3e999f; } - - /* a declaration */ - .dec { - color: #f5871f; } - - /* a variable name */ - .var { - color: #c82829; } - - /* a function name */ - .fun { - color: #4271ae; } } -/* Use higher contrast and text-weight for printable form. */ -@media print, projection { - .str { - color: #060; } - - .kwd { - color: #006; - font-weight: bold; } - - .com { - color: #600; - font-style: italic; } - - .typ { - color: #404; - font-weight: bold; } - - .lit { - color: #044; } - - .pun, .opn, .clo { - color: #440; } - - .tag { - color: #006; - font-weight: bold; } - - .atn { - color: #404; } - - .atv { - color: #060; } } -/* Style */ -/* -pre.prettyprint { - background: white; - font-family: Consolas, Monaco, 'Andale Mono', monospace; - font-size: 12px; - line-height: 1.5; - border: 1px solid #ccc; - padding: 10px; } -*/ - -/* Specify class=linenums on a pre to get line numbering */ -ol.linenums { - margin-top: 0; - margin-bottom: 0; } - -/* IE indents via margin-left */ -li.L0, -li.L1, -li.L2, -li.L3, -li.L4, -li.L5, -li.L6, -li.L7, -li.L8, -li.L9 { - /* */ } - -/* Alternate shading for lines */ -li.L1, -li.L3, -li.L5, -li.L7, -li.L9 { - /* */ } diff --git a/lib/sw-toolbox/docs/sw-toolbox.js b/lib/sw-toolbox/docs/sw-toolbox.js deleted file mode 100644 index 528e708d..00000000 --- a/lib/sw-toolbox/docs/sw-toolbox.js +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2014 Google Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -(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.toolbox = 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;or.value[TIMESTAMP_PROPERTY]){var t=r.value[URL_PROPERTY];u.push(t),s["delete"](t),r["continue"]()}},c.oncomplete=function(){t(u)},c.onabort=o}):Promise.resolve([])}function expireExtraEntries(e,r){return r?new Promise(function(n,t){var o=[],i=e.transaction(STORE_NAME,"readwrite"),u=i.objectStore(STORE_NAME),c=u.index(TIMESTAMP_PROPERTY),s=c.count();c.count().onsuccess=function(){var e=s.result;e>r&&(c.openCursor().onsuccess=function(n){var t=n.target.result;if(t){var i=t.value[URL_PROPERTY];o.push(i),u["delete"](i),e-o.length>r&&t["continue"]()}})},i.oncomplete=function(){n(o)},i.onabort=t}):Promise.resolve([])}function expireEntries(e,r,n,t){return expireOldEntries(e,n,t).then(function(n){return expireExtraEntries(e,r).then(function(e){return n.concat(e)})})}var DB_PREFIX="sw-toolbox-",DB_VERSION=1,STORE_NAME="store",URL_PROPERTY="url",TIMESTAMP_PROPERTY="timestamp",cacheNameToDbPromise={};module.exports={getDb:getDb,setTimestampForUrl:setTimestampForUrl,expireEntries:expireEntries}; -},{}],3:[function(require,module,exports){ -"use strict";var scope;scope=self.registration?self.registration.scope:self.scope||new URL("./",self.location).href,module.exports={cache:{name:"$$$toolbox-cache$$$"+scope+"$$$",maxAgeSeconds:null,maxEntries:null},debug:!1,networkTimeoutSeconds:null,preCacheItems:[],successResponses:/^0|([123]\d\d)|(40[14567])|410$/}; -},{}],4:[function(require,module,exports){ -"use strict";var url=new URL("./",self.location),basePath=url.pathname,pathRegexp=require("path-to-regexp"),Route=function(e,t,i,s){t instanceof RegExp?this.fullUrlRegExp=t:(0!==t.indexOf("/")&&(t=basePath+t),this.keys=[],this.regexp=pathRegexp(t,this.keys)),this.method=e,this.options=s,this.handler=i};Route.prototype.makeHandler=function(e){var t;if(this.regexp){var i=this.regexp.exec(e);t={},this.keys.forEach(function(e,s){t[e.name]=i[s+1]})}return function(e){return this.handler(e,t,this.options)}.bind(this)},module.exports=Route; -},{"path-to-regexp":14}],5:[function(require,module,exports){ -"use strict";function regexEscape(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var Route=require("./route"),keyMatch=function(e,t){for(var r=e.entries(),o=r.next(),n=[];!o.done;){var u=new RegExp(o.value[0]);u.test(t)&&n.push(o.value[1]),o=r.next()}return n},Router=function(){this.routes=new Map,this.routes.set(RegExp,new Map),this["default"]=null};["get","post","put","delete","head","any"].forEach(function(e){Router.prototype[e]=function(t,r,o){return this.add(e,t,r,o)}}),Router.prototype.add=function(e,t,r,o){o=o||{};var n;t instanceof RegExp?n=RegExp:(n=o.origin||self.location.origin,n=n instanceof RegExp?n.source:regexEscape(n)),e=e.toLowerCase();var u=new Route(e,t,r,o);this.routes.has(n)||this.routes.set(n,new Map);var a=this.routes.get(n);a.has(e)||a.set(e,new Map);var s=a.get(e),i=u.regexp||u.fullUrlRegExp;s.set(i.source,u)},Router.prototype.matchMethod=function(e,t){var r=new URL(t),o=r.origin,n=r.pathname;return this._match(e,keyMatch(this.routes,o),n)||this._match(e,[this.routes.get(RegExp)],t)},Router.prototype._match=function(e,t,r){if(0===t.length)return null;for(var o=0;o0)return a[0].makeHandler(r)}}return null},Router.prototype.match=function(e){return this.matchMethod(e.method,e.url)||this.matchMethod("any",e.url)},module.exports=new Router; -},{"./route":4}],6:[function(require,module,exports){ -"use strict";function cacheFirst(e,r,t){return helpers.debug("Strategy: cache first ["+e.url+"]",t),helpers.openCache(t).then(function(r){return r.match(e).then(function(r){return r?r:helpers.fetchAndCache(e,t)})})}var helpers=require("../helpers");module.exports=cacheFirst; -},{"../helpers":1}],7:[function(require,module,exports){ -"use strict";function cacheOnly(e,r,c){return helpers.debug("Strategy: cache only ["+e.url+"]",c),helpers.openCache(c).then(function(r){return r.match(e)})}var helpers=require("../helpers");module.exports=cacheOnly; -},{"../helpers":1}],8:[function(require,module,exports){ -"use strict";function fastest(e,n,t){return helpers.debug("Strategy: fastest ["+e.url+"]",t),new Promise(function(r,s){var c=!1,o=[],a=function(e){o.push(e.toString()),c?s(new Error('Both cache and network failed: "'+o.join('", "')+'"')):c=!0},h=function(e){e instanceof Response?r(e):a("No result returned")};helpers.fetchAndCache(e.clone(),t).then(h,a),cacheOnly(e,n,t).then(h,a)})}var helpers=require("../helpers"),cacheOnly=require("./cacheOnly");module.exports=fastest; -},{"../helpers":1,"./cacheOnly":7}],9:[function(require,module,exports){ -module.exports={networkOnly:require("./networkOnly"),networkFirst:require("./networkFirst"),cacheOnly:require("./cacheOnly"),cacheFirst:require("./cacheFirst"),fastest:require("./fastest")}; -},{"./cacheFirst":6,"./cacheOnly":7,"./fastest":8,"./networkFirst":10,"./networkOnly":11}],10:[function(require,module,exports){ -"use strict";function networkFirst(e,r,t){t=t||{};var s=t.successResponses||globalOptions.successResponses,n=t.networkTimeoutSeconds||globalOptions.networkTimeoutSeconds;return helpers.debug("Strategy: network first ["+e.url+"]",t),helpers.openCache(t).then(function(r){var o,u,i=[];if(n){var c=new Promise(function(t){o=setTimeout(function(){r.match(e).then(function(e){e&&t(e)})},1e3*n)});i.push(c)}var a=helpers.fetchAndCache(e,t).then(function(e){if(o&&clearTimeout(o),s.test(e.status))return e;throw helpers.debug("Response was an HTTP error: "+e.statusText,t),u=e,new Error("Bad response")})["catch"](function(s){return helpers.debug("Network or response error, fallback to cache ["+e.url+"]",t),r.match(e).then(function(e){if(e)return e;if(u)return u;throw s})});return i.push(a),Promise.race(i)})}var globalOptions=require("../options"),helpers=require("../helpers");module.exports=networkFirst; -},{"../helpers":1,"../options":3}],11:[function(require,module,exports){ -"use strict";function networkOnly(e,r,t){return helpers.debug("Strategy: network only ["+e.url+"]",t),fetch(e)}var helpers=require("../helpers");module.exports=networkOnly; -},{"../helpers":1}],12:[function(require,module,exports){ -"use strict";function cache(e,t){return helpers.openCache(t).then(function(t){return t.add(e)})}function uncache(e,t){return helpers.openCache(t).then(function(t){return t["delete"](e)})}function precache(e){e instanceof Promise||validatePrecacheInput(e),options.preCacheItems=options.preCacheItems.concat(e)}require("serviceworker-cache-polyfill");var options=require("./options"),router=require("./router"),helpers=require("./helpers"),strategies=require("./strategies");helpers.debug("Service Worker Toolbox is loading");var flatten=function(e){return e.reduce(function(e,t){return e.concat(t)},[])},validatePrecacheInput=function(e){var t=Array.isArray(e);if(t&&e.forEach(function(e){"string"==typeof e||e instanceof Request||(t=!1)}),!t)throw new TypeError("The precache method expects either an array of strings and/or Requests or a Promise that resolves to an array of strings and/or Requests.");return e};self.addEventListener("install",function(e){var t=options.cache.name+"$$$inactive$$$";helpers.debug("install event fired"),helpers.debug("creating cache ["+t+"]"),e.waitUntil(helpers.openCache({cache:{name:t}}).then(function(e){return Promise.all(options.preCacheItems).then(flatten).then(validatePrecacheInput).then(function(t){return helpers.debug("preCache list: "+(t.join(", ")||"(none)")),e.addAll(t)})}))}),self.addEventListener("activate",function(e){helpers.debug("activate event fired");var t=options.cache.name+"$$$inactive$$$";e.waitUntil(helpers.renameCache(t,options.cache.name))}),self.addEventListener("fetch",function(e){var t=router.match(e.request);t?e.respondWith(t(e.request)):router["default"]&&"GET"===e.request.method&&e.respondWith(router["default"](e.request))}),module.exports={networkOnly:strategies.networkOnly,networkFirst:strategies.networkFirst,cacheOnly:strategies.cacheOnly,cacheFirst:strategies.cacheFirst,fastest:strategies.fastest,router:router,options:options,cache:cache,uncache:uncache,precache:precache}; -},{"./helpers":1,"./options":3,"./router":5,"./strategies":9,"serviceworker-cache-polyfill":15}],13:[function(require,module,exports){ -module.exports=Array.isArray||function(r){return"[object Array]"==Object.prototype.toString.call(r)}; -},{}],14:[function(require,module,exports){ -function parse(e){for(var t,r=[],n=0,o=0,a="";null!=(t=PATH_REGEXP.exec(e));){var p=t[0],i=t[1],s=t.index;if(a+=e.slice(o,s),o=s+p.length,i)a+=i[1];else{var c=e[o],u=t[2],l=t[3],f=t[4],g=t[5],x=t[6],h=t[7];a&&(r.push(a),a="");var d=null!=u&&null!=c&&c!==u,y="+"===x||"*"===x,m="?"===x||"*"===x,R=t[2]||"/",T=f||g||(h?".*":"[^"+R+"]+?");r.push({name:l||n++,prefix:u||"",delimiter:R,optional:m,repeat:y,partial:d,asterisk:!!h,pattern:escapeGroup(T)})}}return o=46||"Chrome"===r&&n>=50)||(Cache.prototype.addAll=function(t){function e(t){this.name="NetworkError",this.code=19,this.message=t}var r=this;return e.prototype=Object.create(Error.prototype),Promise.resolve().then(function(){if(arguments.length<1)throw new TypeError;return t=t.map(function(t){return t instanceof Request?t:String(t)}),Promise.all(t.map(function(t){"string"==typeof t&&(t=new Request(t));var r=new URL(t.url).protocol;if("http:"!==r&&"https:"!==r)throw new e("Invalid scheme");return fetch(t.clone())}))}).then(function(n){if(n.some(function(t){return!t.ok}))throw new e("Incorrect response status");return Promise.all(n.map(function(e,n){return r.put(t[n],e)}))}).then(function(){})},Cache.prototype.add=function(t){return this.addAll([t])})}(); -},{}]},{},[12])(12) -}); - - -//# sourceMappingURL=./build/sw-toolbox.map.json \ No newline at end of file diff --git a/lib/sw-toolbox/docs/tutorial-api.html b/lib/sw-toolbox/docs/tutorial-api.html deleted file mode 100644 index 17344591..00000000 --- a/lib/sw-toolbox/docs/tutorial-api.html +++ /dev/null @@ -1,100 +0,0 @@ - - - - - JSDoc: Tutorial: API - - - - - - - - - - -
    - -

    Tutorial: API

    - -
    - -
    - - -

    API

    -
    - -
    -

    Options

    All options can be specified globally via properties of toolbox.options. -Any individual options can be configured on a per-handler basis, via the Object passed as the -third parameter to toolbox.router methods.

    -

    debug [Boolean]

    Determines whether extra information is logged to the browser's console.

    -

    Default: false

    -

    networkTimeoutSeconds [Number]

    A timeout that applies to the toolbox.networkFirst built-in handler. -If networkTimeoutSeconds is set, then any network requests that take longer than that amount of time -will automatically fall back to the cached response if one exists. When -networkTimeoutSeconds is not set, the browser's native networking timeout logic applies.

    -

    Default: null

    -

    cache [Object]

    Various properties of cache control the behavior of the default cache when set via -toolbox.options.cache, or the cache used by a specific request handler.

    -

    cache.name [String]

    The name of the Cache -used to store Response objects. Using a unique name -allows you to customize the cache's maximum size and age of entries.

    -

    Default: Generated at runtime based on the service worker's registration.scope value.

    -

    cache.maxEntries [Number]

    Imposes a least-recently used cache expiration policy -on entries cached via the various built-in handlers. You can use this with a cache that's dedicated -to storing entries for a dynamic set of resources with no natural limit. Setting cache.maxEntries to, e.g., -10 would mean that after the 11th entry is cached, the least-recently used entry would be -automatically deleted. The cache should never end up growing beyond cache.maxEntries entries. -This option will only take effect if cache.name is also set. -It can be used alone or in conjunction with cache.maxAgeSeconds.

    -

    Default: null

    -

    cache.maxAgeSeconds [Number]

    Imposes a maximum age for cache entries, in seconds. -You can use this with a cache that's dedicated to storing entries for a dynamic set of resources -with no natural limit. Setting cache.maxAgeSeconds to, e.g., 60 * 60 * 24 would mean that any -entries older than a day would automatically be deleted. -This option will only take effect if cache.name is also set. -It can be used alone or in conjunction with cache.maxEntries.

    -

    Default: null

    -

    Handlers

    There are five built-in handlers to cover the most common network strategies. For more information about offline strategies see the Offline Cookbook.

    -

    toolbox.networkFirst

    Try to handle the request by fetching from the network. If it succeeds, store the response in the cache. Otherwise, try to fulfill the request from the cache. This is the strategy to use for basic read-through caching. It's also good for API requests where you always want the freshest data when it is available but would rather have stale data than no data.

    -

    toolbox.cacheFirst

    If the request matches a cache entry, respond with that. Otherwise try to fetch the resource from the network. If the network request succeeds, update the cache. This option is good for resources that don't change, or have some other update mechanism.

    -

    toolbox.fastest

    Request the resource from both the cache and the network in parallel. Respond with whichever returns first. Usually this will be the cached version, if there is one. On the one hand this strategy will always make a network request, even if the resource is cached. On the other hand, if/when the network request completes the cache is updated, so that future cache reads will be more up-to-date.

    -

    toolbox.cacheOnly

    Resolve the request from the cache, or fail. This option is good for when you need to guarantee that no network request will be made, for example saving battery on mobile.

    -

    toolbox.networkOnly

    Handle the request by trying to fetch the URL from the network. If the fetch fails, fail the request. Essentially the same as not creating a route for the URL at all.

    -

    Methods

    - -

    toolbox.router.get(urlPattern, handler, options)

    toolbox.router.post(urlPattern, handler, options)

    toolbox.router.put(urlPattern, handler, options)

    toolbox.router.delete(urlPattern, handler, options)

    toolbox.router.head(urlPattern, handler, options)

    Create a route that causes requests for URLs matching urlPattern to be resolved by calling handler. Matches requests using the GET, POST, PUT, DELETE or HEAD HTTP methods respectively.

    -
      -
    • urlPattern - an Express style route. See the docs for the path-to-regexp module for the full syntax
    • -
    • handler - a request handler, as described above
    • -
    • options - an object containing options for the route. This options object will be passed to the request handler. The origin option is specific to the router methods, and can be either an exact string or a Regexp against which the origin of the Request must match for the route to be used.
    • -
    -

    toolbox.router.any(urlPattern, handler, options)

    Like toolbox.router.get, etc., but matches any HTTP method.

    -

    toolbox.router.default

    Takes a function to use as the request handler for any GET request that does not match a route.

    -

    toolbox.precache(arrayOfURLs)

    Add each URL in arrayOfURLs to the list of resources that should be cached during the service worker install step. Note that this needs to be called before the install event is triggered, so you should do it on the first run of your script.

    -

    toolbox.cache(url, options)

    Causes the resource at url to be added to the cache and returns a Promise that resolves with void. The options parameter supports the debug and cache global options.

    -

    toolbox.uncache(url, options)

    Causes the resource at url to be removed from the cache and returns a Promise that resolves to true if the cache entry is deleted. The options parameter supports the debug and cache global options.

    -
    - -
    - -
    - - - -
    - -
    - Documentation generated by JSDoc 3.4.0 on Thu Jun 09 2016 13:34:34 GMT+0100 (BST) -
    - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/tutorial-recipes.html b/lib/sw-toolbox/docs/tutorial-recipes.html deleted file mode 100644 index 0ea6f1ec..00000000 --- a/lib/sw-toolbox/docs/tutorial-recipes.html +++ /dev/null @@ -1,60 +0,0 @@ - - - - - JSDoc: Tutorial: Service Worker Toolbox Recipes - - - - - - - - - - -
    - -

    Tutorial: Service Worker Toolbox Recipes

    - -
    - -
    - - -

    Service Worker Toolbox Recipes

    -
    - -
    -
      -
    • -

      Cache Expiration

      -

      - Demonstrates using the maxEntries and maxAgeSeconds options - to limit the number and age of entries stored in a cache dedicated to images fetched - from an API. -

      -
    • -
    -
    - -
    - -
    - - - -
    - -
    - Documentation generated by JSDoc 3.4.0 on Thu Jun 09 2016 13:34:34 GMT+0100 (BST) -
    - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/tutorial-usage.html b/lib/sw-toolbox/docs/tutorial-usage.html deleted file mode 100644 index 2b39fbef..00000000 --- a/lib/sw-toolbox/docs/tutorial-usage.html +++ /dev/null @@ -1,125 +0,0 @@ - - - - - JSDoc: Tutorial: Usage - - - - - - - - - - -
    - -

    Tutorial: Usage

    - -
    - -
    - - -

    Usage

    -
    - -
    -

    Basic Routes

    A route is a URL pattern and request method associated with a handler. -It defines the behaviour for a section of the site. -Routing is the process of matching an incoming request with the most -appropriate route. To define a route you call the appropriate method on -toolbox.router.

    -

    For example, to send GET requests for the URL '/myapp/index.html' to the -built-in toolbox.networkFirst handler, you would write the following in your -service worker file:

    -

    toolbox.router.get('/myapp/index.html', toolbox.networkFirst);

    -

    If you don't need wildcards in your route, and your route applies to the same -domain as your main site, then you can use a string like '/myapp/index.html'. -However, if you need wildcards (e.g. match any URL that begins with -/myapp/), or if you need to match URLs that belong to different domains (e.g. -match https://othersite.com/api/), sw-toolbox has two options for -configuring your routes.

    -

    Express-style Routes

    For developers familiar with Express routing, -sw-toolbox offers support for similar named wildcards, via the -path-to-regexp library.

    -

    If you use a String to define your route, it's assumed you're using -Express-style routes.

    -

    By default, a route will only match URLs on the same origin as the service -worker. If you'd like your Express-style routes to match URLs on different -origins, you need to pass in a value for the origin option. The value could be -either a String (which is checked for an exact match) or a RegExp object. -In both cases, it's matched against the full origin of the URL -(e.g. 'https://example.com').

    -

    Some examples of using Express-style routing include:

    -
    // URL patterns are the same syntax as Express routes
    -// (http://expressjs.com/guide/routing.html)
    -toolbox.router.get(':foo/index.html', function(request, values) {
    -  return new Response('Handled a request for ' + request.url +
    -      ', where foo is "' + values.foo + '"');
    -});
    -
    -// For requests to other origins, specify the origin as an option
    -toolbox.router.post('/(.*)', apiHandler, {origin: 'https://api.example.com'});

    Regular Expression Routes

    Developers who are more comfortable using regular expressions -can use an alternative syntax to define routes, passing in a RegExp -object as the first parameter. This RegExp will be matched against the full -request URL when determining whether the route applies, including the origin and -path. This can lead to simpler cross-origin routing vs. Express-style routes, -since both the origin and the path are matched simultaneously, without having -to specify a separate origin option.

    -

    Note that while Express-style routes allow you to name path fragment -parameters that will be passed to your handler (see values.foo in the previous -example), that functionality is not supported while using regular expression -routes.

    -

    Some examples of using Regular Expression routing include:

    -
    // Match URLs that end in index.html
    -toolbox.router.get(/index.html$/, function(request) {
    -  return new Response('Handled a request for ' + request.url);
    -});
    -
    -// Match URLs that begin with https://api.example.com
    -toolbox.router.post(/^https://api.example.com\//, apiHandler);

    The Default Route

    sw-toolbox supports defining an optional "default" route via -toolbox.router.default that is used whenever there is no alternative route for -a given URL. If toolbox.router.default is not set, then sw-toolbox will -just ignore requests for URLs that don't match any alternative routes, and the -requests will potentially be handled by the browser as if there were no -service worker involvement.

    -
    // Provide a default handler for GET requests
    -toolbox.router.default = myDefaultRequestHandler;

    Precaching

    You can provide a list of resources which will be cached at service worker install time

    -
    toolbox.precache(['/index.html', '/site.css', '/images/logo.png']);

    Defining Request Handlers

    A request handler takes three arguments.

    -
    var myHandler = function(request, values, options) {
    -  // ...
    -}
      -
    • request - The Request object that triggered the fetch event
    • -
    • values - When using Express-style routing paths, this will be an object -whose keys are the placeholder names in the URL pattern, with the values being -the corresponding part of the request URL. For example, with a URL pattern of -'/images/:size/:name.jpg' and an actual URL of '/images/large/unicorns.jpg', -values would be {size: 'large', name: 'unicorns'}. -When using a RegExp for the path, values will not be set.
    • -
    • options - the options passed to one of the router methods.
    • -
    -

    The return value should be a Response, or a Promise that resolves with a Response. If another value is returned, or if the returned Promise is rejected, the Request will fail which will appear to be a NetworkError to the page that made the request.

    -
    - -
    - -
    - - - -
    - -
    - Documentation generated by JSDoc 3.4.0 on Thu Jun 09 2016 13:34:34 GMT+0100 (BST) -
    - - - - - \ No newline at end of file diff --git a/lib/sw-toolbox/docs/usage.md b/lib/sw-toolbox/docs/usage.md new file mode 100644 index 00000000..f268c754 --- /dev/null +++ b/lib/sw-toolbox/docs/usage.md @@ -0,0 +1,125 @@ +--- +layout: index +title: "Usage" +navigation_weight: 2 +--- + +## Basic Routes + +A _route_ is a URL pattern and request method associated with a handler. +It defines the behaviour for a section of the site. +_Routing_ is the process of matching an incoming request with the most +appropriate route. To define a route you call the appropriate method on +`toolbox.router`. + +For example, to send `GET` requests for the URL `'/myapp/index.html'` to the +built-in `toolbox.networkFirst` handler, you would write the following in your +service worker file: + +`toolbox.router.get('/myapp/index.html', toolbox.networkFirst);` + +If you don't need wildcards in your route, and your route applies to the same +domain as your main site, then you can use a string like `'/myapp/index.html'`. +However, if you need wildcards (e.g. match _any_ URL that begins with +`/myapp/`), or if you need to match URLs that belong to different domains (e.g. +match `https://othersite.com/api/`), `sw-toolbox` has two options for +configuring your routes. + +## Express-style Routes + +For developers familiar with [Express routing](http://expressjs.com/en/guide/routing.html), +`sw-toolbox` offers support for similar named wildcards, via the +[`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) library. + +If you use a `String` to define your route, it's assumed you're using +Express-style routes. + +By default, a route will only match URLs on the same origin as the service +worker. If you'd like your Express-style routes to match URLs on different +origins, you need to pass in a value for the `origin` option. The value could be +either a `String` (which is checked for an exact match) or a `RegExp` object. +In both cases, it's matched against the full origin of the URL +(e.g. `'https://example.com'`). + +Some examples of using Express-style routing include: + +```javascript +// URL patterns are the same syntax as Express routes +// (http://expressjs.com/guide/routing.html) +toolbox.router.get(':foo/index.html', function(request, values) { + return new Response('Handled a request for ' + request.url + + ', where foo is "' + values.foo + '"'); +}); + +// For requests to other origins, specify the origin as an option +toolbox.router.post('/(.*)', apiHandler, {origin: 'https://api.example.com'}); +``` + +## Regular Expression Routes + +Developers who are more comfortable using [regular expressions](https://regex101.com/) +can use an alternative syntax to define routes, passing in a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) +object as the first parameter. This `RegExp` will be matched against the full +request URL when determining whether the route applies, including the origin and +path. This can lead to simpler cross-origin routing vs. Express-style routes, +since both the origin and the path are matched simultaneously, without having +to specify a separate `origin` option. + +Note that while Express-style routes allow you to name path fragment +parameters that will be passed to your handler (see `values.foo` in the previous +example), that functionality is not supported while using regular expression +routes. + +Some examples of using Regular Expression routing include: + +```javascript +// Match URLs that end in index.html +toolbox.router.get(/index.html$/, function(request) { + return new Response('Handled a request for ' + request.url); +}); + +// Match URLs that begin with https://api.example.com +toolbox.router.post(/^https:\/\/api.example.com\//, apiHandler); +``` + +## The Default Route + +`sw-toolbox` supports defining an optional "default" route via +`toolbox.router.default` that is used whenever there is no alternative route for +a given URL. If `toolbox.router.default` is not set, then `sw-toolbox` will +just ignore requests for URLs that don't match any alternative routes, and the +requests will potentially be handled by the browser as if there were no +service worker involvement. + +```javascript +// Provide a default handler for GET requests +toolbox.router.default = myDefaultRequestHandler; +``` + +## Precaching + +You can provide a list of resources which will be cached at service worker install time + +```javascript +toolbox.precache(['/index.html', '/site.css', '/images/logo.png']); +``` + +## Defining Request Handlers +A request handler takes three arguments. + +```javascript +var myHandler = function(request, values, options) { + // ... +} +``` + +- `request` - The [Request](https://fetch.spec.whatwg.org/#request) object that triggered the `fetch` event +- `values` - When using Express-style routing paths, this will be an object +whose keys are the placeholder names in the URL pattern, with the values being +the corresponding part of the request URL. For example, with a URL pattern of +`'/images/:size/:name.jpg'` and an actual URL of `'/images/large/unicorns.jpg'`, +`values` would be `{size: 'large', name: 'unicorns'}`. +When using a RegExp for the path, `values` will not be set. +- `options` - the [options](#options) passed to one of the [router methods](#methods). + +The return value should be a [Response](https://fetch.spec.whatwg.org/#response), or a [Promise](http://www.html5rocks.com/en/tutorials/es6/promises/) that resolves with a Response. If another value is returned, or if the returned Promise is rejected, the Request will fail which will appear to be a [NetworkError](https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-NetworkError) to the page that made the request. diff --git a/lib/sw-toolbox/package.json b/lib/sw-toolbox/package.json index 8944e741..f2ea611f 100644 --- a/lib/sw-toolbox/package.json +++ b/lib/sw-toolbox/package.json @@ -1,12 +1,14 @@ { "name": "sw-toolbox", - "version": "3.2.1", + "version": "3.3.0", + "description": "Service Worker Toolbox provides some simple helpers for use in creating your own service workers.", "license": "Apache-2.0", "scripts": { - "publish-release": "./node_modules/sw-testing-helpers/project/publish-release.sh", + "publish-release": "publish-release.sh", + "publish-docs": "publish-docs.sh", "build": "gulp default", - "build-docs": "jsdoc -c jsdoc.json && cp ./build/sw-toolbox.js ./docs/", - "test": "gulp lint && gulp test:automated", + "build-docs": "echo No Reference Docs to Build.", + "test": "gulp lint default && node ./test/helpers/download-browsers.js && mocha", "bundle": "./project/create-release-bundle.sh" }, "main": "lib/sw-toolbox.js", @@ -19,22 +21,25 @@ "browserify": "^12.0.1", "browserify-header": "^0.9.2", "chai": "^3.4.1", - "chromedriver": "^2.20.0", + "chromedriver": "^2.24.1", "cookie-parser": "^1.4.1", "eslint": "^1.10.3", "eslint-config-google": "^0.3.0", "express": "^4.13.3", + "geckodriver": "^1.1.2", "gulp": "^3.9.0", "gulp-eslint": "^1.1.1", "gulp-gh-pages": "^0.5.4", - "gulp-mocha": "^2.2.0", "jsdoc": "^3.4.0", "jshint-stylish": "^2.1.0", "minifyify": "^7.1.0", "mocha": "^2.3.4", + "npm-publish-scripts": "^2.0.7", + "operadriver": "^0.2.2", "qunitjs": "^1.20.0", - "selenium-webdriver": "^2.48.2", - "sw-testing-helpers": "0.0.14", + "selenium-assistant": "^1.0.0", + "selenium-webdriver": "^3.0.0-beta-2", + "sw-testing-helpers": "0.1.4", "temp": "^0.8.3", "vinyl-source-stream": "^1.1.0", "which": "^1.2.4" diff --git a/lib/sw-toolbox/sw-toolbox.js b/lib/sw-toolbox/sw-toolbox.js index 528e708d..98302e4f 100644 --- a/lib/sw-toolbox/sw-toolbox.js +++ b/lib/sw-toolbox/sw-toolbox.js @@ -15,16 +15,16 @@ */ (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.toolbox = 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;or.value[TIMESTAMP_PROPERTY]){var t=r.value[URL_PROPERTY];u.push(t),s["delete"](t),r["continue"]()}},c.oncomplete=function(){t(u)},c.onabort=o}):Promise.resolve([])}function expireExtraEntries(e,r){return r?new Promise(function(n,t){var o=[],i=e.transaction(STORE_NAME,"readwrite"),u=i.objectStore(STORE_NAME),c=u.index(TIMESTAMP_PROPERTY),s=c.count();c.count().onsuccess=function(){var e=s.result;e>r&&(c.openCursor().onsuccess=function(n){var t=n.target.result;if(t){var i=t.value[URL_PROPERTY];o.push(i),u["delete"](i),e-o.length>r&&t["continue"]()}})},i.oncomplete=function(){n(o)},i.onabort=t}):Promise.resolve([])}function expireEntries(e,r,n,t){return expireOldEntries(e,n,t).then(function(n){return expireExtraEntries(e,r).then(function(e){return n.concat(e)})})}var DB_PREFIX="sw-toolbox-",DB_VERSION=1,STORE_NAME="store",URL_PROPERTY="url",TIMESTAMP_PROPERTY="timestamp",cacheNameToDbPromise={};module.exports={getDb:getDb,setTimestampForUrl:setTimestampForUrl,expireEntries:expireEntries}; +"use strict";function openDb(e){return new Promise(function(r,n){var t=indexedDB.open(DB_PREFIX+e,DB_VERSION);t.onupgradeneeded=function(){var e=t.result.createObjectStore(STORE_NAME,{keyPath:URL_PROPERTY});e.createIndex(TIMESTAMP_PROPERTY,TIMESTAMP_PROPERTY,{unique:!1})},t.onsuccess=function(){r(t.result)},t.onerror=function(){n(t.error)}})}function getDb(e){return e in cacheNameToDbPromise||(cacheNameToDbPromise[e]=openDb(e)),cacheNameToDbPromise[e]}function setTimestampForUrl(e,r,n){return new Promise(function(t,o){var i=e.transaction(STORE_NAME,"readwrite"),u=i.objectStore(STORE_NAME);u.put({url:r,timestamp:n}),i.oncomplete=function(){t(e)},i.onabort=function(){o(i.error)}})}function expireOldEntries(e,r,n){return r?new Promise(function(t,o){var i=1e3*r,u=[],c=e.transaction(STORE_NAME,"readwrite"),s=c.objectStore(STORE_NAME),a=s.index(TIMESTAMP_PROPERTY);a.openCursor().onsuccess=function(e){var r=e.target.result;if(r&&n-i>r.value[TIMESTAMP_PROPERTY]){var t=r.value[URL_PROPERTY];u.push(t),s.delete(t),r.continue()}},c.oncomplete=function(){t(u)},c.onabort=o}):Promise.resolve([])}function expireExtraEntries(e,r){return r?new Promise(function(n,t){var o=[],i=e.transaction(STORE_NAME,"readwrite"),u=i.objectStore(STORE_NAME),c=u.index(TIMESTAMP_PROPERTY),s=c.count();c.count().onsuccess=function(){var e=s.result;e>r&&(c.openCursor().onsuccess=function(n){var t=n.target.result;if(t){var i=t.value[URL_PROPERTY];o.push(i),u.delete(i),e-o.length>r&&t.continue()}})},i.oncomplete=function(){n(o)},i.onabort=t}):Promise.resolve([])}function expireEntries(e,r,n,t){return expireOldEntries(e,n,t).then(function(n){return expireExtraEntries(e,r).then(function(e){return n.concat(e)})})}var DB_PREFIX="sw-toolbox-",DB_VERSION=1,STORE_NAME="store",URL_PROPERTY="url",TIMESTAMP_PROPERTY="timestamp",cacheNameToDbPromise={};module.exports={getDb:getDb,setTimestampForUrl:setTimestampForUrl,expireEntries:expireEntries}; },{}],3:[function(require,module,exports){ "use strict";var scope;scope=self.registration?self.registration.scope:self.scope||new URL("./",self.location).href,module.exports={cache:{name:"$$$toolbox-cache$$$"+scope+"$$$",maxAgeSeconds:null,maxEntries:null},debug:!1,networkTimeoutSeconds:null,preCacheItems:[],successResponses:/^0|([123]\d\d)|(40[14567])|410$/}; },{}],4:[function(require,module,exports){ "use strict";var url=new URL("./",self.location),basePath=url.pathname,pathRegexp=require("path-to-regexp"),Route=function(e,t,i,s){t instanceof RegExp?this.fullUrlRegExp=t:(0!==t.indexOf("/")&&(t=basePath+t),this.keys=[],this.regexp=pathRegexp(t,this.keys)),this.method=e,this.options=s,this.handler=i};Route.prototype.makeHandler=function(e){var t;if(this.regexp){var i=this.regexp.exec(e);t={},this.keys.forEach(function(e,s){t[e.name]=i[s+1]})}return function(e){return this.handler(e,t,this.options)}.bind(this)},module.exports=Route; },{"path-to-regexp":14}],5:[function(require,module,exports){ -"use strict";function regexEscape(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var Route=require("./route"),keyMatch=function(e,t){for(var r=e.entries(),o=r.next(),n=[];!o.done;){var u=new RegExp(o.value[0]);u.test(t)&&n.push(o.value[1]),o=r.next()}return n},Router=function(){this.routes=new Map,this.routes.set(RegExp,new Map),this["default"]=null};["get","post","put","delete","head","any"].forEach(function(e){Router.prototype[e]=function(t,r,o){return this.add(e,t,r,o)}}),Router.prototype.add=function(e,t,r,o){o=o||{};var n;t instanceof RegExp?n=RegExp:(n=o.origin||self.location.origin,n=n instanceof RegExp?n.source:regexEscape(n)),e=e.toLowerCase();var u=new Route(e,t,r,o);this.routes.has(n)||this.routes.set(n,new Map);var a=this.routes.get(n);a.has(e)||a.set(e,new Map);var s=a.get(e),i=u.regexp||u.fullUrlRegExp;s.set(i.source,u)},Router.prototype.matchMethod=function(e,t){var r=new URL(t),o=r.origin,n=r.pathname;return this._match(e,keyMatch(this.routes,o),n)||this._match(e,[this.routes.get(RegExp)],t)},Router.prototype._match=function(e,t,r){if(0===t.length)return null;for(var o=0;o0)return a[0].makeHandler(r)}}return null},Router.prototype.match=function(e){return this.matchMethod(e.method,e.url)||this.matchMethod("any",e.url)},module.exports=new Router; -},{"./route":4}],6:[function(require,module,exports){ +"use strict";function regexEscape(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var Route=require("./route"),helpers=require("./helpers"),keyMatch=function(e,t){for(var r=e.entries(),o=r.next(),n=[];!o.done;){var u=new RegExp(o.value[0]);u.test(t)&&n.push(o.value[1]),o=r.next()}return n},Router=function(){this.routes=new Map,this.routes.set(RegExp,new Map),this.default=null};["get","post","put","delete","head","any"].forEach(function(e){Router.prototype[e]=function(t,r,o){return this.add(e,t,r,o)}}),Router.prototype.add=function(e,t,r,o){o=o||{};var n;t instanceof RegExp?n=RegExp:(n=o.origin||self.location.origin,n=n instanceof RegExp?n.source:regexEscape(n)),e=e.toLowerCase();var u=new Route(e,t,r,o);this.routes.has(n)||this.routes.set(n,new Map);var s=this.routes.get(n);s.has(e)||s.set(e,new Map);var a=s.get(e),h=u.regexp||u.fullUrlRegExp;a.has(h.source)&&helpers.debug('"'+t+'" resolves to same regex as existing route.'),a.set(h.source,u)},Router.prototype.matchMethod=function(e,t){var r=new URL(t),o=r.origin,n=r.pathname;return this._match(e,keyMatch(this.routes,o),n)||this._match(e,[this.routes.get(RegExp)],t)},Router.prototype._match=function(e,t,r){if(0===t.length)return null;for(var o=0;o0)return s[0].makeHandler(r)}}return null},Router.prototype.match=function(e){return this.matchMethod(e.method,e.url)||this.matchMethod("any",e.url)},module.exports=new Router; +},{"./helpers":1,"./route":4}],6:[function(require,module,exports){ "use strict";function cacheFirst(e,r,t){return helpers.debug("Strategy: cache first ["+e.url+"]",t),helpers.openCache(t).then(function(r){return r.match(e).then(function(r){return r?r:helpers.fetchAndCache(e,t)})})}var helpers=require("../helpers");module.exports=cacheFirst; },{"../helpers":1}],7:[function(require,module,exports){ "use strict";function cacheOnly(e,r,c){return helpers.debug("Strategy: cache only ["+e.url+"]",c),helpers.openCache(c).then(function(r){return r.match(e)})}var helpers=require("../helpers");module.exports=cacheOnly; @@ -33,15 +33,15 @@ },{"../helpers":1,"./cacheOnly":7}],9:[function(require,module,exports){ module.exports={networkOnly:require("./networkOnly"),networkFirst:require("./networkFirst"),cacheOnly:require("./cacheOnly"),cacheFirst:require("./cacheFirst"),fastest:require("./fastest")}; },{"./cacheFirst":6,"./cacheOnly":7,"./fastest":8,"./networkFirst":10,"./networkOnly":11}],10:[function(require,module,exports){ -"use strict";function networkFirst(e,r,t){t=t||{};var s=t.successResponses||globalOptions.successResponses,n=t.networkTimeoutSeconds||globalOptions.networkTimeoutSeconds;return helpers.debug("Strategy: network first ["+e.url+"]",t),helpers.openCache(t).then(function(r){var o,u,i=[];if(n){var c=new Promise(function(t){o=setTimeout(function(){r.match(e).then(function(e){e&&t(e)})},1e3*n)});i.push(c)}var a=helpers.fetchAndCache(e,t).then(function(e){if(o&&clearTimeout(o),s.test(e.status))return e;throw helpers.debug("Response was an HTTP error: "+e.statusText,t),u=e,new Error("Bad response")})["catch"](function(s){return helpers.debug("Network or response error, fallback to cache ["+e.url+"]",t),r.match(e).then(function(e){if(e)return e;if(u)return u;throw s})});return i.push(a),Promise.race(i)})}var globalOptions=require("../options"),helpers=require("../helpers");module.exports=networkFirst; +"use strict";function networkFirst(e,r,t){t=t||{};var s=t.successResponses||globalOptions.successResponses,n=t.networkTimeoutSeconds||globalOptions.networkTimeoutSeconds;return helpers.debug("Strategy: network first ["+e.url+"]",t),helpers.openCache(t).then(function(r){var o,u,i=[];if(n){var c=new Promise(function(t){o=setTimeout(function(){r.match(e).then(function(e){e&&t(e)})},1e3*n)});i.push(c)}var a=helpers.fetchAndCache(e,t).then(function(e){if(o&&clearTimeout(o),s.test(e.status))return e;throw helpers.debug("Response was an HTTP error: "+e.statusText,t),u=e,new Error("Bad response")}).catch(function(s){return helpers.debug("Network or response error, fallback to cache ["+e.url+"]",t),r.match(e).then(function(e){if(e)return e;if(u)return u;throw s})});return i.push(a),Promise.race(i)})}var globalOptions=require("../options"),helpers=require("../helpers");module.exports=networkFirst; },{"../helpers":1,"../options":3}],11:[function(require,module,exports){ "use strict";function networkOnly(e,r,t){return helpers.debug("Strategy: network only ["+e.url+"]",t),fetch(e)}var helpers=require("../helpers");module.exports=networkOnly; },{"../helpers":1}],12:[function(require,module,exports){ -"use strict";function cache(e,t){return helpers.openCache(t).then(function(t){return t.add(e)})}function uncache(e,t){return helpers.openCache(t).then(function(t){return t["delete"](e)})}function precache(e){e instanceof Promise||validatePrecacheInput(e),options.preCacheItems=options.preCacheItems.concat(e)}require("serviceworker-cache-polyfill");var options=require("./options"),router=require("./router"),helpers=require("./helpers"),strategies=require("./strategies");helpers.debug("Service Worker Toolbox is loading");var flatten=function(e){return e.reduce(function(e,t){return e.concat(t)},[])},validatePrecacheInput=function(e){var t=Array.isArray(e);if(t&&e.forEach(function(e){"string"==typeof e||e instanceof Request||(t=!1)}),!t)throw new TypeError("The precache method expects either an array of strings and/or Requests or a Promise that resolves to an array of strings and/or Requests.");return e};self.addEventListener("install",function(e){var t=options.cache.name+"$$$inactive$$$";helpers.debug("install event fired"),helpers.debug("creating cache ["+t+"]"),e.waitUntil(helpers.openCache({cache:{name:t}}).then(function(e){return Promise.all(options.preCacheItems).then(flatten).then(validatePrecacheInput).then(function(t){return helpers.debug("preCache list: "+(t.join(", ")||"(none)")),e.addAll(t)})}))}),self.addEventListener("activate",function(e){helpers.debug("activate event fired");var t=options.cache.name+"$$$inactive$$$";e.waitUntil(helpers.renameCache(t,options.cache.name))}),self.addEventListener("fetch",function(e){var t=router.match(e.request);t?e.respondWith(t(e.request)):router["default"]&&"GET"===e.request.method&&e.respondWith(router["default"](e.request))}),module.exports={networkOnly:strategies.networkOnly,networkFirst:strategies.networkFirst,cacheOnly:strategies.cacheOnly,cacheFirst:strategies.cacheFirst,fastest:strategies.fastest,router:router,options:options,cache:cache,uncache:uncache,precache:precache}; +"use strict";function cache(e,t){return helpers.openCache(t).then(function(t){return t.add(e)})}function uncache(e,t){return helpers.openCache(t).then(function(t){return t.delete(e)})}function precache(e){e instanceof Promise||validatePrecacheInput(e),options.preCacheItems=options.preCacheItems.concat(e)}require("serviceworker-cache-polyfill");var options=require("./options"),router=require("./router"),helpers=require("./helpers"),strategies=require("./strategies");helpers.debug("Service Worker Toolbox is loading");var flatten=function(e){return e.reduce(function(e,t){return e.concat(t)},[])},validatePrecacheInput=function(e){var t=Array.isArray(e);if(t&&e.forEach(function(e){"string"==typeof e||e instanceof Request||(t=!1)}),!t)throw new TypeError("The precache method expects either an array of strings and/or Requests or a Promise that resolves to an array of strings and/or Requests.");return e};self.addEventListener("install",function(e){var t=options.cache.name+"$$$inactive$$$";helpers.debug("install event fired"),helpers.debug("creating cache ["+t+"]"),e.waitUntil(helpers.openCache({cache:{name:t}}).then(function(e){return Promise.all(options.preCacheItems).then(flatten).then(validatePrecacheInput).then(function(t){return helpers.debug("preCache list: "+(t.join(", ")||"(none)")),e.addAll(t)})}))}),self.addEventListener("activate",function(e){helpers.debug("activate event fired");var t=options.cache.name+"$$$inactive$$$";e.waitUntil(helpers.renameCache(t,options.cache.name))}),self.addEventListener("fetch",function(e){var t=router.match(e.request);t?e.respondWith(t(e.request)):router.default&&"GET"===e.request.method&&e.respondWith(router.default(e.request))}),module.exports={networkOnly:strategies.networkOnly,networkFirst:strategies.networkFirst,cacheOnly:strategies.cacheOnly,cacheFirst:strategies.cacheFirst,fastest:strategies.fastest,router:router,options:options,cache:cache,uncache:uncache,precache:precache}; },{"./helpers":1,"./options":3,"./router":5,"./strategies":9,"serviceworker-cache-polyfill":15}],13:[function(require,module,exports){ module.exports=Array.isArray||function(r){return"[object Array]"==Object.prototype.toString.call(r)}; },{}],14:[function(require,module,exports){ -function parse(e){for(var t,r=[],n=0,o=0,a="";null!=(t=PATH_REGEXP.exec(e));){var p=t[0],i=t[1],s=t.index;if(a+=e.slice(o,s),o=s+p.length,i)a+=i[1];else{var c=e[o],u=t[2],l=t[3],f=t[4],g=t[5],x=t[6],h=t[7];a&&(r.push(a),a="");var d=null!=u&&null!=c&&c!==u,y="+"===x||"*"===x,m="?"===x||"*"===x,R=t[2]||"/",T=f||g||(h?".*":"[^"+R+"]+?");r.push({name:l||n++,prefix:u||"",delimiter:R,optional:m,repeat:y,partial:d,asterisk:!!h,pattern:escapeGroup(T)})}}return o=46||"Chrome"===r&&n>=50)||(Cache.prototype.addAll=function(t){function e(t){this.name="NetworkError",this.code=19,this.message=t}var r=this;return e.prototype=Object.create(Error.prototype),Promise.resolve().then(function(){if(arguments.length<1)throw new TypeError;return t=t.map(function(t){return t instanceof Request?t:String(t)}),Promise.all(t.map(function(t){"string"==typeof t&&(t=new Request(t));var r=new URL(t.url).protocol;if("http:"!==r&&"https:"!==r)throw new e("Invalid scheme");return fetch(t.clone())}))}).then(function(n){if(n.some(function(t){return!t.ok}))throw new e("Incorrect response status");return Promise.all(n.map(function(e,n){return r.put(t[n],e)}))}).then(function(){})},Cache.prototype.add=function(t){return this.addAll([t])})}(); },{}]},{},[12])(12) diff --git a/lib/sw-toolbox/sw-toolbox.map.json b/lib/sw-toolbox/sw-toolbox.map.json index b6089590..58191476 100644 --- a/lib/sw-toolbox/sw-toolbox.map.json +++ b/lib/sw-toolbox/sw-toolbox.map.json @@ -1 +1 @@ -{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/sw-toolbox.js","lib/options.js","lib/router.js","lib/helpers.js","lib/strategies/index.js","lib/route.js","lib/idb-cache-expiration.js","node_modules/serviceworker-cache-polyfill/index.js","lib/strategies/networkOnly.js","lib/strategies/cacheOnly.js","lib/strategies/networkFirst.js","lib/strategies/cacheFirst.js","lib/strategies/fastest.js","node_modules/path-to-regexp/index.js","node_modules/isarray/index.js"],"names":["cache","url","options","helpers","openCache","then","add","uncache","precache","items","Promise","validatePrecacheInput","preCacheItems","concat","require","router","strategies","debug","flatten","reduce","a","b","isValid","Array","isArray","forEach","item","Request","TypeError","self","addEventListener","event","inactiveCache","name","waitUntil","all","join","addAll","renameCache","handler","match","request","respondWith","method","module","exports","networkOnly","networkFirst","cacheOnly","cacheFirst","fastest","scope","registration","URL","location","href","maxAgeSeconds","maxEntries","networkTimeoutSeconds","successResponses","regexEscape","s","replace","Route","keyMatch","map","string","entriesIterator","entries","next","matches","done","pattern","RegExp","value","test","push","Router","this","routes","Map","set","prototype","path","origin","source","toLowerCase","route","has","methodMap","get","routeMap","regExp","regexp","fullUrlRegExp","matchMethod","urlObject","pathname","_match","methodMaps","pathOrUrl","length","i","makeHandler","message","flag","globalOptions","console","log","cacheName","caches","open","fetchAndCache","fetch","clone","response","status","put","cacheOptions","queueCacheExpiration","cleanup","cleanupCache","bind","cleanupQueue","requestUrl","now","Date","idbCacheExpiration","getDb","db","setTimestampForUrl","expireEntries","urlsToDelete","deletionPromises","urlToDelete","error","destination","results","sourceCache","destCache","keys","requests","basePath","pathRegexp","indexOf","values","exec","key","index","openDb","resolve","reject","indexedDB","DB_PREFIX","DB_VERSION","onupgradeneeded","objectStore","result","createObjectStore","STORE_NAME","keyPath","URL_PROPERTY","createIndex","TIMESTAMP_PROPERTY","unique","onsuccess","onerror","cacheNameToDbPromise","transaction","timestamp","oncomplete","onabort","expireOldEntries","maxAgeMillis","urls","openCursor","cursorEvent","cursor","target","expireExtraEntries","countRequest","count","initialCount","oldUrls","extraUrls","nativeAddAll","Cache","userAgent","navigator","agent","version","parseInt","NetworkError","code","Object","create","Error","arguments","String","scheme","protocol","responses","some","ok","timeoutId","originalResponse","promises","cacheWhenTimedOutPromise","setTimeout","networkPromise","clearTimeout","statusText","race","rejected","reasons","maybeReject","reason","toString","maybeResolve","Response","parse","str","res","tokens","PATH_REGEXP","m","escaped","offset","slice","prefix","capture","group","modifier","asterisk","partial","repeat","optional","delimiter","escapeGroup","substr","compile","tokensToFunction","encodeURIComponentPretty","encodeURI","c","charCodeAt","toUpperCase","encodeAsterisk","obj","opts","data","encode","pretty","encodeURIComponent","token","segment","isarray","JSON","stringify","j","escapeString","attachKeys","re","flags","sensitive","regexpToRegexp","groups","arrayToRegexp","parts","pathToRegexp","stringToRegexp","tokensToRegExp","strict","end","lastToken","endsWithSlash","arr","call"],"mappings":"AAAA;AIeA,YAKA,SAASiB,OAAMuF,EAAStG,GACtBA,EAAUA,KACV,IAAIuG,GAAOvG,EAAQe,OAASyF,cAAczF,KACtCwF,IACFE,QAAQC,IAAI,gBAAkBJ,GAIlC,QAASpG,WAAUF,GACjB,GAAI2G,EAMJ,OALI3G,IAAWA,EAAQF,QACrB6G,EAAY3G,EAAQF,MAAMiC,MAE5B4E,EAAYA,GAAaH,cAAc1G,MAAMiC,KAEtC6E,OAAOC,KAAKF,GAGrB,QAASG,eAAcvE,EAASvC,GAC9BA,EAAUA,KACV,IAAIyD,GAAmBzD,EAAQyD,kBAC3B+C,cAAc/C,gBAElB,OAAOsD,OAAMxE,EAAQyE,SAAS7G,KAAK,SAAS8G,GAwB1C,MAnBuB,QAAnB1E,EAAQE,QAAoBgB,EAAiBgB,KAAKwC,EAASC,SAC7DhH,UAAUF,GAASG,KAAK,SAASL,GAC/BA,EAAMqH,IAAI5E,EAAS0E,GAAU9G,KAAK,WAIhC,GAAIiH,GAAepH,EAAQF,OAAS0G,cAAc1G,OAK7CsH,EAAa7D,YAAc6D,EAAa9D,gBACzC8D,EAAarF,MACfsF,qBAAqB9E,EAASzC,EAAOsH,OAMtCH,EAASD,UAKpB,QAASK,sBAAqB9E,EAASzC,EAAOsH,GAC5C,GAAIE,GAAUC,aAAaC,KAAK,KAAMjF,EAASzC,EAAOsH,EAGpDK,cADEA,aACaA,aAAatH,KAAKmH,GAElBA,IAInB,QAASC,cAAahF,EAASzC,EAAOsH,GACpC,GAAIM,GAAanF,EAAQxC,IACrBuD,EAAgB8D,EAAa9D,cAC7BC,EAAa6D,EAAa7D,WAC1BoD,EAAYS,EAAarF,KAEzB4F,EAAMC,KAAKD,KAIf,OAHA5G,OAAM,0BAA4B2G,EAAa,oBAC7CnE,EAAa,gBAAkBD,GAE1BuE,mBAAmBC,MAAMnB,GAAWxG,KAAK,SAAS4H,GACvD,MAAOF,oBAAmBG,mBAAmBD,EAAIL,EAAYC,KAC5DxH,KAAK,SAAS4H,GACf,MAAOF,oBAAmBI,cAAcF,EAAIxE,EAAYD,EAAeqE,KACtExH,KAAK,SAAS+H,GACfnH,MAAM,4BAEN,IAAIoH,GAAmBD,EAAanE,IAAI,SAASqE,GAC/C,MAAOtI,GAAAA,UAAasI,IAGtB,OAAO5H,SAAQyB,IAAIkG,GAAkBhI,KAAK,WACxCY,MAAM,gCAZH8G,SAcE,SAASQ,GAChBtH,MAAMsH,KAIV,QAASjG,aAAY+C,EAAQmD,EAAatI,GAExC,MADAe,OAAM,oBAAsBoE,EAAS,SAAWmD,EAAc,IAAKtI,GAC5D4G,OAAAA,UAAc0B,GAAanI,KAAK,WACrC,MAAOK,SAAQyB,KACb2E,OAAOC,KAAK1B,GACZyB,OAAOC,KAAKyB,KACXnI,KAAK,SAASoI,GACf,GAAIC,GAAcD,EAAQ,GACtBE,EAAYF,EAAQ,EAExB,OAAOC,GAAYE,OAAOvI,KAAK,SAASwI,GACtC,MAAOnI,SAAQyB,IAAI0G,EAAS5E,IAAI,SAASxB,GACvC,MAAOiG,GAAYlG,MAAMC,GAASpC,KAAK,SAAS8G,GAC9C,MAAOwB,GAAUtB,IAAI5E,EAAS0E,UAGjC9G,KAAK,WACN,MAAOyG,QAAAA,UAAczB,SA/G7B,GAAIqB,eAAgB5F,QAAQ,aACxBiH,mBAAqBjH,QAAQ,0BAqD7B6G,YA+DJ/E,QAAOC,SACL5B,MAAOA,MACP+F,cAAeA,cACf5G,UAAWA,UACXkC,YAAaA;;AG3Hf,YASA,SAAS+G,QAAOxC,GACd,MAAO,IAAInG,SAAQ,SAAS4I,EAASC,GACnC,GAAI9G,GAAU+G,UAAUzC,KAAK0C,UAAY5C,EAAW6C,WAEpDjH,GAAQkH,gBAAkB,WACxB,GAAIC,GAAcnH,EAAQoH,OAAOC,kBAAkBC,YAC9CC,QAASC,cACdL,GAAYM,YAAYC,mBAAoBA,oBACvCC,QAAQ,KAGf3H,EAAQ4H,UAAY,WAClBf,EAAQ7G,EAAQoH,SAGlBpH,EAAQ6H,QAAU,WAChBf,EAAO9G,EAAQ8F,UAKrB,QAASP,OAAMnB,GAKb,MAJMA,KAAa0D,wBACjBA,qBAAqB1D,GAAawC,OAAOxC,IAGpC0D,qBAAqB1D,GAG9B,QAASqB,oBAAmBD,EAAIhI,EAAK4H,GACnC,MAAO,IAAInH,SAAQ,SAAS4I,EAASC,GACnC,GAAIiB,GAAcvC,EAAGuC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,WAC1CH,GAAYvC,KAAKpH,IAAKA,EAAKwK,UAAW5C,IAEtC2C,EAAYE,WAAa,WACvBpB,EAAQrB,IAGVuC,EAAYG,QAAU,WACpBpB,EAAOiB,EAAYjC,UAKzB,QAASqC,kBAAiB3C,EAAIzE,EAAeqE,GAG3C,MAAKrE,GAIE,GAAI9C,SAAQ,SAAS4I,EAASC,GACnC,GAAIsB,GAA+B,IAAhBrH,EACfsH,KAEAN,EAAcvC,EAAGuC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,YACtCX,EAAQQ,EAAYR,MAAMe,mBAE9Bf,GAAM2B,aAAaV,UAAY,SAASW,GACtC,GAAIC,GAASD,EAAYE,OAAOrB,MAChC,IAAIoB,GACEpD,EAAMgD,EAAeI,EAAOvG,MAAMyF,oBAAqB,CACzD,GAAIlK,GAAMgL,EAAOvG,MAAMuF,aACvBa,GAAKlG,KAAK3E,GACV2J,EAAAA,UAAmB3J,GACnBgL,EAAAA,gBAKNT,EAAYE,WAAa,WACvBpB,EAAQwB,IAGVN,EAAYG,QAAUpB,IA3Bf7I,QAAQ4I,YA+BnB,QAAS6B,oBAAmBlD,EAAIxE,GAG9B,MAAKA,GAIE,GAAI/C,SAAQ,SAAS4I,EAASC,GACnC,GAAIuB,MAEAN,EAAcvC,EAAGuC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,YACtCX,EAAQQ,EAAYR,MAAMe,oBAE1BiB,EAAehC,EAAMiC,OACzBjC,GAAMiC,QAAQhB,UAAY,WACxB,GAAIiB,GAAeF,EAAavB,MAE5ByB,GAAe7H,IACjB2F,EAAM2B,aAAaV,UAAY,SAASW,GACtC,GAAIC,GAASD,EAAYE,OAAOrB,MAChC,IAAIoB,EAAQ,CACV,GAAIhL,GAAMgL,EAAOvG,MAAMuF,aACvBa,GAAKlG,KAAK3E,GACV2J,EAAAA,UAAmB3J,GACfqL,EAAeR,EAAKzE,OAAS5C,GAC/BwH,EAAAA,kBAOVT,EAAYE,WAAa,WACvBpB,EAAQwB,IAGVN,EAAYG,QAAUpB,IAjCf7I,QAAQ4I,YAqCnB,QAASnB,eAAcF,EAAIxE,EAAYD,EAAeqE,GACpD,MAAO+C,kBAAiB3C,EAAIzE,EAAeqE,GAAKxH,KAAK,SAASkL,GAC5D,MAAOJ,oBAAmBlD,EAAIxE,GAAYpD,KAAK,SAASmL,GACtD,MAAOD,GAAQ1K,OAAO2K,OAnI5B,GAAI/B,WAAY,cACZC,WAAa,EACbK,WAAa,QACbE,aAAe,MACfE,mBAAqB,YACrBI,uBAmIJ3H,QAAOC,SACLmF,MAAOA,MACPE,mBAAoBA,mBACpBC,cAAeA;;AL7IjB,YAIA,IAAIhF,MAEFA,OADEtB,KAAKuB,aACCvB,KAAKuB,aAAaD,MAElBtB,KAAKsB,OAAS,GAAIE,KAAI,KAAMxB,KAAKyB,UAAUC,KAGrDX,OAAOC,SACL7C,OACEiC,KAAM,sBAAwBkB,MAAQ,MACtCK,cAAe,KACfC,WAAY,MAEdxC,OAAO,EACPyC,sBAAuB,KACvB9C,iBAIA+C,iBAAkB;;AIvBpB,YAGA,IAAI1D,KAAM,GAAIoD,KAAI,KAAMxB,KAAKyB,UACzBwF,SAAW7I,IAAIgG,SACf8C,WAAajI,QAAQ,kBAErBiD,MAAQ,SAASpB,EAAQwC,EAAM5C,EAASrC,GACtCiF,YAAgBV,QAClBK,KAAKgB,cAAgBX,GAOK,IAAtBA,EAAK6D,QAAQ,OACf7D,EAAO2D,SAAW3D,GAGpBL,KAAK8D,QACL9D,KAAKe,OAASkD,WAAW5D,EAAML,KAAK8D,OAGtC9D,KAAKnC,OAASA,EACdmC,KAAK5E,QAAUA,EACf4E,KAAKvC,QAAUA,EAGjBwB,OAAMmB,UAAUqB,YAAc,SAAStG,GACrC,GAAIgJ,EACJ,IAAInE,KAAKe,OAAQ,CACf,GAAIrD,GAAQsC,KAAKe,OAAOqD,KAAKjJ,EAC7BgJ,MACAnE,KAAK8D,KAAKnH,QAAQ,SAAS0H,EAAKC,GAC9BH,EAAOE,EAAIlH,MAAQO,EAAM4G,EAAQ,KAIrC,MAAO,UAAS3G,GACd,MAAOqC,MAAKvC,QAAQE,EAASwG,EAAQnE,KAAK5E,UAC1CwH,KAAK5C,OAGTlC,OAAOC,QAAUkB;;AH5CjB,YAIA,SAASH,aAAYC,GACnB,MAAOA,GAAEC,QAAQ,yBAA0B,QAH7C,GAAIC,OAAQjD,QAAQ,WAMhBkD,SAAW,SAASC,EAAKC,GAM3B,IAHA,GAAIC,GAAkBF,EAAIG,UACtB1C,EAAOyC,EAAgBE,OACvBC,MACI5C,EAAK6C,MAAM,CACjB,GAAIC,GAAU,GAAIC,QAAO/C,EAAKgD,MAAM,GAChCF,GAAQG,KAAKT,IACfI,EAAQM,KAAKlD,EAAKgD,MAAM,IAE1BhD,EAAOyC,EAAgBE,OAEzB,MAAOC,IAGLO,OAAS,WACXC,KAAKC,OAAS,GAAIC,KAElBF,KAAKC,OAAOE,IAAIR,OAAQ,GAAIO,MAC5BF,KAAAA,WAAe,OAGhB,MAAO,OAAQ,MAAO,SAAU,OAAQ,OAAOrD,QAAQ,SAASkB,GAC/DkC,OAAOK,UAAUvC,GAAU,SAASwC,EAAM5C,EAASrC,GACjD,MAAO4E,MAAKxE,IAAIqC,EAAQwC,EAAM5C,EAASrC,MAI3C2E,OAAOK,UAAU5E,IAAM,SAASqC,EAAQwC,EAAM5C,EAASrC,GACrDA,EAAUA,KACV,IAAIkF,EAEAD,aAAgBV,QAIlBW,EAASX,QAETW,EAASlF,EAAQkF,QAAUvD,KAAKyB,SAAS8B,OAEvCA,EADEA,YAAkBX,QACXW,EAAOC,OAEPzB,YAAYwB,IAIzBzC,EAASA,EAAO2C,aAEhB,IAAIC,GAAQ,GAAIxB,OAAMpB,EAAQwC,EAAM5C,EAASrC,EAExC4E,MAAKC,OAAOS,IAAIJ,IACnBN,KAAKC,OAAOE,IAAIG,EAAQ,GAAIJ,KAG9B,IAAIS,GAAYX,KAAKC,OAAOW,IAAIN,EAC3BK,GAAUD,IAAI7C,IACjB8C,EAAUR,IAAItC,EAAQ,GAAIqC,KAG5B,IAAIW,GAAWF,EAAUC,IAAI/C,GACzBiD,EAASL,EAAMM,QAAUN,EAAMO,aACnCH,GAASV,IAAIW,EAAOP,OAAQE,IAG9BV,OAAOK,UAAUa,YAAc,SAASpD,EAAQ1C,GAC9C,GAAI+F,GAAY,GAAI3C,KAAIpD,GACpBmF,EAASY,EAAUZ,OACnBD,EAAOa,EAAUC,QAOrB,OAAOnB,MAAKoB,OAAOvD,EAAQqB,SAASc,KAAKC,OAAQK,GAASD,IACxDL,KAAKoB,OAAOvD,GAASmC,KAAKC,OAAOW,IAAIjB,SAAUxE,IAGnD4E,OAAOK,UAAUgB,OAAS,SAASvD,EAAQwD,EAAYC,GACrD,GAA0B,IAAtBD,EAAWE,OACb,MAAO,KAGT,KAAK,GAAIC,GAAI,EAAGA,EAAIH,EAAWE,OAAQC,IAAK,CAC1C,GAAIb,GAAYU,EAAWG,GACvBX,EAAWF,GAAaA,EAAUC,IAAI/C,EAAO2C,cACjD,IAAIK,EAAU,CACZ,GAAIZ,GAASf,SAAS2B,EAAUS,EAChC,IAAIrB,EAAOsB,OAAS,EAClB,MAAOtB,GAAO,GAAGwB,YAAYH,IAKnC,MAAO,OAGTvB,OAAOK,UAAU1C,MAAQ,SAASC,GAChC,MAAOqC,MAAKiB,YAAYtD,EAAQE,OAAQF,EAAQxC,MAC5C6E,KAAKiB,YAAY,MAAOtD,EAAQxC,MAGtC2C,OAAOC,QAAU,GAAIgC;;AS/GrB,YAGA,SAAS5B,YAAWR,EAASwG,EAAQ/I,GAEnC,MADAC,SAAQc,MAAM,0BAA4BwB,EAAQxC,IAAM,IAAKC,GACtDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMwC,MAAMC,GAASpC,KAAK,SAAS8G,GACxC,MAAIA,GACKA,EAGFhH,QAAQ6G,cAAcvE,EAASvC,OAV5C,GAAIC,SAAUW,QAAQ,aAetB8B,QAAOC,QAAUI;;AFhBjB,YAGA,SAASD,WAAUP,EAASwG,EAAQ/I,GAElC,MADAC,SAAQc,MAAM,yBAA2BwB,EAAQxC,IAAM,IAAKC,GACrDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMwC,MAAMC,KALvB,GAAItC,SAAUW,QAAQ,aAStB8B,QAAOC,QAAUG;;AGVjB,YAIA,SAASE,SAAQT,EAASwG,EAAQ/I,GAGhC,MAFAC,SAAQc,MAAM,sBAAwBwB,EAAQxC,IAAM,IAAKC,GAElD,GAAIQ,SAAQ,SAAS4I,EAASC,GACnC,GAAI8D,IAAW,EACXC,KAEAC,EAAc,SAASC,GACzBF,EAAQ1I,KAAK4I,EAAOC,YAChBJ,EACF9D,EAAO,GAAI6C,OAAM,mCACbkB,EAAQlL,KAAK,QAAU,MAE3BiL,GAAW,GAIXK,EAAe,SAAS7D,GACtBA,YAAkB8D,UACpBrE,EAAQO,GAER0D,EAAY,sBAIhBpN,SAAQ6G,cAAcvE,EAAQyE,QAAShH,GACpCG,KAAKqN,EAAcH,GAEtBvK,UAAUP,EAASwG,EAAQ/I,GACxBG,KAAKqN,EAAcH,KAhC1B,GAAIpN,SAAUW,QAAQ,cAClBkC,UAAYlC,QAAQ,cAmCxB8B,QAAOC,QAAUK;;ARrCjBN,OAAOC,SACLC,YAAahC,QAAQ,iBACrBiC,aAAcjC,QAAQ,kBACtBkC,UAAWlC,QAAQ,eACnBmC,WAAYnC,QAAQ,gBACpBoC,QAASpC,QAAQ;;AMLnB,YAIA,SAASiC,cAAaN,EAASwG,EAAQ/I,GACrCA,EAAUA,KACV,IAAIyD,GAAmBzD,EAAQyD,kBAC3B+C,cAAc/C,iBAGdD,EAAwBxD,EAAQwD,uBAChCgD,cAAchD,qBAGlB,OAFAvD,SAAQc,MAAM,4BAA8BwB,EAAQxC,IAAM,IAAKC,GAExDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,GAAI4M,GAEAC,EADAC,IAGJ,IAAIpJ,EAAuB,CACzB,GAAIqJ,GAA2B,GAAIrM,SAAQ,SAAS4I,GAClDsD,EAAYI,WAAW,WACrBhN,EAAMwC,MAAMC,GAASpC,KAAK,SAAS8G,GAC7BA,GAKFmC,EAAQnC,MAGa,IAAxBzD,IAELoJ,GAASlI,KAAKmI,GAGhB,GAAIE,GAAiB9M,QAAQ6G,cAAcvE,EAASvC,GACjDG,KAAK,SAAS8G,GAMb,GAJIyF,GACFM,aAAaN,GAGXjJ,EAAiBgB,KAAKwC,EAASC,QACjC,MAAOD,EAMT,MAHAhH,SAAQc,MAAM,+BAAiCkG,EAASgG,WACpDjN,GACJ2M,EAAmB1F,EACb,GAAIiF,OAAM,kBAdCjM,SAeV,SAASoI,GAGhB,MAFApI,SAAQc,MAAM,iDACVwB,EAAQxC,IAAM,IAAKC,GAChBF,EAAMwC,MAAMC,GAASpC,KAAK,SAAS8G,GAExC,GAAIA,EACF,MAAOA,EAKT,IAAI0F,EACF,MAAOA,EAKT,MAAMtE,MAMZ,OAFAuE,GAASlI,KAAKqI,GAEPvM,QAAQ0M,KAAKN,KAzExB,GAAIpG,eAAgB5F,QAAQ,cACxBX,QAAUW,QAAQ,aA4EtB8B,QAAOC,QAAUE;;AF9EjB,YAGA,SAASD,aAAYL,EAASwG,EAAQ/I,GAEpC,MADAC,SAAQc,MAAM,2BAA6BwB,EAAQxC,IAAM,IAAKC,GACvD+G,MAAMxE,GAJf,GAAItC,SAAUW,QAAQ,aAOtB8B,QAAOC,QAAUC;;ARRjB,YA6EA,SAAS9C,OAAMC,EAAKC,GAClB,MAAOC,SAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMM,IAAIL,KAIrB,QAASM,SAAQN,EAAKC,GACpB,MAAOC,SAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAAA,UAAaC,KAIxB,QAASO,UAASC,GACVA,YAAiBC,UACrBC,sBAAsBF,GAGxBP,QAAQU,cAAgBV,QAAQU,cAAcC,OAAOJ,GA5FvDK,QAAQ,+BACR,IAAIZ,SAAUY,QAAQ,aAClBC,OAASD,QAAQ,YACjBX,QAAUW,QAAQ,aAClBE,WAAaF,QAAQ,eAEzBX,SAAQc,MAAM,oCAGd,IAAIC,SAAU,SAAST,GACrB,MAAOA,GAAMU,OAAO,SAASC,EAAGC,GAC9B,MAAOD,GAAEP,OAAOQ,SAIhBV,sBAAwB,SAASF,GACnC,GAAIa,GAAUC,MAAMC,QAAQf,EAS5B,IARIa,GACFb,EAAMgB,QAAQ,SAASC,GACC,gBAATA,IAAsBA,YAAgBC,WACjDL,GAAU,MAKXA,EACH,KAAM,IAAIM,WAAU,4IAKtB,OAAOnB,GAGToB,MAAKC,iBAAiB,UAAW,SAASC,GACxC,GAAIC,GAAgB9B,QAAQF,MAAMiC,KAAO,gBACzC9B,SAAQc,MAAM,uBACdd,QAAQc,MAAM,mBAAqBe,EAAgB,KACnDD,EAAMG,UACJ/B,QAAQC,WAAWJ,OAAQiC,KAAMD,KAChC3B,KAAK,SAASL,GACb,MAAOU,SAAQyB,IAAIjC,QAAQU,eAC1BP,KAAKa,SACLb,KAAKM,uBACLN,KAAK,SAASO,GAGb,MAFAT,SAAQc,MAAM,mBACTL,EAAcwB,KAAK,OAAS,WAC1BpC,EAAMqC,OAAOzB,UAQ5BiB,KAAKC,iBAAiB,WAAY,SAASC,GACzC5B,QAAQc,MAAM,uBACd,IAAIe,GAAgB9B,QAAQF,MAAMiC,KAAO,gBACzCF,GAAMG,UAAU/B,QAAQmC,YAAYN,EAAe9B,QAAQF,MAAMiC,SAKnEJ,KAAKC,iBAAiB,QAAS,SAASC,GACtC,GAAIQ,GAAUxB,OAAOyB,MAAMT,EAAMU,QAE7BF,GACFR,EAAMW,YAAYH,EAAQR,EAAMU,UACvB1B,OAAAA,YAA2C,QAAzBgB,EAAMU,QAAQE,QACzCZ,EAAMW,YAAY3B,OAAAA,WAAegB,EAAMU,YA0B3CG,OAAOC,SACLC,YAAa9B,WAAW8B,YACxBC,aAAc/B,WAAW+B,aACzBC,UAAWhC,WAAWgC,UACtBC,WAAYjC,WAAWiC,WACvBC,QAASlC,WAAWkC,QACpBnC,OAAQA,OACRb,QAASA,QACTF,MAAOA,MACPO,QAASA,QACTC,SAAUA;;Ac1HZoC,OAAOC,QAAUtB,MAAMC,SAAW,SAAU4P,GAC1C,MAA8C,kBAAvClF,OAAOhH,UAAUuI,SAAS4D,KAAKD;;ADkCxC,QAASxD,OAAOC,GAOd,IANA,GAIIC,GAJAC,KACA5E,EAAM,EACNC,EAAQ,EACRjE,EAAO,GAG6B,OAAhC2I,EAAME,YAAY9E,KAAK2E,KAAe,CAC5C,GAAII,GAAIH,EAAI,GACRI,EAAUJ,EAAI,GACdK,EAASL,EAAI1E,KAKjB,IAJAjE,GAAQ0I,EAAIO,MAAMhF,EAAO+E,GACzB/E,EAAQ+E,EAASF,EAAE5H,OAGf6H,EACF/I,GAAQ+I,EAAQ,OADlB,CAKA,GAAI7J,GAAOwJ,EAAIzE,GACXiF,EAASP,EAAI,GACb7L,EAAO6L,EAAI,GACXQ,EAAUR,EAAI,GACdS,EAAQT,EAAI,GACZU,EAAWV,EAAI,GACfW,EAAWX,EAAI,EAGf3I,KACF4I,EAAOnJ,KAAKO,GACZA,EAAO,GAGT,IAAIuJ,GAAoB,MAAVL,GAA0B,MAARhK,GAAgBA,IAASgK,EACrDM,EAAsB,MAAbH,GAAiC,MAAbA,EAC7BI,EAAwB,MAAbJ,GAAiC,MAAbA,EAC/BK,EAAYf,EAAI,IAAM,IACtBtJ,EAAU8J,GAAWC,IAAUE,EAAW,KAAO,KAAOI,EAAY,MAExEd,GAAOnJ,MACL3C,KAAMA,GAAQkH,IACdkF,OAAQA,GAAU,GAClBQ,UAAWA,EACXD,SAAUA,EACVD,OAAQA,EACRD,QAASA,EACTD,WAAYA,EACZjK,QAASsK,YAAYtK,MAczB,MATI4E,GAAQyE,EAAIxH,SACdlB,GAAQ0I,EAAIkB,OAAO3F,IAIjBjE,GACF4I,EAAOnJ,KAAKO,GAGP4I,EAST,QAASiB,SAASnB,GAChB,MAAOoB,kBAAiBrB,MAAMC,IAShC,QAASqB,0BAA0BrB,GACjC,MAAOsB,WAAUtB,GAAK/J,QAAQ,UAAW,SAAUsL,GACjD,MAAO,IAAMA,EAAEC,WAAW,GAAG5B,SAAS,IAAI6B,gBAU9C,QAASC,gBAAgB1B,GACvB,MAAOsB,WAAUtB,GAAK/J,QAAQ,QAAS,SAAUsL,GAC/C,MAAO,IAAMA,EAAEC,WAAW,GAAG5B,SAAS,IAAI6B,gBAO9C,QAASL,kBAAkBlB,GAKzB,IAAK,GAHDzJ,GAAU,GAAI/C,OAAMwM,EAAO1H,QAGtBC,EAAI,EAAGA,EAAIyH,EAAO1H,OAAQC,IACR,gBAAdyH,GAAOzH,KAChBhC,EAAQgC,GAAK,GAAI7B,QAAO,OAASsJ,EAAOzH,GAAG9B,QAAU,MAIzD,OAAO,UAAUgL,EAAKC,GAMpB,IAAK,GALDtK,GAAO,GACPuK,EAAOF,MACPtP,EAAUuP,MACVE,EAASzP,EAAQ0P,OAASV,yBAA2BW,mBAEhDvJ,EAAI,EAAGA,EAAIyH,EAAO1H,OAAQC,IAAK,CACtC,GAAIwJ,GAAQ/B,EAAOzH,EAEnB,IAAqB,gBAAVwJ,GAAX,CAMA,GACIC,GADArL,EAAQgL,EAAKI,EAAM7N,KAGvB,IAAa,MAATyC,EAAe,CACjB,GAAIoL,EAAMlB,SAAU,CAEdkB,EAAMpB,UACRvJ,GAAQ2K,EAAMzB,OAGhB,UAEA,KAAM,IAAIzM,WAAU,aAAekO,EAAM7N,KAAO,mBAIpD,GAAI+N,QAAQtL,GAAZ,CACE,IAAKoL,EAAMnB,OACT,KAAM,IAAI/M,WAAU,aAAekO,EAAM7N,KAAO,kCAAoCgO,KAAKC,UAAUxL,GAAS,IAG9G,IAAqB,IAAjBA,EAAM2B,OAAc,CACtB,GAAIyJ,EAAMlB,SACR,QAEA,MAAM,IAAIhN,WAAU,aAAekO,EAAM7N,KAAO,qBAIpD,IAAK,GAAIkO,GAAI,EAAGA,EAAIzL,EAAM2B,OAAQ8J,IAAK,CAGrC,GAFAJ,EAAUJ,EAAOjL,EAAMyL,KAElB7L,EAAQgC,GAAG3B,KAAKoL,GACnB,KAAM,IAAInO,WAAU,iBAAmBkO,EAAM7N,KAAO,eAAiB6N,EAAMtL,QAAU,oBAAsByL,KAAKC,UAAUH,GAAW,IAGvI5K,KAAe,IAANgL,EAAUL,EAAMzB,OAASyB,EAAMjB,WAAakB,OApBzD,CA4BA,GAFAA,EAAUD,EAAMrB,SAAWc,eAAe7K,GAASiL,EAAOjL,IAErDJ,EAAQgC,GAAG3B,KAAKoL,GACnB,KAAM,IAAInO,WAAU,aAAekO,EAAM7N,KAAO,eAAiB6N,EAAMtL,QAAU,oBAAsBuL,EAAU,IAGnH5K,IAAQ2K,EAAMzB,OAAS0B,OArDrB5K,IAAQ2K,EAwDZ,MAAO3K,IAUX,QAASiL,cAAcvC,GACrB,MAAOA,GAAI/J,QAAQ,2BAA4B,QASjD,QAASgL,aAAaP,GACpB,MAAOA,GAAMzK,QAAQ,gBAAiB,QAUxC,QAASuM,YAAYC,EAAI1H,GAEvB,MADA0H,GAAG1H,KAAOA,EACH0H,EAST,QAASC,OAAOrQ,GACd,MAAOA,GAAQsQ,UAAY,GAAK,IAUlC,QAASC,gBAAgBtL,EAAMyD,GAE7B,GAAI8H,GAASvL,EAAKE,OAAO7C,MAAM,YAE/B,IAAIkO,EACF,IAAK,GAAIpK,GAAI,EAAGA,EAAIoK,EAAOrK,OAAQC,IACjCsC,EAAKhE,MACH3C,KAAMqE,EACN+H,OAAQ,KACRQ,UAAW,KACXD,UAAU,EACVD,QAAQ,EACRD,SAAS,EACTD,UAAU,EACVjK,QAAS,MAKf,OAAO6L,YAAWlL,EAAMyD,GAW1B,QAAS+H,eAAexL,EAAMyD,EAAM1I,GAGlC,IAAK,GAFD0Q,MAEKtK,EAAI,EAAGA,EAAInB,EAAKkB,OAAQC,IAC/BsK,EAAMhM,KAAKiM,aAAa1L,EAAKmB,GAAIsC,EAAM1I,GAASmF,OAGlD,IAAIQ,GAAS,GAAIpB,QAAO,MAAQmM,EAAMxO,KAAK,KAAO,IAAKmO,MAAMrQ,GAE7D,OAAOmQ,YAAWxK,EAAQ+C,GAW5B,QAASkI,gBAAgB3L,EAAMyD,EAAM1I,GAKnC,IAAK,GAJD6N,GAASH,MAAMzI,GACfmL,EAAKS,eAAehD,EAAQ7N,GAGvBoG,EAAI,EAAGA,EAAIyH,EAAO1H,OAAQC,IACR,gBAAdyH,GAAOzH,IAChBsC,EAAKhE,KAAKmJ,EAAOzH,GAIrB,OAAO+J,YAAWC,EAAI1H,GAUxB,QAASmI,gBAAgBhD,EAAQ7N,GAC/BA,EAAUA,KASV,KAAK,GAPD8Q,GAAS9Q,EAAQ8Q,OACjBC,EAAM/Q,EAAQ+Q,OAAQ,EACtB1L,EAAQ,GACR2L,EAAYnD,EAAOA,EAAO1H,OAAS,GACnC8K,EAAqC,gBAAdD,IAA0B,MAAMvM,KAAKuM,GAGvD5K,EAAI,EAAGA,EAAIyH,EAAO1H,OAAQC,IAAK,CACtC,GAAIwJ,GAAQ/B,EAAOzH,EAEnB,IAAqB,gBAAVwJ,GACTvK,GAAS6K,aAAaN,OACjB,CACL,GAAIzB,GAAS+B,aAAaN,EAAMzB,QAC5BC,EAAU,MAAQwB,EAAMtL,QAAU,GAElCsL,GAAMnB,SACRL,GAAW,MAAQD,EAASC,EAAU,MAOpCA,EAJAwB,EAAMlB,SACHkB,EAAMpB,QAGCL,EAAS,IAAMC,EAAU,KAFzB,MAAQD,EAAS,IAAMC,EAAU,MAKnCD,EAAS,IAAMC,EAAU,IAGrC/I,GAAS+I,GAoBb,MAZK0C,KACHzL,GAAS4L,EAAgB5L,EAAM6I,MAAM,EAAG,IAAM7I,GAAS,iBAIvDA,GADE0L,EACO,IAIAD,GAAUG,EAAgB,GAAK,YAGnC,GAAI1M,QAAO,IAAMc,EAAOgL,MAAMrQ,IAevC,QAAS2Q,cAAc1L,EAAMyD,EAAM1I,GAUjC,MATA0I,GAAOA,MAEFoH,QAAQpH,GAGD1I,IACVA,OAHAA,EAAiC,EACjC0I,MAKEzD,YAAgBV,QACXgM,eAAetL,EAA4B,GAGhD6K,QAAQ7K,GACHwL,cAAoC,EAA8B,EAAQzQ,GAG5E4Q,eAAqC,EAA8B,EAAQ5Q,GAxapF,GAAI8P,SAAUlP,QAAQ,UAKtB8B,QAAOC,QAAUgO,aACjBjO,OAAOC,QAAQ+K,MAAQA,MACvBhL,OAAOC,QAAQmM,QAAUA,QACzBpM,OAAOC,QAAQoM,iBAAmBA,iBAClCrM,OAAOC,QAAQkO,eAAiBA,cAOhC,IAAI/C,aAAc,GAAIvJ,SAGpB,UAOA,kGACArC,KAAK,KAAM;;CNVZ,WACC,GAAIqJ,GAAeC,MAAMxG,UAAU7C,OAC/BsJ,EAAYC,UAAUD,UAAUnJ,MAAM,4BAG1C,IAAImJ,EACF,GAAIE,GAAQF,EAAU,GAClBG,EAAUC,SAASJ,EAAU,GAIjCF,MAAkBE,GACL,YAAVE,GAAuBC,GAAW,IACxB,WAAVD,GAAuBC,GAAW,MAMvCJ,MAAMxG,UAAU7C,OAAS,SAAgBwG,GAIvC,QAASmD,GAAaxF,GACpB1B,KAAK7C,KAAO,eACZ6C,KAAKmH,KAAO,GACZnH,KAAK0B,QAAUA,EANjB,GAAIxG,GAAQ8E,IAWZ,OAFAkH,GAAa9G,UAAYgH,OAAOC,OAAOC,MAAMlH,WAEtCxE,QAAQ4I,UAAUjJ,KAAK,WAC5B,GAAIgM,UAAUhG,OAAS,EAAG,KAAM,IAAIzE,UAcpC,OATAiH,GAAWA,EAAS5E,IAAI,SAASxB,GAC/B,MAAIA,aAAmBd,SACdc,EAGA6J,OAAO7J,KAIX/B,QAAQyB,IACb0G,EAAS5E,IAAI,SAASxB,GACG,gBAAZA,KACTA,EAAU,GAAId,SAAQc,GAGxB,IAAI8J,GAAS,GAAIlJ,KAAIZ,EAAQxC,KAAKuM,QAElC,IAAe,UAAXD,GAAiC,WAAXA,EACxB,KAAM,IAAIP,GAAa,iBAGzB,OAAO/E,OAAMxE,EAAQyE,cAGxB7G,KAAK,SAASoM,GAGf,GAAIA,EAAUC,KAAK,SAASvF,GAC1B,OAAQA,EAASwF,KAEjB,KAAM,IAAIX,GAAa,4BAKzB,OAAOtL,SAAQyB,IACbsK,EAAUxI,IAAI,SAASkD,EAAUb,GAC/B,MAAOtG,GAAMqH,IAAIwB,EAASvC,GAAIa,QAGjC9G,KAAK,eAKVqL,MAAMxG,UAAU5E,IAAM,SAAamC,GACjC,MAAOqC,MAAKzC,QAAQI","file":"bundle.js","sourcesContent":["(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 0) {\n return routes[0].makeHandler(pathOrUrl);\n }\n }\n }\n\n return null;\n};\n\nRouter.prototype.match = function(request) {\n return this.matchMethod(request.method, request.url) ||\n this.matchMethod('any', request.url);\n};\n\nmodule.exports = new Router();\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\nvar globalOptions = require('./options');\nvar idbCacheExpiration = require('./idb-cache-expiration');\n\nfunction debug(message, options) {\n options = options || {};\n var flag = options.debug || globalOptions.debug;\n if (flag) {\n console.log('[sw-toolbox] ' + message);\n }\n}\n\nfunction openCache(options) {\n var cacheName;\n if (options && options.cache) {\n cacheName = options.cache.name;\n }\n cacheName = cacheName || globalOptions.cache.name;\n\n return caches.open(cacheName);\n}\n\nfunction fetchAndCache(request, options) {\n options = options || {};\n var successResponses = options.successResponses ||\n globalOptions.successResponses;\n\n return fetch(request.clone()).then(function(response) {\n // Only cache GET requests with successful responses.\n // Since this is not part of the promise chain, it will be done\n // asynchronously and will not block the response from being returned to the\n // page.\n if (request.method === 'GET' && successResponses.test(response.status)) {\n openCache(options).then(function(cache) {\n cache.put(request, response).then(function() {\n // If any of the options are provided in options.cache then use them.\n // Do not fallback to the global options for any that are missing\n // unless they are all missing.\n var cacheOptions = options.cache || globalOptions.cache;\n\n // Only run the cache expiration logic if at least one of the maximums\n // is set, and if we have a name for the cache that the options are\n // being applied to.\n if ((cacheOptions.maxEntries || cacheOptions.maxAgeSeconds) &&\n cacheOptions.name) {\n queueCacheExpiration(request, cache, cacheOptions);\n }\n });\n });\n }\n\n return response.clone();\n });\n}\n\nvar cleanupQueue;\nfunction queueCacheExpiration(request, cache, cacheOptions) {\n var cleanup = cleanupCache.bind(null, request, cache, cacheOptions);\n\n if (cleanupQueue) {\n cleanupQueue = cleanupQueue.then(cleanup);\n } else {\n cleanupQueue = cleanup();\n }\n}\n\nfunction cleanupCache(request, cache, cacheOptions) {\n var requestUrl = request.url;\n var maxAgeSeconds = cacheOptions.maxAgeSeconds;\n var maxEntries = cacheOptions.maxEntries;\n var cacheName = cacheOptions.name;\n\n var now = Date.now();\n debug('Updating LRU order for ' + requestUrl + '. Max entries is ' +\n maxEntries + ', max age is ' + maxAgeSeconds);\n\n return idbCacheExpiration.getDb(cacheName).then(function(db) {\n return idbCacheExpiration.setTimestampForUrl(db, requestUrl, now);\n }).then(function(db) {\n return idbCacheExpiration.expireEntries(db, maxEntries, maxAgeSeconds, now);\n }).then(function(urlsToDelete) {\n debug('Successfully updated IDB.');\n\n var deletionPromises = urlsToDelete.map(function(urlToDelete) {\n return cache.delete(urlToDelete);\n });\n\n return Promise.all(deletionPromises).then(function() {\n debug('Done with cache cleanup.');\n });\n }).catch(function(error) {\n debug(error);\n });\n}\n\nfunction renameCache(source, destination, options) {\n debug('Renaming cache: [' + source + '] to [' + destination + ']', options);\n return caches.delete(destination).then(function() {\n return Promise.all([\n caches.open(source),\n caches.open(destination)\n ]).then(function(results) {\n var sourceCache = results[0];\n var destCache = results[1];\n\n return sourceCache.keys().then(function(requests) {\n return Promise.all(requests.map(function(request) {\n return sourceCache.match(request).then(function(response) {\n return destCache.put(request, response);\n });\n }));\n }).then(function() {\n return caches.delete(source);\n });\n });\n });\n}\n\nmodule.exports = {\n debug: debug,\n fetchAndCache: fetchAndCache,\n openCache: openCache,\n renameCache: renameCache\n};\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\nmodule.exports = {\n networkOnly: require('./networkOnly'),\n networkFirst: require('./networkFirst'),\n cacheOnly: require('./cacheOnly'),\n cacheFirst: require('./cacheFirst'),\n fastest: require('./fastest')\n};\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\n// TODO: Use self.registration.scope instead of self.location\nvar url = new URL('./', self.location);\nvar basePath = url.pathname;\nvar pathRegexp = require('path-to-regexp');\n\nvar Route = function(method, path, handler, options) {\n if (path instanceof RegExp) {\n this.fullUrlRegExp = path;\n } else {\n // The URL() constructor can't parse express-style routes as they are not\n // valid urls. This means we have to manually manipulate relative urls into\n // absolute ones. This check is extremely naive but implementing a tweaked\n // version of the full algorithm seems like overkill\n // (https://url.spec.whatwg.org/#concept-basic-url-parser)\n if (path.indexOf('/') !== 0) {\n path = basePath + path;\n }\n\n this.keys = [];\n this.regexp = pathRegexp(path, this.keys);\n }\n\n this.method = method;\n this.options = options;\n this.handler = handler;\n};\n\nRoute.prototype.makeHandler = function(url) {\n var values;\n if (this.regexp) {\n var match = this.regexp.exec(url);\n values = {};\n this.keys.forEach(function(key, index) {\n values[key.name] = match[index + 1];\n });\n }\n\n return function(request) {\n return this.handler(request, values, this.options);\n }.bind(this);\n};\n\nmodule.exports = Route;\n","/*\n Copyright 2015 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\nvar DB_PREFIX = 'sw-toolbox-';\nvar DB_VERSION = 1;\nvar STORE_NAME = 'store';\nvar URL_PROPERTY = 'url';\nvar TIMESTAMP_PROPERTY = 'timestamp';\nvar cacheNameToDbPromise = {};\n\nfunction openDb(cacheName) {\n return new Promise(function(resolve, reject) {\n var request = indexedDB.open(DB_PREFIX + cacheName, DB_VERSION);\n\n request.onupgradeneeded = function() {\n var objectStore = request.result.createObjectStore(STORE_NAME,\n {keyPath: URL_PROPERTY});\n objectStore.createIndex(TIMESTAMP_PROPERTY, TIMESTAMP_PROPERTY,\n {unique: false});\n };\n\n request.onsuccess = function() {\n resolve(request.result);\n };\n\n request.onerror = function() {\n reject(request.error);\n };\n });\n}\n\nfunction getDb(cacheName) {\n if (!(cacheName in cacheNameToDbPromise)) {\n cacheNameToDbPromise[cacheName] = openDb(cacheName);\n }\n\n return cacheNameToDbPromise[cacheName];\n}\n\nfunction setTimestampForUrl(db, url, now) {\n return new Promise(function(resolve, reject) {\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n objectStore.put({url: url, timestamp: now});\n\n transaction.oncomplete = function() {\n resolve(db);\n };\n\n transaction.onabort = function() {\n reject(transaction.error);\n };\n });\n}\n\nfunction expireOldEntries(db, maxAgeSeconds, now) {\n // Bail out early by resolving with an empty array if we're not using\n // maxAgeSeconds.\n if (!maxAgeSeconds) {\n return Promise.resolve([]);\n }\n\n return new Promise(function(resolve, reject) {\n var maxAgeMillis = maxAgeSeconds * 1000;\n var urls = [];\n\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n var index = objectStore.index(TIMESTAMP_PROPERTY);\n\n index.openCursor().onsuccess = function(cursorEvent) {\n var cursor = cursorEvent.target.result;\n if (cursor) {\n if (now - maxAgeMillis > cursor.value[TIMESTAMP_PROPERTY]) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n cursor.continue();\n }\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireExtraEntries(db, maxEntries) {\n // Bail out early by resolving with an empty array if we're not using\n // maxEntries.\n if (!maxEntries) {\n return Promise.resolve([]);\n }\n\n return new Promise(function(resolve, reject) {\n var urls = [];\n\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n var index = objectStore.index(TIMESTAMP_PROPERTY);\n\n var countRequest = index.count();\n index.count().onsuccess = function() {\n var initialCount = countRequest.result;\n\n if (initialCount > maxEntries) {\n index.openCursor().onsuccess = function(cursorEvent) {\n var cursor = cursorEvent.target.result;\n if (cursor) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n if (initialCount - urls.length > maxEntries) {\n cursor.continue();\n }\n }\n };\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireEntries(db, maxEntries, maxAgeSeconds, now) {\n return expireOldEntries(db, maxAgeSeconds, now).then(function(oldUrls) {\n return expireExtraEntries(db, maxEntries).then(function(extraUrls) {\n return oldUrls.concat(extraUrls);\n });\n });\n}\n\nmodule.exports = {\n getDb: getDb,\n setTimestampForUrl: setTimestampForUrl,\n expireEntries: expireEntries\n};\n","/**\n * Copyright 2015 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n(function() {\n var nativeAddAll = Cache.prototype.addAll;\n var userAgent = navigator.userAgent.match(/(Firefox|Chrome)\\/(\\d+\\.)/);\n\n // Has nice behavior of `var` which everyone hates\n if (userAgent) {\n var agent = userAgent[1];\n var version = parseInt(userAgent[2]);\n }\n\n if (\n nativeAddAll && (!userAgent ||\n (agent === 'Firefox' && version >= 46) ||\n (agent === 'Chrome' && version >= 50)\n )\n ) {\n return;\n }\n\n Cache.prototype.addAll = function addAll(requests) {\n var cache = this;\n\n // Since DOMExceptions are not constructable:\n function NetworkError(message) {\n this.name = 'NetworkError';\n this.code = 19;\n this.message = message;\n }\n\n NetworkError.prototype = Object.create(Error.prototype);\n\n return Promise.resolve().then(function() {\n if (arguments.length < 1) throw new TypeError();\n\n // Simulate sequence<(Request or USVString)> binding:\n var sequence = [];\n\n requests = requests.map(function(request) {\n if (request instanceof Request) {\n return request;\n }\n else {\n return String(request); // may throw TypeError\n }\n });\n\n return Promise.all(\n requests.map(function(request) {\n if (typeof request === 'string') {\n request = new Request(request);\n }\n\n var scheme = new URL(request.url).protocol;\n\n if (scheme !== 'http:' && scheme !== 'https:') {\n throw new NetworkError(\"Invalid scheme\");\n }\n\n return fetch(request.clone());\n })\n );\n }).then(function(responses) {\n // If some of the responses has not OK-eish status,\n // then whole operation should reject\n if (responses.some(function(response) {\n return !response.ok;\n })) {\n throw new NetworkError('Incorrect response status');\n }\n\n // TODO: check that requests don't overwrite one another\n // (don't think this is possible to polyfill due to opaque responses)\n return Promise.all(\n responses.map(function(response, i) {\n return cache.put(requests[i], response);\n })\n );\n }).then(function() {\n return undefined;\n });\n };\n\n Cache.prototype.add = function add(request) {\n return this.addAll([request]);\n };\n}());","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction networkOnly(request, values, options) {\n helpers.debug('Strategy: network only [' + request.url + ']', options);\n return fetch(request);\n}\n\nmodule.exports = networkOnly;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheOnly(request, values, options) {\n helpers.debug('Strategy: cache only [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request);\n });\n}\n\nmodule.exports = cacheOnly;\n","/*\n Copyright 2015 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar globalOptions = require('../options');\nvar helpers = require('../helpers');\n\nfunction networkFirst(request, values, options) {\n options = options || {};\n var successResponses = options.successResponses ||\n globalOptions.successResponses;\n // This will bypass options.networkTimeout if it's set to a false-y value like\n // 0, but that's the sane thing to do anyway.\n var networkTimeoutSeconds = options.networkTimeoutSeconds ||\n globalOptions.networkTimeoutSeconds;\n helpers.debug('Strategy: network first [' + request.url + ']', options);\n\n return helpers.openCache(options).then(function(cache) {\n var timeoutId;\n var promises = [];\n var originalResponse;\n\n if (networkTimeoutSeconds) {\n var cacheWhenTimedOutPromise = new Promise(function(resolve) {\n timeoutId = setTimeout(function() {\n cache.match(request).then(function(response) {\n if (response) {\n // Only resolve this promise if there's a valid response in the\n // cache. This ensures that we won't time out a network request\n // unless there's a cached entry to fallback on, which is arguably\n // the preferable behavior.\n resolve(response);\n }\n });\n }, networkTimeoutSeconds * 1000);\n });\n promises.push(cacheWhenTimedOutPromise);\n }\n\n var networkPromise = helpers.fetchAndCache(request, options)\n .then(function(response) {\n // We've got a response, so clear the network timeout if there is one.\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (successResponses.test(response.status)) {\n return response;\n }\n\n helpers.debug('Response was an HTTP error: ' + response.statusText,\n options);\n originalResponse = response;\n throw new Error('Bad response');\n }).catch(function(error) {\n helpers.debug('Network or response error, fallback to cache [' +\n request.url + ']', options);\n return cache.match(request).then(function(response) {\n // If there's a match in the cache, resolve with that.\n if (response) {\n return response;\n }\n\n // If we have a Response object from the previous fetch, then resolve\n // with that, even though it corresponds to an error status code.\n if (originalResponse) {\n return originalResponse;\n }\n\n // If we don't have a Response object from the previous fetch, likely\n // due to a network failure, then reject with the failure error.\n throw error;\n });\n });\n\n promises.push(networkPromise);\n\n return Promise.race(promises);\n });\n}\n\nmodule.exports = networkFirst;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheFirst(request, values, options) {\n helpers.debug('Strategy: cache first [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request).then(function(response) {\n if (response) {\n return response;\n }\n\n return helpers.fetchAndCache(request, options);\n });\n });\n}\n\nmodule.exports = cacheFirst;\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\nvar cacheOnly = require('./cacheOnly');\n\nfunction fastest(request, values, options) {\n helpers.debug('Strategy: fastest [' + request.url + ']', options);\n\n return new Promise(function(resolve, reject) {\n var rejected = false;\n var reasons = [];\n\n var maybeReject = function(reason) {\n reasons.push(reason.toString());\n if (rejected) {\n reject(new Error('Both cache and network failed: \"' +\n reasons.join('\", \"') + '\"'));\n } else {\n rejected = true;\n }\n };\n\n var maybeResolve = function(result) {\n if (result instanceof Response) {\n resolve(result);\n } else {\n maybeReject('No result returned');\n }\n };\n\n helpers.fetchAndCache(request.clone(), options)\n .then(maybeResolve, maybeReject);\n\n cacheOnly(request, values, options)\n .then(maybeResolve, maybeReject);\n });\n}\n\nmodule.exports = fastest;\n","var isarray = require('isarray')\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @return {!Array}\n */\nfunction parse (str) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || '/'\n var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?')\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: escapeGroup(pattern)\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str) {\n return tokensToFunction(parse(str))\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n var tokens = parse(path)\n var re = tokensToRegExp(tokens, options)\n\n // Attach keys back to the regexp.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] !== 'string') {\n keys.push(tokens[i])\n }\n }\n\n return attachKeys(re, keys)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, options) {\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n var lastToken = tokens[tokens.length - 1]\n var endsWithSlash = typeof lastToken === 'string' && /\\/$/.test(lastToken)\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\\\/(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithSlash ? '' : '(?=\\\\/|$)'\n }\n\n return new RegExp('^' + route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n keys = keys || []\n\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys)\n keys = []\n } else if (!options) {\n options = {}\n }\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\n}\n","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n"]} \ No newline at end of file +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/sw-toolbox.js","lib/options.js","lib/router.js","lib/helpers.js","lib/strategies/index.js","lib/route.js","lib/idb-cache-expiration.js","node_modules/serviceworker-cache-polyfill/index.js","lib/strategies/networkOnly.js","lib/strategies/networkFirst.js","lib/strategies/cacheOnly.js","lib/strategies/cacheFirst.js","lib/strategies/fastest.js","node_modules/path-to-regexp/index.js","node_modules/isarray/index.js"],"names":["cache","url","options","helpers","openCache","then","add","uncache","delete","precache","items","Promise","validatePrecacheInput","preCacheItems","concat","require","router","strategies","debug","flatten","reduce","a","b","isValid","Array","isArray","forEach","item","Request","TypeError","self","addEventListener","event","inactiveCache","name","waitUntil","all","join","addAll","renameCache","handler","match","request","respondWith","default","method","module","exports","networkOnly","networkFirst","cacheOnly","cacheFirst","fastest","scope","registration","URL","location","href","maxAgeSeconds","maxEntries","networkTimeoutSeconds","successResponses","regexEscape","s","replace","Route","keyMatch","map","string","entriesIterator","entries","next","matches","done","pattern","RegExp","value","test","push","Router","this","routes","Map","set","prototype","path","origin","source","toLowerCase","route","has","methodMap","get","routeMap","regExp","regexp","fullUrlRegExp","matchMethod","urlObject","pathname","_match","methodMaps","pathOrUrl","length","i","makeHandler","message","flag","globalOptions","console","log","cacheName","caches","open","fetchAndCache","fetch","clone","response","status","put","cacheOptions","queueCacheExpiration","cleanup","cleanupCache","bind","cleanupQueue","requestUrl","now","Date","idbCacheExpiration","getDb","db","setTimestampForUrl","expireEntries","urlsToDelete","deletionPromises","urlToDelete","catch","error","destination","results","sourceCache","destCache","keys","requests","basePath","pathRegexp","indexOf","values","exec","key","index","openDb","resolve","reject","indexedDB","DB_PREFIX","DB_VERSION","onupgradeneeded","objectStore","result","createObjectStore","STORE_NAME","keyPath","URL_PROPERTY","createIndex","TIMESTAMP_PROPERTY","unique","onsuccess","onerror","cacheNameToDbPromise","transaction","timestamp","oncomplete","onabort","expireOldEntries","maxAgeMillis","urls","openCursor","cursorEvent","cursor","target","continue","expireExtraEntries","countRequest","count","initialCount","oldUrls","extraUrls","nativeAddAll","Cache","userAgent","navigator","agent","version","parseInt","NetworkError","code","Object","create","Error","arguments","String","scheme","protocol","responses","some","ok","timeoutId","originalResponse","promises","cacheWhenTimedOutPromise","setTimeout","networkPromise","clearTimeout","statusText","race","rejected","reasons","maybeReject","reason","toString","maybeResolve","Response","parse","str","res","tokens","PATH_REGEXP","m","escaped","offset","slice","prefix","capture","group","modifier","asterisk","partial","repeat","optional","delimiter","escapeGroup","substr","compile","tokensToFunction","encodeURIComponentPretty","encodeURI","c","charCodeAt","toUpperCase","encodeAsterisk","obj","opts","data","encode","pretty","encodeURIComponent","token","segment","isarray","JSON","stringify","j","escapeString","attachKeys","re","flags","sensitive","regexpToRegexp","groups","arrayToRegexp","parts","pathToRegexp","stringToRegexp","tokensToRegExp","strict","end","lastToken","endsWithSlash","arr","call"],"mappings":"AAAA;AIeA,YAKA,SAASkB,OAAMwF,EAASxG,GACtBA,EAAUA,KACV,IAAIyG,GAAOzG,EAAQgB,OAAS0F,cAAc1F,KACtCyF,IACFE,QAAQC,IAAI,gBAAkBJ,GAIlC,QAAStG,WAAUF,GACjB,GAAI6G,EAMJ,OALI7G,IAAWA,EAAQF,QACrB+G,EAAY7G,EAAQF,MAAMkC,MAE5B6E,EAAYA,GAAaH,cAAc5G,MAAMkC,KAEtC8E,OAAOC,KAAKF,GAGrB,QAASG,eAAcxE,EAASxC,GAC9BA,EAAUA,KACV,IAAI2D,GAAmB3D,EAAQ2D,kBAC3B+C,cAAc/C,gBAElB,OAAOsD,OAAMzE,EAAQ0E,SAAS/G,KAAK,SAASgH,GAwB1C,MAnBuB,QAAnB3E,EAAQG,QAAoBgB,EAAiBgB,KAAKwC,EAASC,SAC7DlH,UAAUF,GAASG,KAAK,SAASL,GAC/BA,EAAMuH,IAAI7E,EAAS2E,GAAUhH,KAAK,WAIhC,GAAImH,GAAetH,EAAQF,OAAS4G,cAAc5G,OAK7CwH,EAAa7D,YAAc6D,EAAa9D,gBACzC8D,EAAatF,MACfuF,qBAAqB/E,EAAS1C,EAAOwH,OAMtCH,EAASD,UAKpB,QAASK,sBAAqB/E,EAAS1C,EAAOwH,GAC5C,GAAIE,GAAUC,aAAaC,KAAK,KAAMlF,EAAS1C,EAAOwH,EAGpDK,cADEA,aACaA,aAAaxH,KAAKqH,GAElBA,IAInB,QAASC,cAAajF,EAAS1C,EAAOwH,GACpC,GAAIM,GAAapF,EAAQzC,IACrByD,EAAgB8D,EAAa9D,cAC7BC,EAAa6D,EAAa7D,WAC1BoD,EAAYS,EAAatF,KAEzB6F,EAAMC,KAAKD,KAIf,OAHA7G,OAAM,0BAA4B4G,EAAa,oBAC7CnE,EAAa,gBAAkBD,GAE1BuE,mBAAmBC,MAAMnB,GAAW1G,KAAK,SAAS8H,GACvD,MAAOF,oBAAmBG,mBAAmBD,EAAIL,EAAYC,KAC5D1H,KAAK,SAAS8H,GACf,MAAOF,oBAAmBI,cAAcF,EAAIxE,EAAYD,EAAeqE,KACtE1H,KAAK,SAASiI,GACfpH,MAAM,4BAEN,IAAIqH,GAAmBD,EAAanE,IAAI,SAASqE,GAC/C,MAAOxI,GAAMQ,OAAOgI,IAGtB,OAAO7H,SAAQyB,IAAImG,GAAkBlI,KAAK,WACxCa,MAAM,gCAEPuH,MAAM,SAASC,GAChBxH,MAAMwH,KAIV,QAASnG,aAAYgD,EAAQoD,EAAazI,GAExC,MADAgB,OAAM,oBAAsBqE,EAAS,SAAWoD,EAAc,IAAKzI,GAC5D8G,OAAOxG,OAAOmI,GAAatI,KAAK,WACrC,MAAOM,SAAQyB,KACb4E,OAAOC,KAAK1B,GACZyB,OAAOC,KAAK0B,KACXtI,KAAK,SAASuI,GACf,GAAIC,GAAcD,EAAQ,GACtBE,EAAYF,EAAQ,EAExB,OAAOC,GAAYE,OAAO1I,KAAK,SAAS2I,GACtC,MAAOrI,SAAQyB,IAAI4G,EAAS7E,IAAI,SAASzB,GACvC,MAAOmG,GAAYpG,MAAMC,GAASrC,KAAK,SAASgH,GAC9C,MAAOyB,GAAUvB,IAAI7E,EAAS2E,UAGjChH,KAAK,WACN,MAAO2G,QAAOxG,OAAO+E,SA/G7B,GAAIqB,eAAgB7F,QAAQ,aACxBkH,mBAAqBlH,QAAQ,0BAqD7B8G,YA+DJ/E,QAAOC,SACL7B,MAAOA,MACPgG,cAAeA,cACf9G,UAAWA,UACXmC,YAAaA;;AG3Hf,YASA,SAASiH,QAAOzC,GACd,MAAO,IAAIpG,SAAQ,SAAS8I,EAASC,GACnC,GAAIhH,GAAUiH,UAAU1C,KAAK2C,UAAY7C,EAAW8C,WAEpDnH,GAAQoH,gBAAkB,WACxB,GAAIC,GAAcrH,EAAQsH,OAAOC,kBAAkBC,YAC9CC,QAASC,cACdL,GAAYM,YAAYC,mBAAoBA,oBACvCC,QAAQ,KAGf7H,EAAQ8H,UAAY,WAClBf,EAAQ/G,EAAQsH,SAGlBtH,EAAQ+H,QAAU,WAChBf,EAAOhH,EAAQgG,UAKrB,QAASR,OAAMnB,GAKb,MAJMA,KAAa2D,wBACjBA,qBAAqB3D,GAAayC,OAAOzC,IAGpC2D,qBAAqB3D,GAG9B,QAASqB,oBAAmBD,EAAIlI,EAAK8H,GACnC,MAAO,IAAIpH,SAAQ,SAAS8I,EAASC,GACnC,GAAIiB,GAAcxC,EAAGwC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,WAC1CH,GAAYxC,KAAKtH,IAAKA,EAAK2K,UAAW7C,IAEtC4C,EAAYE,WAAa,WACvBpB,EAAQtB,IAGVwC,EAAYG,QAAU,WACpBpB,EAAOiB,EAAYjC,UAKzB,QAASqC,kBAAiB5C,EAAIzE,EAAeqE,GAG3C,MAAKrE,GAIE,GAAI/C,SAAQ,SAAS8I,EAASC,GACnC,GAAIsB,GAA+B,IAAhBtH,EACfuH,KAEAN,EAAcxC,EAAGwC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,YACtCX,EAAQQ,EAAYR,MAAMe,mBAE9Bf,GAAM2B,aAAaV,UAAY,SAASW,GACtC,GAAIC,GAASD,EAAYE,OAAOrB,MAChC,IAAIoB,GACErD,EAAMiD,EAAeI,EAAOxG,MAAM0F,oBAAqB,CACzD,GAAIrK,GAAMmL,EAAOxG,MAAMwF,aACvBa,GAAKnG,KAAK7E,GACV8J,EAAYvJ,OAAOP,GACnBmL,EAAOE,aAKbX,EAAYE,WAAa,WACvBpB,EAAQwB,IAGVN,EAAYG,QAAUpB,IA3Bf/I,QAAQ8I,YA+BnB,QAAS8B,oBAAmBpD,EAAIxE,GAG9B,MAAKA,GAIE,GAAIhD,SAAQ,SAAS8I,EAASC,GACnC,GAAIuB,MAEAN,EAAcxC,EAAGwC,YAAYT,WAAY,aACzCH,EAAcY,EAAYZ,YAAYG,YACtCX,EAAQQ,EAAYR,MAAMe,oBAE1BkB,EAAejC,EAAMkC,OACzBlC,GAAMkC,QAAQjB,UAAY,WACxB,GAAIkB,GAAeF,EAAaxB,MAE5B0B,GAAe/H,IACjB4F,EAAM2B,aAAaV,UAAY,SAASW,GACtC,GAAIC,GAASD,EAAYE,OAAOrB,MAChC,IAAIoB,EAAQ,CACV,GAAInL,GAAMmL,EAAOxG,MAAMwF,aACvBa,GAAKnG,KAAK7E,GACV8J,EAAYvJ,OAAOP,GACfyL,EAAeT,EAAK1E,OAAS5C,GAC/ByH,EAAOE,eAOjBX,EAAYE,WAAa,WACvBpB,EAAQwB,IAGVN,EAAYG,QAAUpB,IAjCf/I,QAAQ8I,YAqCnB,QAASpB,eAAcF,EAAIxE,EAAYD,EAAeqE,GACpD,MAAOgD,kBAAiB5C,EAAIzE,EAAeqE,GAAK1H,KAAK,SAASsL,GAC5D,MAAOJ,oBAAmBpD,EAAIxE,GAAYtD,KAAK,SAASuL,GACtD,MAAOD,GAAQ7K,OAAO8K,OAnI5B,GAAIhC,WAAY,cACZC,WAAa,EACbK,WAAa,QACbE,aAAe,MACfE,mBAAqB,YACrBI,uBAmIJ5H,QAAOC,SACLmF,MAAOA,MACPE,mBAAoBA,mBACpBC,cAAeA;;AL7IjB,YAIA,IAAIhF,MAEFA,OADEvB,KAAKwB,aACCxB,KAAKwB,aAAaD,MAElBvB,KAAKuB,OAAS,GAAIE,KAAI,KAAMzB,KAAK0B,UAAUC,KAGrDX,OAAOC,SACL/C,OACEkC,KAAM,sBAAwBmB,MAAQ,MACtCK,cAAe,KACfC,WAAY,MAEdzC,OAAO,EACP0C,sBAAuB,KACvB/C,iBAIAgD,iBAAkB;;AIvBpB,YAGA,IAAI5D,KAAM,GAAIsD,KAAI,KAAMzB,KAAK0B,UACzByF,SAAWhJ,IAAIkG,SACf+C,WAAanI,QAAQ,kBAErBkD,MAAQ,SAASpB,EAAQwC,EAAM7C,EAAStC,GACtCmF,YAAgBV,QAClBK,KAAKgB,cAAgBX,GAOK,IAAtBA,EAAK8D,QAAQ,OACf9D,EAAO4D,SAAW5D,GAGpBL,KAAK+D,QACL/D,KAAKe,OAASmD,WAAW7D,EAAML,KAAK+D,OAGtC/D,KAAKnC,OAASA,EACdmC,KAAK9E,QAAUA,EACf8E,KAAKxC,QAAUA,EAGjByB,OAAMmB,UAAUqB,YAAc,SAASxG,GACrC,GAAImJ,EACJ,IAAIpE,KAAKe,OAAQ,CACf,GAAItD,GAAQuC,KAAKe,OAAOsD,KAAKpJ,EAC7BmJ,MACApE,KAAK+D,KAAKrH,QAAQ,SAAS4H,EAAKC,GAC9BH,EAAOE,EAAIpH,MAAQO,EAAM8G,EAAQ,KAIrC,MAAO,UAAS7G,GACd,MAAOsC,MAAKxC,QAAQE,EAAS0G,EAAQpE,KAAK9E,UAC1C0H,KAAK5C,OAGTlC,OAAOC,QAAUkB;;AH5CjB,YAKA,SAASH,aAAYC,GACnB,MAAOA,GAAEC,QAAQ,yBAA0B,QAJ7C,GAAIC,OAAQlD,QAAQ,WAChBZ,QAAUY,QAAQ,aAMlBmD,SAAW,SAASC,EAAKC,GAM3B,IAHA,GAAIC,GAAkBF,EAAIG,UACtB3C,EAAO0C,EAAgBE,OACvBC,MACI7C,EAAK8C,MAAM,CACjB,GAAIC,GAAU,GAAIC,QAAOhD,EAAKiD,MAAM,GAChCF,GAAQG,KAAKT,IACfI,EAAQM,KAAKnD,EAAKiD,MAAM,IAE1BjD,EAAO0C,EAAgBE,OAEzB,MAAOC,IAGLO,OAAS,WACXC,KAAKC,OAAS,GAAIC,KAElBF,KAAKC,OAAOE,IAAIR,OAAQ,GAAIO,MAC5BF,KAAKpC,QAAU,OAGhB,MAAO,OAAQ,MAAO,SAAU,OAAQ,OAAOlB,QAAQ,SAASmB,GAC/DkC,OAAOK,UAAUvC,GAAU,SAASwC,EAAM7C,EAAStC,GACjD,MAAO8E,MAAK1E,IAAIuC,EAAQwC,EAAM7C,EAAStC,MAI3C6E,OAAOK,UAAU9E,IAAM,SAASuC,EAAQwC,EAAM7C,EAAStC,GACrDA,EAAUA,KACV,IAAIoF,EAEAD,aAAgBV,QAIlBW,EAASX,QAETW,EAASpF,EAAQoF,QAAUxD,KAAK0B,SAAS8B,OAEvCA,EADEA,YAAkBX,QACXW,EAAOC,OAEPzB,YAAYwB,IAIzBzC,EAASA,EAAO2C,aAEhB,IAAIC,GAAQ,GAAIxB,OAAMpB,EAAQwC,EAAM7C,EAAStC,EAExC8E,MAAKC,OAAOS,IAAIJ,IACnBN,KAAKC,OAAOE,IAAIG,EAAQ,GAAIJ,KAG9B,IAAIS,GAAYX,KAAKC,OAAOW,IAAIN,EAC3BK,GAAUD,IAAI7C,IACjB8C,EAAUR,IAAItC,EAAQ,GAAIqC,KAG5B,IAAIW,GAAWF,EAAUC,IAAI/C,GACzBiD,EAASL,EAAMM,QAAUN,EAAMO,aAE/BH,GAASH,IAAII,EAAOP,SACtBpF,QAAQe,MAAM,IAAMmE,EAAO,+CAG7BQ,EAASV,IAAIW,EAAOP,OAAQE,IAG9BV,OAAOK,UAAUa,YAAc,SAASpD,EAAQ5C,GAC9C,GAAIiG,GAAY,GAAI3C,KAAItD,GACpBqF,EAASY,EAAUZ,OACnBD,EAAOa,EAAUC,QAOrB,OAAOnB,MAAKoB,OAAOvD,EAAQqB,SAASc,KAAKC,OAAQK,GAASD,IACxDL,KAAKoB,OAAOvD,GAASmC,KAAKC,OAAOW,IAAIjB,SAAU1E,IAGnD8E,OAAOK,UAAUgB,OAAS,SAASvD,EAAQwD,EAAYC,GACrD,GAA0B,IAAtBD,EAAWE,OACb,MAAO,KAGT,KAAK,GAAIC,GAAI,EAAGA,EAAIH,EAAWE,OAAQC,IAAK,CAC1C,GAAIb,GAAYU,EAAWG,GACvBX,EAAWF,GAAaA,EAAUC,IAAI/C,EAAO2C,cACjD,IAAIK,EAAU,CACZ,GAAIZ,GAASf,SAAS2B,EAAUS,EAChC,IAAIrB,EAAOsB,OAAS,EAClB,MAAOtB,GAAO,GAAGwB,YAAYH,IAKnC,MAAO,OAGTvB,OAAOK,UAAU3C,MAAQ,SAASC,GAChC,MAAOsC,MAAKiB,YAAYvD,EAAQG,OAAQH,EAAQzC,MAC5C+E,KAAKiB,YAAY,MAAOvD,EAAQzC,MAGtC6C,OAAOC,QAAU,GAAIgC;;ASrHrB,YAGA,SAAS5B,YAAWT,EAAS0G,EAAQlJ,GAEnC,MADAC,SAAQe,MAAM,0BAA4BwB,EAAQzC,IAAM,IAAKC,GACtDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMyC,MAAMC,GAASrC,KAAK,SAASgH,GACxC,MAAIA,GACKA,EAGFlH,QAAQ+G,cAAcxE,EAASxC,OAV5C,GAAIC,SAAUY,QAAQ,aAetB+B,QAAOC,QAAUI;;ADhBjB,YAGA,SAASD,WAAUR,EAAS0G,EAAQlJ,GAElC,MADAC,SAAQe,MAAM,yBAA2BwB,EAAQzC,IAAM,IAAKC,GACrDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMyC,MAAMC,KALvB,GAAIvC,SAAUY,QAAQ,aAStB+B,QAAOC,QAAUG;;AEVjB,YAIA,SAASE,SAAQV,EAAS0G,EAAQlJ,GAGhC,MAFAC,SAAQe,MAAM,sBAAwBwB,EAAQzC,IAAM,IAAKC,GAElD,GAAIS,SAAQ,SAAS8I,EAASC,GACnC,GAAI+D,IAAW,EACXC,KAEAC,EAAc,SAASC,GACzBF,EAAQ5I,KAAK8I,EAAOC,YAChBJ,EACF/D,EAAO,GAAI8C,OAAM,mCACbkB,EAAQrL,KAAK,QAAU,MAE3BoL,GAAW,GAIXK,EAAe,SAAS9D,GACtBA,YAAkB+D,UACpBtE,EAAQO,GAER2D,EAAY,sBAIhBxN,SAAQ+G,cAAcxE,EAAQ0E,QAASlH,GACpCG,KAAKyN,EAAcH,GAEtBzK,UAAUR,EAAS0G,EAAQlJ,GACxBG,KAAKyN,EAAcH,KAhC1B,GAAIxN,SAAUY,QAAQ,cAClBmC,UAAYnC,QAAQ,cAmCxB+B,QAAOC,QAAUK;;ARrCjBN,OAAOC,SACLC,YAAajC,QAAQ,iBACrBkC,aAAclC,QAAQ,kBACtBmC,UAAWnC,QAAQ,eACnBoC,WAAYpC,QAAQ,gBACpBqC,QAASrC,QAAQ;;AKLnB,YAIA,SAASkC,cAAaP,EAAS0G,EAAQlJ,GACrCA,EAAUA,KACV,IAAI2D,GAAmB3D,EAAQ2D,kBAC3B+C,cAAc/C,iBAGdD,EAAwB1D,EAAQ0D,uBAChCgD,cAAchD,qBAGlB,OAFAzD,SAAQe,MAAM,4BAA8BwB,EAAQzC,IAAM,IAAKC,GAExDC,QAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,GAAIgN,GAEAC,EADAC,IAGJ,IAAItJ,EAAuB,CACzB,GAAIuJ,GAA2B,GAAIxM,SAAQ,SAAS8I,GAClDuD,EAAYI,WAAW,WACrBpN,EAAMyC,MAAMC,GAASrC,KAAK,SAASgH,GAC7BA,GAKFoC,EAAQpC,MAGa,IAAxBzD,IAELsJ,GAASpI,KAAKqI,GAGhB,GAAIE,GAAiBlN,QAAQ+G,cAAcxE,EAASxC,GACjDG,KAAK,SAASgH,GAMb,GAJI2F,GACFM,aAAaN,GAGXnJ,EAAiBgB,KAAKwC,EAASC,QACjC,MAAOD,EAMT,MAHAlH,SAAQe,MAAM,+BAAiCmG,EAASkG,WACpDrN,GACJ+M,EAAmB5F,EACb,GAAImF,OAAM,kBACf/D,MAAM,SAASC,GAGhB,MAFAvI,SAAQe,MAAM,iDACVwB,EAAQzC,IAAM,IAAKC,GAChBF,EAAMyC,MAAMC,GAASrC,KAAK,SAASgH,GAExC,GAAIA,EACF,MAAOA,EAKT,IAAI4F,EACF,MAAOA,EAKT,MAAMvE,MAMZ,OAFAwE,GAASpI,KAAKuI,GAEP1M,QAAQ6M,KAAKN,KAzExB,GAAItG,eAAgB7F,QAAQ,cACxBZ,QAAUY,QAAQ,aA4EtB+B,QAAOC,QAAUE;;AD9EjB,YAGA,SAASD,aAAYN,EAAS0G,EAAQlJ,GAEpC,MADAC,SAAQe,MAAM,2BAA6BwB,EAAQzC,IAAM,IAAKC,GACvDiH,MAAMzE,GAJf,GAAIvC,SAAUY,QAAQ,aAOtB+B,QAAOC,QAAUC;;ARRjB,YA6EA,SAAShD,OAAMC,EAAKC,GAClB,MAAOC,SAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMM,IAAIL,KAIrB,QAASM,SAAQN,EAAKC,GACpB,MAAOC,SAAQC,UAAUF,GAASG,KAAK,SAASL,GAC9C,MAAOA,GAAMQ,OAAOP,KAIxB,QAASQ,UAASC,GACVA,YAAiBC,UACrBC,sBAAsBF,GAGxBR,QAAQW,cAAgBX,QAAQW,cAAcC,OAAOJ,GA5FvDK,QAAQ,+BACR,IAAIb,SAAUa,QAAQ,aAClBC,OAASD,QAAQ,YACjBZ,QAAUY,QAAQ,aAClBE,WAAaF,QAAQ,eAEzBZ,SAAQe,MAAM,oCAGd,IAAIC,SAAU,SAAST,GACrB,MAAOA,GAAMU,OAAO,SAASC,EAAGC,GAC9B,MAAOD,GAAEP,OAAOQ,SAIhBV,sBAAwB,SAASF,GACnC,GAAIa,GAAUC,MAAMC,QAAQf,EAS5B,IARIa,GACFb,EAAMgB,QAAQ,SAASC,GACC,gBAATA,IAAsBA,YAAgBC,WACjDL,GAAU,MAKXA,EACH,KAAM,IAAIM,WAAU,4IAKtB,OAAOnB,GAGToB,MAAKC,iBAAiB,UAAW,SAASC,GACxC,GAAIC,GAAgB/B,QAAQF,MAAMkC,KAAO,gBACzC/B,SAAQe,MAAM,uBACdf,QAAQe,MAAM,mBAAqBe,EAAgB,KACnDD,EAAMG,UACJhC,QAAQC,WAAWJ,OAAQkC,KAAMD,KAChC5B,KAAK,SAASL,GACb,MAAOW,SAAQyB,IAAIlC,QAAQW,eAC1BR,KAAKc,SACLd,KAAKO,uBACLP,KAAK,SAASQ,GAGb,MAFAV,SAAQe,MAAM,mBACTL,EAAcwB,KAAK,OAAS,WAC1BrC,EAAMsC,OAAOzB,UAQ5BiB,KAAKC,iBAAiB,WAAY,SAASC,GACzC7B,QAAQe,MAAM,uBACd,IAAIe,GAAgB/B,QAAQF,MAAMkC,KAAO,gBACzCF,GAAMG,UAAUhC,QAAQoC,YAAYN,EAAe/B,QAAQF,MAAMkC,SAKnEJ,KAAKC,iBAAiB,QAAS,SAASC,GACtC,GAAIQ,GAAUxB,OAAOyB,MAAMT,EAAMU,QAE7BF,GACFR,EAAMW,YAAYH,EAAQR,EAAMU,UACvB1B,OAAO4B,SAAoC,QAAzBZ,EAAMU,QAAQG,QACzCb,EAAMW,YAAY3B,OAAO4B,QAAQZ,EAAMU,YA0B3CI,OAAOC,SACLC,YAAa/B,WAAW+B,YACxBC,aAAchC,WAAWgC,aACzBC,UAAWjC,WAAWiC,UACtBC,WAAYlC,WAAWkC,WACvBC,QAASnC,WAAWmC,QACpBpC,OAAQA,OACRd,QAASA,QACTF,MAAOA,MACPO,QAASA,QACTE,SAAUA;;Ac1HZqC,OAAOC,QAAUvB,MAAMC,SAAW,SAAU+P,GAC1C,MAA8C,kBAAvClF,OAAOlH,UAAUyI,SAAS4D,KAAKD;;ADkCxC,QAASxD,OAAOC,GAOd,IANA,GAIIC,GAJAC,KACA7E,EAAM,EACNC,EAAQ,EACRlE,EAAO,GAG6B,OAAhC6I,EAAME,YAAY/E,KAAK4E,KAAe,CAC5C,GAAII,GAAIH,EAAI,GACRI,EAAUJ,EAAI,GACdK,EAASL,EAAI3E,KAKjB,IAJAlE,GAAQ4I,EAAIO,MAAMjF,EAAOgF,GACzBhF,EAAQgF,EAASF,EAAE9H,OAGf+H,EACFjJ,GAAQiJ,EAAQ,OADlB,CAKA,GAAI/J,GAAO0J,EAAI1E,GACXkF,EAASP,EAAI,GACbhM,EAAOgM,EAAI,GACXQ,EAAUR,EAAI,GACdS,EAAQT,EAAI,GACZU,EAAWV,EAAI,GACfW,EAAWX,EAAI,EAGf7I,KACF8I,EAAOrJ,KAAKO,GACZA,EAAO,GAGT,IAAIyJ,GAAoB,MAAVL,GAA0B,MAARlK,GAAgBA,IAASkK,EACrDM,EAAsB,MAAbH,GAAiC,MAAbA,EAC7BI,EAAwB,MAAbJ,GAAiC,MAAbA,EAC/BK,EAAYf,EAAI,IAAM,IACtBxJ,EAAUgK,GAAWC,IAAUE,EAAW,KAAO,KAAOI,EAAY,MAExEd,GAAOrJ,MACL5C,KAAMA,GAAQoH,IACdmF,OAAQA,GAAU,GAClBQ,UAAWA,EACXD,SAAUA,EACVD,OAAQA,EACRD,QAASA,EACTD,WAAYA,EACZnK,QAASwK,YAAYxK,MAczB,MATI6E,GAAQ0E,EAAI1H,SACdlB,GAAQ4I,EAAIkB,OAAO5F,IAIjBlE,GACF8I,EAAOrJ,KAAKO,GAGP8I,EAST,QAASiB,SAASnB,GAChB,MAAOoB,kBAAiBrB,MAAMC,IAShC,QAASqB,0BAA0BrB,GACjC,MAAOsB,WAAUtB,GAAKjK,QAAQ,UAAW,SAAUwL,GACjD,MAAO,IAAMA,EAAEC,WAAW,GAAG5B,SAAS,IAAI6B,gBAU9C,QAASC,gBAAgB1B,GACvB,MAAOsB,WAAUtB,GAAKjK,QAAQ,QAAS,SAAUwL,GAC/C,MAAO,IAAMA,EAAEC,WAAW,GAAG5B,SAAS,IAAI6B,gBAO9C,QAASL,kBAAkBlB,GAKzB,IAAK,GAHD3J,GAAU,GAAIhD,OAAM2M,EAAO5H,QAGtBC,EAAI,EAAGA,EAAI2H,EAAO5H,OAAQC,IACR,gBAAd2H,GAAO3H,KAChBhC,EAAQgC,GAAK,GAAI7B,QAAO,OAASwJ,EAAO3H,GAAG9B,QAAU,MAIzD,OAAO,UAAUkL,EAAKC,GAMpB,IAAK,GALDxK,GAAO,GACPyK,EAAOF,MACP1P,EAAU2P,MACVE,EAAS7P,EAAQ8P,OAASV,yBAA2BW,mBAEhDzJ,EAAI,EAAGA,EAAI2H,EAAO5H,OAAQC,IAAK,CACtC,GAAI0J,GAAQ/B,EAAO3H,EAEnB,IAAqB,gBAAV0J,GAAX,CAMA,GACIC,GADAvL,EAAQkL,EAAKI,EAAMhO,KAGvB,IAAa,MAAT0C,EAAe,CACjB,GAAIsL,EAAMlB,SAAU,CAEdkB,EAAMpB,UACRzJ,GAAQ6K,EAAMzB,OAGhB,UAEA,KAAM,IAAI5M,WAAU,aAAeqO,EAAMhO,KAAO,mBAIpD,GAAIkO,QAAQxL,GAAZ,CACE,IAAKsL,EAAMnB,OACT,KAAM,IAAIlN,WAAU,aAAeqO,EAAMhO,KAAO,kCAAoCmO,KAAKC,UAAU1L,GAAS,IAG9G,IAAqB,IAAjBA,EAAM2B,OAAc,CACtB,GAAI2J,EAAMlB,SACR,QAEA,MAAM,IAAInN,WAAU,aAAeqO,EAAMhO,KAAO,qBAIpD,IAAK,GAAIqO,GAAI,EAAGA,EAAI3L,EAAM2B,OAAQgK,IAAK,CAGrC,GAFAJ,EAAUJ,EAAOnL,EAAM2L,KAElB/L,EAAQgC,GAAG3B,KAAKsL,GACnB,KAAM,IAAItO,WAAU,iBAAmBqO,EAAMhO,KAAO,eAAiBgO,EAAMxL,QAAU,oBAAsB2L,KAAKC,UAAUH,GAAW,IAGvI9K,KAAe,IAANkL,EAAUL,EAAMzB,OAASyB,EAAMjB,WAAakB,OApBzD,CA4BA,GAFAA,EAAUD,EAAMrB,SAAWc,eAAe/K,GAASmL,EAAOnL,IAErDJ,EAAQgC,GAAG3B,KAAKsL,GACnB,KAAM,IAAItO,WAAU,aAAeqO,EAAMhO,KAAO,eAAiBgO,EAAMxL,QAAU,oBAAsByL,EAAU,IAGnH9K,IAAQ6K,EAAMzB,OAAS0B,OArDrB9K,IAAQ6K,EAwDZ,MAAO7K,IAUX,QAASmL,cAAcvC,GACrB,MAAOA,GAAIjK,QAAQ,6BAA8B,QASnD,QAASkL,aAAaP,GACpB,MAAOA,GAAM3K,QAAQ,gBAAiB,QAUxC,QAASyM,YAAYC,EAAI3H,GAEvB,MADA2H,GAAG3H,KAAOA,EACH2H,EAST,QAASC,OAAOzQ,GACd,MAAOA,GAAQ0Q,UAAY,GAAK,IAUlC,QAASC,gBAAgBxL,EAAM0D,GAE7B,GAAI+H,GAASzL,EAAKE,OAAO9C,MAAM,YAE/B,IAAIqO,EACF,IAAK,GAAItK,GAAI,EAAGA,EAAIsK,EAAOvK,OAAQC,IACjCuC,EAAKjE,MACH5C,KAAMsE,EACNiI,OAAQ,KACRQ,UAAW,KACXD,UAAU,EACVD,QAAQ,EACRD,SAAS,EACTD,UAAU,EACVnK,QAAS,MAKf,OAAO+L,YAAWpL,EAAM0D,GAW1B,QAASgI,eAAe1L,EAAM0D,EAAM7I,GAGlC,IAAK,GAFD8Q,MAEKxK,EAAI,EAAGA,EAAInB,EAAKkB,OAAQC,IAC/BwK,EAAMlM,KAAKmM,aAAa5L,EAAKmB,GAAIuC,EAAM7I,GAASqF,OAGlD,IAAIQ,GAAS,GAAIpB,QAAO,MAAQqM,EAAM3O,KAAK,KAAO,IAAKsO,MAAMzQ,GAE7D,OAAOuQ,YAAW1K,EAAQgD,GAW5B,QAASmI,gBAAgB7L,EAAM0D,EAAM7I,GAKnC,IAAK,GAJDiO,GAASH,MAAM3I,GACfqL,EAAKS,eAAehD,EAAQjO,GAGvBsG,EAAI,EAAGA,EAAI2H,EAAO5H,OAAQC,IACR,gBAAd2H,GAAO3H,IAChBuC,EAAKjE,KAAKqJ,EAAO3H,GAIrB,OAAOiK,YAAWC,EAAI3H,GAUxB,QAASoI,gBAAgBhD,EAAQjO,GAC/BA,EAAUA,KASV,KAAK,GAPDkR,GAASlR,EAAQkR,OACjBC,EAAMnR,EAAQmR,OAAQ,EACtB5L,EAAQ,GACR6L,EAAYnD,EAAOA,EAAO5H,OAAS,GACnCgL,EAAqC,gBAAdD,IAA0B,MAAMzM,KAAKyM,GAGvD9K,EAAI,EAAGA,EAAI2H,EAAO5H,OAAQC,IAAK,CACtC,GAAI0J,GAAQ/B,EAAO3H,EAEnB,IAAqB,gBAAV0J,GACTzK,GAAS+K,aAAaN,OACjB,CACL,GAAIzB,GAAS+B,aAAaN,EAAMzB,QAC5BC,EAAU,MAAQwB,EAAMxL,QAAU,GAElCwL,GAAMnB,SACRL,GAAW,MAAQD,EAASC,EAAU,MAOpCA,EAJAwB,EAAMlB,SACHkB,EAAMpB,QAGCL,EAAS,IAAMC,EAAU,KAFzB,MAAQD,EAAS,IAAMC,EAAU,MAKnCD,EAAS,IAAMC,EAAU,IAGrCjJ,GAASiJ,GAoBb,MAZK0C,KACH3L,GAAS8L,EAAgB9L,EAAM+I,MAAM,GAAG,GAAM/I,GAAS,iBAIvDA,GADE4L,EACO,IAIAD,GAAUG,EAAgB,GAAK,YAGnC,GAAI5M,QAAO,IAAMc,EAAOkL,MAAMzQ,IAevC,QAAS+Q,cAAc5L,EAAM0D,EAAM7I,GAUjC,MATA6I,GAAOA,MAEFqH,QAAQrH,GAGD7I,IACVA,OAHAA,EAAiC,EACjC6I,MAKE1D,YAAgBV,QACXkM,eAAexL,EAA4B,GAGhD+K,QAAQ/K,GACH0L,cAAoC,EAA8B,EAAQ7Q,GAG5EgR,eAAqC,EAA8B,EAAQhR,GAxapF,GAAIkQ,SAAUrP,QAAQ,UAKtB+B,QAAOC,QAAUkO,aACjBnO,OAAOC,QAAQiL,MAAQA,MACvBlL,OAAOC,QAAQqM,QAAUA,QACzBtM,OAAOC,QAAQsM,iBAAmBA,iBAClCvM,OAAOC,QAAQoO,eAAiBA,cAOhC,IAAI/C,aAAc,GAAIzJ,SAGpB,UAOA,0GACAtC,KAAK,KAAM;;CNVZ,WACC,GAAIwJ,GAAeC,MAAM1G,UAAU9C,OAC/ByJ,EAAYC,UAAUD,UAAUtJ,MAAM,4BAG1C,IAAIsJ,EACF,GAAIE,GAAQF,EAAU,GAClBG,EAAUC,SAASJ,EAAU,GAIjCF,MAAkBE,GACL,YAAVE,GAAuBC,GAAW,IACxB,WAAVD,GAAuBC,GAAW,MAMvCJ,MAAM1G,UAAU9C,OAAS,SAAgB0G,GAIvC,QAASoD,GAAa1F,GACpB1B,KAAK9C,KAAO,eACZ8C,KAAKqH,KAAO,GACZrH,KAAK0B,QAAUA,EANjB,GAAI1G,GAAQgF,IAWZ,OAFAoH,GAAahH,UAAYkH,OAAOC,OAAOC,MAAMpH,WAEtCzE,QAAQ8I,UAAUpJ,KAAK,WAC5B,GAAIoM,UAAUlG,OAAS,EAAG,KAAM,IAAI1E,UAcpC,OATAmH,GAAWA,EAAS7E,IAAI,SAASzB,GAC/B,MAAIA,aAAmBd,SACdc,EAGAgK,OAAOhK,KAIX/B,QAAQyB,IACb4G,EAAS7E,IAAI,SAASzB,GACG,gBAAZA,KACTA,EAAU,GAAId,SAAQc,GAGxB,IAAIiK,GAAS,GAAIpJ,KAAIb,EAAQzC,KAAK2M,QAElC,IAAe,UAAXD,GAAiC,WAAXA,EACxB,KAAM,IAAIP,GAAa,iBAGzB,OAAOjF,OAAMzE,EAAQ0E,cAGxB/G,KAAK,SAASwM,GAGf,GAAIA,EAAUC,KAAK,SAASzF,GAC1B,OAAQA,EAAS0F,KAEjB,KAAM,IAAIX,GAAa,4BAKzB,OAAOzL,SAAQyB,IACbyK,EAAU1I,IAAI,SAASkD,EAAUb,GAC/B,MAAOxG,GAAMuH,IAAIyB,EAASxC,GAAIa,QAGjChH,KAAK,eAKVyL,MAAM1G,UAAU9E,IAAM,SAAaoC,GACjC,MAAOsC,MAAK1C,QAAQI","file":"bundle.js","sourcesContent":["(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 0) {\n return routes[0].makeHandler(pathOrUrl);\n }\n }\n }\n\n return null;\n};\n\nRouter.prototype.match = function(request) {\n return this.matchMethod(request.method, request.url) ||\n this.matchMethod('any', request.url);\n};\n\nmodule.exports = new Router();\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\nvar globalOptions = require('./options');\nvar idbCacheExpiration = require('./idb-cache-expiration');\n\nfunction debug(message, options) {\n options = options || {};\n var flag = options.debug || globalOptions.debug;\n if (flag) {\n console.log('[sw-toolbox] ' + message);\n }\n}\n\nfunction openCache(options) {\n var cacheName;\n if (options && options.cache) {\n cacheName = options.cache.name;\n }\n cacheName = cacheName || globalOptions.cache.name;\n\n return caches.open(cacheName);\n}\n\nfunction fetchAndCache(request, options) {\n options = options || {};\n var successResponses = options.successResponses ||\n globalOptions.successResponses;\n\n return fetch(request.clone()).then(function(response) {\n // Only cache GET requests with successful responses.\n // Since this is not part of the promise chain, it will be done\n // asynchronously and will not block the response from being returned to the\n // page.\n if (request.method === 'GET' && successResponses.test(response.status)) {\n openCache(options).then(function(cache) {\n cache.put(request, response).then(function() {\n // If any of the options are provided in options.cache then use them.\n // Do not fallback to the global options for any that are missing\n // unless they are all missing.\n var cacheOptions = options.cache || globalOptions.cache;\n\n // Only run the cache expiration logic if at least one of the maximums\n // is set, and if we have a name for the cache that the options are\n // being applied to.\n if ((cacheOptions.maxEntries || cacheOptions.maxAgeSeconds) &&\n cacheOptions.name) {\n queueCacheExpiration(request, cache, cacheOptions);\n }\n });\n });\n }\n\n return response.clone();\n });\n}\n\nvar cleanupQueue;\nfunction queueCacheExpiration(request, cache, cacheOptions) {\n var cleanup = cleanupCache.bind(null, request, cache, cacheOptions);\n\n if (cleanupQueue) {\n cleanupQueue = cleanupQueue.then(cleanup);\n } else {\n cleanupQueue = cleanup();\n }\n}\n\nfunction cleanupCache(request, cache, cacheOptions) {\n var requestUrl = request.url;\n var maxAgeSeconds = cacheOptions.maxAgeSeconds;\n var maxEntries = cacheOptions.maxEntries;\n var cacheName = cacheOptions.name;\n\n var now = Date.now();\n debug('Updating LRU order for ' + requestUrl + '. Max entries is ' +\n maxEntries + ', max age is ' + maxAgeSeconds);\n\n return idbCacheExpiration.getDb(cacheName).then(function(db) {\n return idbCacheExpiration.setTimestampForUrl(db, requestUrl, now);\n }).then(function(db) {\n return idbCacheExpiration.expireEntries(db, maxEntries, maxAgeSeconds, now);\n }).then(function(urlsToDelete) {\n debug('Successfully updated IDB.');\n\n var deletionPromises = urlsToDelete.map(function(urlToDelete) {\n return cache.delete(urlToDelete);\n });\n\n return Promise.all(deletionPromises).then(function() {\n debug('Done with cache cleanup.');\n });\n }).catch(function(error) {\n debug(error);\n });\n}\n\nfunction renameCache(source, destination, options) {\n debug('Renaming cache: [' + source + '] to [' + destination + ']', options);\n return caches.delete(destination).then(function() {\n return Promise.all([\n caches.open(source),\n caches.open(destination)\n ]).then(function(results) {\n var sourceCache = results[0];\n var destCache = results[1];\n\n return sourceCache.keys().then(function(requests) {\n return Promise.all(requests.map(function(request) {\n return sourceCache.match(request).then(function(response) {\n return destCache.put(request, response);\n });\n }));\n }).then(function() {\n return caches.delete(source);\n });\n });\n });\n}\n\nmodule.exports = {\n debug: debug,\n fetchAndCache: fetchAndCache,\n openCache: openCache,\n renameCache: renameCache\n};\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\nmodule.exports = {\n networkOnly: require('./networkOnly'),\n networkFirst: require('./networkFirst'),\n cacheOnly: require('./cacheOnly'),\n cacheFirst: require('./cacheFirst'),\n fastest: require('./fastest')\n};\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\n// TODO: Use self.registration.scope instead of self.location\nvar url = new URL('./', self.location);\nvar basePath = url.pathname;\nvar pathRegexp = require('path-to-regexp');\n\nvar Route = function(method, path, handler, options) {\n if (path instanceof RegExp) {\n this.fullUrlRegExp = path;\n } else {\n // The URL() constructor can't parse express-style routes as they are not\n // valid urls. This means we have to manually manipulate relative urls into\n // absolute ones. This check is extremely naive but implementing a tweaked\n // version of the full algorithm seems like overkill\n // (https://url.spec.whatwg.org/#concept-basic-url-parser)\n if (path.indexOf('/') !== 0) {\n path = basePath + path;\n }\n\n this.keys = [];\n this.regexp = pathRegexp(path, this.keys);\n }\n\n this.method = method;\n this.options = options;\n this.handler = handler;\n};\n\nRoute.prototype.makeHandler = function(url) {\n var values;\n if (this.regexp) {\n var match = this.regexp.exec(url);\n values = {};\n this.keys.forEach(function(key, index) {\n values[key.name] = match[index + 1];\n });\n }\n\n return function(request) {\n return this.handler(request, values, this.options);\n }.bind(this);\n};\n\nmodule.exports = Route;\n","/*\n Copyright 2015 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\nvar DB_PREFIX = 'sw-toolbox-';\nvar DB_VERSION = 1;\nvar STORE_NAME = 'store';\nvar URL_PROPERTY = 'url';\nvar TIMESTAMP_PROPERTY = 'timestamp';\nvar cacheNameToDbPromise = {};\n\nfunction openDb(cacheName) {\n return new Promise(function(resolve, reject) {\n var request = indexedDB.open(DB_PREFIX + cacheName, DB_VERSION);\n\n request.onupgradeneeded = function() {\n var objectStore = request.result.createObjectStore(STORE_NAME,\n {keyPath: URL_PROPERTY});\n objectStore.createIndex(TIMESTAMP_PROPERTY, TIMESTAMP_PROPERTY,\n {unique: false});\n };\n\n request.onsuccess = function() {\n resolve(request.result);\n };\n\n request.onerror = function() {\n reject(request.error);\n };\n });\n}\n\nfunction getDb(cacheName) {\n if (!(cacheName in cacheNameToDbPromise)) {\n cacheNameToDbPromise[cacheName] = openDb(cacheName);\n }\n\n return cacheNameToDbPromise[cacheName];\n}\n\nfunction setTimestampForUrl(db, url, now) {\n return new Promise(function(resolve, reject) {\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n objectStore.put({url: url, timestamp: now});\n\n transaction.oncomplete = function() {\n resolve(db);\n };\n\n transaction.onabort = function() {\n reject(transaction.error);\n };\n });\n}\n\nfunction expireOldEntries(db, maxAgeSeconds, now) {\n // Bail out early by resolving with an empty array if we're not using\n // maxAgeSeconds.\n if (!maxAgeSeconds) {\n return Promise.resolve([]);\n }\n\n return new Promise(function(resolve, reject) {\n var maxAgeMillis = maxAgeSeconds * 1000;\n var urls = [];\n\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n var index = objectStore.index(TIMESTAMP_PROPERTY);\n\n index.openCursor().onsuccess = function(cursorEvent) {\n var cursor = cursorEvent.target.result;\n if (cursor) {\n if (now - maxAgeMillis > cursor.value[TIMESTAMP_PROPERTY]) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n cursor.continue();\n }\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireExtraEntries(db, maxEntries) {\n // Bail out early by resolving with an empty array if we're not using\n // maxEntries.\n if (!maxEntries) {\n return Promise.resolve([]);\n }\n\n return new Promise(function(resolve, reject) {\n var urls = [];\n\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n var index = objectStore.index(TIMESTAMP_PROPERTY);\n\n var countRequest = index.count();\n index.count().onsuccess = function() {\n var initialCount = countRequest.result;\n\n if (initialCount > maxEntries) {\n index.openCursor().onsuccess = function(cursorEvent) {\n var cursor = cursorEvent.target.result;\n if (cursor) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n if (initialCount - urls.length > maxEntries) {\n cursor.continue();\n }\n }\n };\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireEntries(db, maxEntries, maxAgeSeconds, now) {\n return expireOldEntries(db, maxAgeSeconds, now).then(function(oldUrls) {\n return expireExtraEntries(db, maxEntries).then(function(extraUrls) {\n return oldUrls.concat(extraUrls);\n });\n });\n}\n\nmodule.exports = {\n getDb: getDb,\n setTimestampForUrl: setTimestampForUrl,\n expireEntries: expireEntries\n};\n","/**\n * Copyright 2015 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n(function() {\n var nativeAddAll = Cache.prototype.addAll;\n var userAgent = navigator.userAgent.match(/(Firefox|Chrome)\\/(\\d+\\.)/);\n\n // Has nice behavior of `var` which everyone hates\n if (userAgent) {\n var agent = userAgent[1];\n var version = parseInt(userAgent[2]);\n }\n\n if (\n nativeAddAll && (!userAgent ||\n (agent === 'Firefox' && version >= 46) ||\n (agent === 'Chrome' && version >= 50)\n )\n ) {\n return;\n }\n\n Cache.prototype.addAll = function addAll(requests) {\n var cache = this;\n\n // Since DOMExceptions are not constructable:\n function NetworkError(message) {\n this.name = 'NetworkError';\n this.code = 19;\n this.message = message;\n }\n\n NetworkError.prototype = Object.create(Error.prototype);\n\n return Promise.resolve().then(function() {\n if (arguments.length < 1) throw new TypeError();\n\n // Simulate sequence<(Request or USVString)> binding:\n var sequence = [];\n\n requests = requests.map(function(request) {\n if (request instanceof Request) {\n return request;\n }\n else {\n return String(request); // may throw TypeError\n }\n });\n\n return Promise.all(\n requests.map(function(request) {\n if (typeof request === 'string') {\n request = new Request(request);\n }\n\n var scheme = new URL(request.url).protocol;\n\n if (scheme !== 'http:' && scheme !== 'https:') {\n throw new NetworkError(\"Invalid scheme\");\n }\n\n return fetch(request.clone());\n })\n );\n }).then(function(responses) {\n // If some of the responses has not OK-eish status,\n // then whole operation should reject\n if (responses.some(function(response) {\n return !response.ok;\n })) {\n throw new NetworkError('Incorrect response status');\n }\n\n // TODO: check that requests don't overwrite one another\n // (don't think this is possible to polyfill due to opaque responses)\n return Promise.all(\n responses.map(function(response, i) {\n return cache.put(requests[i], response);\n })\n );\n }).then(function() {\n return undefined;\n });\n };\n\n Cache.prototype.add = function add(request) {\n return this.addAll([request]);\n };\n}());","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction networkOnly(request, values, options) {\n helpers.debug('Strategy: network only [' + request.url + ']', options);\n return fetch(request);\n}\n\nmodule.exports = networkOnly;\n","/*\n Copyright 2015 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar globalOptions = require('../options');\nvar helpers = require('../helpers');\n\nfunction networkFirst(request, values, options) {\n options = options || {};\n var successResponses = options.successResponses ||\n globalOptions.successResponses;\n // This will bypass options.networkTimeout if it's set to a false-y value like\n // 0, but that's the sane thing to do anyway.\n var networkTimeoutSeconds = options.networkTimeoutSeconds ||\n globalOptions.networkTimeoutSeconds;\n helpers.debug('Strategy: network first [' + request.url + ']', options);\n\n return helpers.openCache(options).then(function(cache) {\n var timeoutId;\n var promises = [];\n var originalResponse;\n\n if (networkTimeoutSeconds) {\n var cacheWhenTimedOutPromise = new Promise(function(resolve) {\n timeoutId = setTimeout(function() {\n cache.match(request).then(function(response) {\n if (response) {\n // Only resolve this promise if there's a valid response in the\n // cache. This ensures that we won't time out a network request\n // unless there's a cached entry to fallback on, which is arguably\n // the preferable behavior.\n resolve(response);\n }\n });\n }, networkTimeoutSeconds * 1000);\n });\n promises.push(cacheWhenTimedOutPromise);\n }\n\n var networkPromise = helpers.fetchAndCache(request, options)\n .then(function(response) {\n // We've got a response, so clear the network timeout if there is one.\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (successResponses.test(response.status)) {\n return response;\n }\n\n helpers.debug('Response was an HTTP error: ' + response.statusText,\n options);\n originalResponse = response;\n throw new Error('Bad response');\n }).catch(function(error) {\n helpers.debug('Network or response error, fallback to cache [' +\n request.url + ']', options);\n return cache.match(request).then(function(response) {\n // If there's a match in the cache, resolve with that.\n if (response) {\n return response;\n }\n\n // If we have a Response object from the previous fetch, then resolve\n // with that, even though it corresponds to an error status code.\n if (originalResponse) {\n return originalResponse;\n }\n\n // If we don't have a Response object from the previous fetch, likely\n // due to a network failure, then reject with the failure error.\n throw error;\n });\n });\n\n promises.push(networkPromise);\n\n return Promise.race(promises);\n });\n}\n\nmodule.exports = networkFirst;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheOnly(request, values, options) {\n helpers.debug('Strategy: cache only [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request);\n });\n}\n\nmodule.exports = cacheOnly;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheFirst(request, values, options) {\n helpers.debug('Strategy: cache first [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request).then(function(response) {\n if (response) {\n return response;\n }\n\n return helpers.fetchAndCache(request, options);\n });\n });\n}\n\nmodule.exports = cacheFirst;\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\nvar cacheOnly = require('./cacheOnly');\n\nfunction fastest(request, values, options) {\n helpers.debug('Strategy: fastest [' + request.url + ']', options);\n\n return new Promise(function(resolve, reject) {\n var rejected = false;\n var reasons = [];\n\n var maybeReject = function(reason) {\n reasons.push(reason.toString());\n if (rejected) {\n reject(new Error('Both cache and network failed: \"' +\n reasons.join('\", \"') + '\"'));\n } else {\n rejected = true;\n }\n };\n\n var maybeResolve = function(result) {\n if (result instanceof Response) {\n resolve(result);\n } else {\n maybeReject('No result returned');\n }\n };\n\n helpers.fetchAndCache(request.clone(), options)\n .then(maybeResolve, maybeReject);\n\n cacheOnly(request, values, options)\n .then(maybeResolve, maybeReject);\n });\n}\n\nmodule.exports = fastest;\n","var isarray = require('isarray')\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @return {!Array}\n */\nfunction parse (str) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || '/'\n var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?')\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: escapeGroup(pattern)\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str) {\n return tokensToFunction(parse(str))\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n var tokens = parse(path)\n var re = tokensToRegExp(tokens, options)\n\n // Attach keys back to the regexp.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] !== 'string') {\n keys.push(tokens[i])\n }\n }\n\n return attachKeys(re, keys)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, options) {\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n var lastToken = tokens[tokens.length - 1]\n var endsWithSlash = typeof lastToken === 'string' && /\\/$/.test(lastToken)\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\\\/(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithSlash ? '' : '(?=\\\\/|$)'\n }\n\n return new RegExp('^' + route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n keys = keys || []\n\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys)\n keys = []\n } else if (!options) {\n options = {}\n }\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\n}\n","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n"]} \ No newline at end of file diff --git a/package.json b/package.json index 3b1c2161..45f39c0f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "polymer-cdn", - "version": "1.6.1", + "version": "1.7.0", "description": "A mirror of Polymer so it can be used from CDN.", "keywords": ["polymer", "cdn"], "homepage": "https://github.com/download/polymer-cdn",