├── .gitignore ├── .jshintrc ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── bin ├── dev-server.js ├── run-test.sh └── test-browser.js ├── bower.json ├── dist ├── pouchdb.all-dbs.js └── pouchdb.all-dbs.min.js ├── lib ├── index.js ├── pouch-utils.js └── taskqueue.js ├── package.json └── test ├── bind-polyfill.js ├── index.html ├── test.js └── webrunner.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | *~ 4 | coverage 5 | test/test-bundle.js 6 | npm-debug.log 7 | dist 8 | .nyc_output -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "immed": true, 5 | "newcap": true, 6 | "noarg": true, 7 | "sub": true, 8 | "undef": true, 9 | "unused": true, 10 | "eqnull": true, 11 | "browser": true, 12 | "node": true, 13 | "strict": true, 14 | "globalstrict": true, 15 | "globals": { "Pouch": true}, 16 | "white": true, 17 | "indent": 2, 18 | "maxlen": 100, 19 | "predef": [ 20 | "process", 21 | "global", 22 | "require", 23 | "console", 24 | "describe", 25 | "beforeEach", 26 | "afterEach", 27 | "it", 28 | "emit" 29 | ] 30 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .git* 2 | node_modules 3 | .DS_Store 4 | *~ 5 | coverage 6 | npm-debug.log 7 | vendor/ 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | services: 4 | - couchdb 5 | 6 | node_js: 7 | - "14" 8 | sudo: false 9 | script: npm run $COMMAND 10 | before_script: 11 | - curl -X PUT localhost:5984/test 12 | 13 | env: 14 | matrix: 15 | - COMMAND=test 16 | - CLIENT=selenium:phantomjs COMMAND=test 17 | - COMMAND=coverage 18 | 19 | branches: 20 | only: 21 | - master 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PouchDB allDbs() plugin 2 | ===== 3 | 4 | [![Build Status](https://travis-ci.org/nolanlawson/pouchdb-all-dbs.svg)](https://travis-ci.org/nolanlawson/pouchdb-all-dbs) 5 | 6 | This plugin exposes the `PouchDB.allDbs()` function, which you can use to list all local databases. It works by listening for `PouchDB.on('created')` and `PouchDB.on('destroyed')` events, and maintaining a separate database to store the names of those databases. 7 | 8 | **Note**: `allDbs()` used to be part of PouchDB core (enabled using `PouchDB.enableAllDbs = true`). It was deprecated in PouchDB 2.0.0, and now lives on as a plugin. 9 | 10 | Usage 11 | ----- 12 | 13 | ### In the browser 14 | 15 | To use this plugin, include it after `pouchdb.js` in your HTML page: 16 | 17 | ```html 18 | 19 | 20 | ``` 21 | 22 | This plugin is also available from Bower: 23 | 24 | ``` 25 | bower install pouchdb-all-dbs 26 | ``` 27 | 28 | Merely including it as a script tag will work, assuming you also used a script tag for PouchDB. 29 | 30 | ### In Node/Browserify/Webpack/etc. 31 | 32 | First, npm install it: 33 | 34 | ``` 35 | npm install pouchdb-all-dbs 36 | ``` 37 | 38 | And then do this: 39 | 40 | ```js 41 | var PouchDB = require('pouchdb'); 42 | require('pouchdb-all-dbs')(PouchDB); 43 | ``` 44 | 45 | API 46 | ----- 47 | 48 | #### PouchDB.allDbs([callback]) 49 | 50 | Returns a list of all non-deleted databases. Example usage as a promise: 51 | 52 | ```js 53 | PouchDB.allDbs().then(function (dbs) { 54 | // dbs is an array of strings, e.g. ['mydb1', 'mydb2'] 55 | }).catch(function (err) { 56 | // handle err 57 | }); 58 | ``` 59 | 60 | Or if you like callbacks, you can use that style instead: 61 | 62 | ```js 63 | PouchDB.allDbs(function (err, dbs) { 64 | if (err) { 65 | // handle err 66 | } 67 | // dbs is an array of strings, e.g. ['mydb1', 'mydb2'] 68 | }); 69 | ``` 70 | 71 | #### PouchDB.resetAllDbs([callback]) 72 | 73 | Destroys the separate allDbs database. You should never need to call this function; I just use it for the unit tests. 74 | 75 | Example usage: 76 | 77 | ```js 78 | PouchDB.resetAllDbs().then(function () { 79 | // allDbs store is now destroyed 80 | }).catch(function (err) { 81 | // handle err 82 | }); 83 | ``` 84 | 85 | Building 86 | ---- 87 | npm install 88 | npm run build 89 | 90 | Testing 91 | ---- 92 | 93 | ### In Node 94 | 95 | This will run the tests in Node using LevelDB: 96 | 97 | npm test 98 | 99 | You can also check for 100% code coverage using: 100 | 101 | npm run coverage 102 | 103 | 104 | If you have mocha installed globally you can run single test with: 105 | ``` 106 | TEST_DB=local mocha --reporter spec --grep search_phrase 107 | ``` 108 | 109 | The `TEST_DB` environment variable specifies the database that PouchDB should use (see `package.json`). 110 | 111 | ### In the browser 112 | 113 | Run `npm run dev` and then point your favorite browser to [http://127.0.0.1:8001/test/index.html](http://127.0.0.1:8001/test/index.html). 114 | 115 | The query param `?grep=mysearch` will search for tests matching `mysearch`. 116 | 117 | ### Automated browser tests 118 | 119 | You can run e.g. 120 | 121 | CLIENT=selenium:firefox npm test 122 | CLIENT=selenium:phantomjs npm test 123 | 124 | This will run the tests automatically and the process will exit with a 0 or a 1 when it's done. Firefox uses IndexedDB, and PhantomJS uses WebSQL. 125 | -------------------------------------------------------------------------------- /bin/dev-server.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | var COUCH_HOST = process.env.COUCH_HOST || 'http://127.0.0.1:5984'; 6 | var HTTP_PORT = 8001; 7 | 8 | var Promise = require('bluebird'); 9 | var request = require('request'); 10 | var http_server = require("http-server"); 11 | var fs = require('fs'); 12 | var indexfile = "./test/test.js"; 13 | var dotfile = "./test/.test-bundle.js"; 14 | var outfile = "./test/test-bundle.js"; 15 | var watchify = require("watchify"); 16 | var browserify = require('browserify'); 17 | var w = watchify(browserify(indexfile, { 18 | cache: {}, 19 | packageCache: {}, 20 | fullPaths: true, 21 | debug: true 22 | })); 23 | 24 | w.on('update', bundle); 25 | bundle(); 26 | 27 | var filesWritten = false; 28 | var serverStarted = false; 29 | var readyCallback; 30 | 31 | function bundle() { 32 | var wb = w.bundle(); 33 | wb.on('error', function (err) { 34 | console.error(String(err)); 35 | }); 36 | wb.on("end", end); 37 | wb.pipe(fs.createWriteStream(dotfile)); 38 | 39 | function end() { 40 | fs.rename(dotfile, outfile, function (err) { 41 | if (err) { return console.error(err); } 42 | console.log('Updated:', outfile); 43 | filesWritten = true; 44 | checkReady(); 45 | }); 46 | } 47 | } 48 | 49 | function startServers(callback) { 50 | readyCallback = callback; 51 | // enable CORS globally, because it's easier this way 52 | 53 | var corsValues = { 54 | '/_config/httpd/enable_cors': 'true', 55 | '/_config/cors/origins': '*', 56 | '/_config/cors/credentials': 'true', 57 | '/_config/cors/methods': 'PROPFIND, PROPPATCH, COPY, MOVE, DELETE, ' + 58 | 'MKCOL, LOCK, UNLOCK, PUT, GETLIB, VERSION-CONTROL, CHECKIN, ' + 59 | 'CHECKOUT, UNCHECKOUT, REPORT, UPDATE, CANCELUPLOAD, HEAD, ' + 60 | 'OPTIONS, GET, POST', 61 | '/_config/cors/headers': 62 | 'Cache-Control, Content-Type, Depth, Destination, ' + 63 | 'If-Modified-Since, Overwrite, User-Agent, X-File-Name, ' + 64 | 'X-File-Size, X-Requested-With, accept, accept-encoding, ' + 65 | 'accept-language, authorization, content-type, origin, referer' 66 | }; 67 | 68 | Promise.all(Object.keys(corsValues).map(function (key) { 69 | var value = corsValues[key]; 70 | return request({ 71 | method: 'put', 72 | url: COUCH_HOST + key, 73 | body: JSON.stringify(value) 74 | }); 75 | })).then(function () { 76 | return http_server.createServer().listen(HTTP_PORT); 77 | }).then(function () { 78 | console.log('Tests: http://127.0.0.1:' + HTTP_PORT + '/test/index.html'); 79 | serverStarted = true; 80 | checkReady(); 81 | }).catch(function (err) { 82 | if (err) { 83 | console.log(err); 84 | process.exit(1); 85 | } 86 | }); 87 | } 88 | 89 | function checkReady() { 90 | if (filesWritten && serverStarted && readyCallback) { 91 | readyCallback(); 92 | } 93 | } 94 | 95 | if (require.main === module) { 96 | startServers(); 97 | } else { 98 | module.exports.start = startServers; 99 | } 100 | -------------------------------------------------------------------------------- /bin/run-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | : ${CLIENT:="node"} 4 | 5 | if [ "$CLIENT" == "node" ]; then 6 | npm run test-node 7 | else 8 | npm run test-browser 9 | fi 10 | -------------------------------------------------------------------------------- /bin/test-browser.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 'use strict'; 3 | 4 | var wd = require('wd'); 5 | var sauceConnectLauncher = require('sauce-connect-launcher'); 6 | var selenium = require('selenium-standalone'); 7 | var querystring = require("querystring"); 8 | 9 | var devserver = require('./dev-server.js'); 10 | 11 | var testTimeout = 30 * 60 * 1000; 12 | 13 | var username = process.env.SAUCE_USERNAME; 14 | var accessKey = process.env.SAUCE_ACCESS_KEY; 15 | 16 | // process.env.CLIENT is a colon seperated list of 17 | // (saucelabs|selenium):browserName:browserVerion:platform 18 | var tmp = (process.env.CLIENT || 'selenium:firefox').split(':'); 19 | var client = { 20 | runner: tmp[0] || 'selenium', 21 | browser: tmp[1] || 'firefox', 22 | version: tmp[2] || null, // Latest 23 | platform: tmp[3] || null 24 | }; 25 | 26 | var testUrl = 'http://127.0.0.1:8001/test/index.html'; 27 | var qs = {}; 28 | 29 | var sauceClient; 30 | var sauceConnectProcess; 31 | var tunnelId = process.env.TRAVIS_JOB_NUMBER || 'tunnel-' + Date.now(); 32 | 33 | if (client.runner === 'saucelabs') { 34 | qs.saucelabs = true; 35 | } 36 | if (process.env.GREP) { 37 | qs.grep = process.env.GREP; 38 | } 39 | if (process.env.ADAPTERS) { 40 | qs.adapters = process.env.ADAPTERS; 41 | } 42 | if (process.env.ES5_SHIM || process.env.ES5_SHIMS) { 43 | qs.es5shim = true; 44 | } 45 | testUrl += '?'; 46 | testUrl += querystring.stringify(qs); 47 | 48 | if (process.env.TRAVIS && 49 | client.browser !== 'firefox' && 50 | client.browser !== 'phantomjs' && 51 | process.env.TRAVIS_SECURE_ENV_VARS === 'false') { 52 | console.error('Not running test, cannot connect to saucelabs'); 53 | process.exit(1); 54 | return; 55 | } 56 | 57 | function testError(e) { 58 | console.error(e); 59 | console.error('Doh, tests failed'); 60 | sauceClient.quit(); 61 | process.exit(3); 62 | } 63 | 64 | function postResult(result) { 65 | process.exit(!process.env.PERF && result.failed ? 1 : 0); 66 | } 67 | 68 | function testComplete(result) { 69 | console.log(result); 70 | 71 | sauceClient.quit().then(function () { 72 | if (sauceConnectProcess) { 73 | sauceConnectProcess.close(function () { 74 | postResult(result); 75 | }); 76 | } else { 77 | postResult(result); 78 | } 79 | }); 80 | } 81 | 82 | function startSelenium(callback) { 83 | // Start selenium 84 | var opts = {version: '2.42.0'}; 85 | selenium.install(opts, function(err) { 86 | if (err) { 87 | console.error('Failed to install selenium'); 88 | process.exit(1); 89 | } 90 | selenium.start(opts, function(err, server) { 91 | sauceClient = wd.promiseChainRemote(); 92 | callback(); 93 | }); 94 | }); 95 | } 96 | 97 | function startSauceConnect(callback) { 98 | 99 | var options = { 100 | username: username, 101 | accessKey: accessKey, 102 | tunnelIdentifier: tunnelId 103 | }; 104 | 105 | sauceConnectLauncher(options, function (err, process) { 106 | if (err) { 107 | console.error('Failed to connect to saucelabs'); 108 | console.error(err); 109 | return process.exit(1); 110 | } 111 | sauceConnectProcess = process; 112 | sauceClient = wd.promiseChainRemote("localhost", 4445, username, accessKey); 113 | callback(); 114 | }); 115 | } 116 | 117 | function startTest() { 118 | 119 | console.log('Starting', client); 120 | 121 | var opts = { 122 | browserName: client.browser, 123 | version: client.version, 124 | platform: client.platform, 125 | tunnelTimeout: testTimeout, 126 | name: client.browser + ' - ' + tunnelId, 127 | 'max-duration': 60 * 30, 128 | 'command-timeout': 599, 129 | 'idle-timeout': 599, 130 | 'tunnel-identifier': tunnelId 131 | }; 132 | 133 | sauceClient.init(opts).get(testUrl, function () { 134 | 135 | /* jshint evil: true */ 136 | var interval = setInterval(function () { 137 | sauceClient.eval('window.results', function (err, results) { 138 | if (err) { 139 | clearInterval(interval); 140 | testError(err); 141 | } else if (results.completed || results.failures.length) { 142 | clearInterval(interval); 143 | testComplete(results); 144 | } else { 145 | console.log('=> ', results); 146 | } 147 | }); 148 | }, 10 * 1000); 149 | }); 150 | } 151 | 152 | devserver.start(function () { 153 | if (client.runner === 'saucelabs') { 154 | startSauceConnect(startTest); 155 | } else { 156 | startSelenium(startTest); 157 | } 158 | }); 159 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pouchdb-all-dbs", 3 | "version": "1.0.1", 4 | "description": "allDbs() plugin for PouchDB", 5 | "main": "dist/pouchdb.all-dbs.js", 6 | "homepage": "https://github.com/nolanlawson/pouchdb-all-dbs", 7 | "authors": [ 8 | "Nolan Lawson " 9 | ], 10 | "moduleType": [ 11 | "node" 12 | ], 13 | "keywords": [ 14 | "pouchdb", 15 | "couchdb", 16 | "alldbs", 17 | "plugin" 18 | ], 19 | "license": "Apache 2", 20 | "ignore": [ 21 | "**/.*", 22 | "node_modules", 23 | "bower_components", 24 | "test", 25 | "tests", 26 | "vendor" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /dist/pouchdb.all-dbs.js: -------------------------------------------------------------------------------- 1 | (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 element; its readystatechange event will be fired asynchronously once it is inserted 171 | // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. 172 | var scriptEl = global.document.createElement('script'); 173 | scriptEl.onreadystatechange = function () { 174 | nextTick(); 175 | 176 | scriptEl.onreadystatechange = null; 177 | scriptEl.parentNode.removeChild(scriptEl); 178 | scriptEl = null; 179 | }; 180 | global.document.documentElement.appendChild(scriptEl); 181 | }; 182 | } else { 183 | scheduleDrain = function () { 184 | setTimeout(nextTick, 0); 185 | }; 186 | } 187 | } 188 | 189 | var draining; 190 | var queue = []; 191 | //named nextTick for less confusing stack traces 192 | function nextTick() { 193 | draining = true; 194 | var i, oldQueue; 195 | var len = queue.length; 196 | while (len) { 197 | oldQueue = queue; 198 | queue = []; 199 | i = -1; 200 | while (++i < len) { 201 | oldQueue[i](); 202 | } 203 | len = queue.length; 204 | } 205 | draining = false; 206 | } 207 | 208 | module.exports = immediate; 209 | function immediate(task) { 210 | if (queue.push(task) === 1 && !draining) { 211 | scheduleDrain(); 212 | } 213 | } 214 | 215 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 216 | },{}],5:[function(require,module,exports){ 217 | if (typeof Object.create === 'function') { 218 | // implementation from standard node.js 'util' module 219 | module.exports = function inherits(ctor, superCtor) { 220 | ctor.super_ = superCtor 221 | ctor.prototype = Object.create(superCtor.prototype, { 222 | constructor: { 223 | value: ctor, 224 | enumerable: false, 225 | writable: true, 226 | configurable: true 227 | } 228 | }); 229 | }; 230 | } else { 231 | // old school shim for old browsers 232 | module.exports = function inherits(ctor, superCtor) { 233 | ctor.super_ = superCtor 234 | var TempCtor = function () {} 235 | TempCtor.prototype = superCtor.prototype 236 | ctor.prototype = new TempCtor() 237 | ctor.prototype.constructor = ctor 238 | } 239 | } 240 | 241 | },{}],6:[function(require,module,exports){ 242 | 'use strict'; 243 | var immediate = require('immediate'); 244 | 245 | /* istanbul ignore next */ 246 | function INTERNAL() {} 247 | 248 | var handlers = {}; 249 | 250 | var REJECTED = ['REJECTED']; 251 | var FULFILLED = ['FULFILLED']; 252 | var PENDING = ['PENDING']; 253 | 254 | module.exports = Promise; 255 | 256 | function Promise(resolver) { 257 | if (typeof resolver !== 'function') { 258 | throw new TypeError('resolver must be a function'); 259 | } 260 | this.state = PENDING; 261 | this.queue = []; 262 | this.outcome = void 0; 263 | if (resolver !== INTERNAL) { 264 | safelyResolveThenable(this, resolver); 265 | } 266 | } 267 | 268 | Promise.prototype["catch"] = function (onRejected) { 269 | return this.then(null, onRejected); 270 | }; 271 | Promise.prototype.then = function (onFulfilled, onRejected) { 272 | if (typeof onFulfilled !== 'function' && this.state === FULFILLED || 273 | typeof onRejected !== 'function' && this.state === REJECTED) { 274 | return this; 275 | } 276 | var promise = new this.constructor(INTERNAL); 277 | if (this.state !== PENDING) { 278 | var resolver = this.state === FULFILLED ? onFulfilled : onRejected; 279 | unwrap(promise, resolver, this.outcome); 280 | } else { 281 | this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); 282 | } 283 | 284 | return promise; 285 | }; 286 | function QueueItem(promise, onFulfilled, onRejected) { 287 | this.promise = promise; 288 | if (typeof onFulfilled === 'function') { 289 | this.onFulfilled = onFulfilled; 290 | this.callFulfilled = this.otherCallFulfilled; 291 | } 292 | if (typeof onRejected === 'function') { 293 | this.onRejected = onRejected; 294 | this.callRejected = this.otherCallRejected; 295 | } 296 | } 297 | QueueItem.prototype.callFulfilled = function (value) { 298 | handlers.resolve(this.promise, value); 299 | }; 300 | QueueItem.prototype.otherCallFulfilled = function (value) { 301 | unwrap(this.promise, this.onFulfilled, value); 302 | }; 303 | QueueItem.prototype.callRejected = function (value) { 304 | handlers.reject(this.promise, value); 305 | }; 306 | QueueItem.prototype.otherCallRejected = function (value) { 307 | unwrap(this.promise, this.onRejected, value); 308 | }; 309 | 310 | function unwrap(promise, func, value) { 311 | immediate(function () { 312 | var returnValue; 313 | try { 314 | returnValue = func(value); 315 | } catch (e) { 316 | return handlers.reject(promise, e); 317 | } 318 | if (returnValue === promise) { 319 | handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); 320 | } else { 321 | handlers.resolve(promise, returnValue); 322 | } 323 | }); 324 | } 325 | 326 | handlers.resolve = function (self, value) { 327 | var result = tryCatch(getThen, value); 328 | if (result.status === 'error') { 329 | return handlers.reject(self, result.value); 330 | } 331 | var thenable = result.value; 332 | 333 | if (thenable) { 334 | safelyResolveThenable(self, thenable); 335 | } else { 336 | self.state = FULFILLED; 337 | self.outcome = value; 338 | var i = -1; 339 | var len = self.queue.length; 340 | while (++i < len) { 341 | self.queue[i].callFulfilled(value); 342 | } 343 | } 344 | return self; 345 | }; 346 | handlers.reject = function (self, error) { 347 | self.state = REJECTED; 348 | self.outcome = error; 349 | var i = -1; 350 | var len = self.queue.length; 351 | while (++i < len) { 352 | self.queue[i].callRejected(error); 353 | } 354 | return self; 355 | }; 356 | 357 | function getThen(obj) { 358 | // Make sure we only access the accessor once as required by the spec 359 | var then = obj && obj.then; 360 | if (obj && typeof obj === 'object' && typeof then === 'function') { 361 | return function appyThen() { 362 | then.apply(obj, arguments); 363 | }; 364 | } 365 | } 366 | 367 | function safelyResolveThenable(self, thenable) { 368 | // Either fulfill, reject or reject with error 369 | var called = false; 370 | function onError(value) { 371 | if (called) { 372 | return; 373 | } 374 | called = true; 375 | handlers.reject(self, value); 376 | } 377 | 378 | function onSuccess(value) { 379 | if (called) { 380 | return; 381 | } 382 | called = true; 383 | handlers.resolve(self, value); 384 | } 385 | 386 | function tryToUnwrap() { 387 | thenable(onSuccess, onError); 388 | } 389 | 390 | var result = tryCatch(tryToUnwrap); 391 | if (result.status === 'error') { 392 | onError(result.value); 393 | } 394 | } 395 | 396 | function tryCatch(func, value) { 397 | var out = {}; 398 | try { 399 | out.value = func(value); 400 | out.status = 'success'; 401 | } catch (e) { 402 | out.status = 'error'; 403 | out.value = e; 404 | } 405 | return out; 406 | } 407 | 408 | Promise.resolve = resolve; 409 | function resolve(value) { 410 | if (value instanceof this) { 411 | return value; 412 | } 413 | return handlers.resolve(new this(INTERNAL), value); 414 | } 415 | 416 | Promise.reject = reject; 417 | function reject(reason) { 418 | var promise = new this(INTERNAL); 419 | return handlers.reject(promise, reason); 420 | } 421 | 422 | Promise.all = all; 423 | function all(iterable) { 424 | var self = this; 425 | if (Object.prototype.toString.call(iterable) !== '[object Array]') { 426 | return this.reject(new TypeError('must be an array')); 427 | } 428 | 429 | var len = iterable.length; 430 | var called = false; 431 | if (!len) { 432 | return this.resolve([]); 433 | } 434 | 435 | var values = new Array(len); 436 | var resolved = 0; 437 | var i = -1; 438 | var promise = new this(INTERNAL); 439 | 440 | while (++i < len) { 441 | allResolver(iterable[i], i); 442 | } 443 | return promise; 444 | function allResolver(value, i) { 445 | self.resolve(value).then(resolveFromAll, function (error) { 446 | if (!called) { 447 | called = true; 448 | handlers.reject(promise, error); 449 | } 450 | }); 451 | function resolveFromAll(outValue) { 452 | values[i] = outValue; 453 | if (++resolved === len && !called) { 454 | called = true; 455 | handlers.resolve(promise, values); 456 | } 457 | } 458 | } 459 | } 460 | 461 | Promise.race = race; 462 | function race(iterable) { 463 | var self = this; 464 | if (Object.prototype.toString.call(iterable) !== '[object Array]') { 465 | return this.reject(new TypeError('must be an array')); 466 | } 467 | 468 | var len = iterable.length; 469 | var called = false; 470 | if (!len) { 471 | return this.resolve([]); 472 | } 473 | 474 | var i = -1; 475 | var promise = new this(INTERNAL); 476 | 477 | while (++i < len) { 478 | resolver(iterable[i]); 479 | } 480 | return promise; 481 | function resolver(value) { 482 | self.resolve(value).then(function (response) { 483 | if (!called) { 484 | called = true; 485 | handlers.resolve(promise, response); 486 | } 487 | }, function (error) { 488 | if (!called) { 489 | called = true; 490 | handlers.reject(promise, error); 491 | } 492 | }); 493 | } 494 | } 495 | 496 | },{"immediate":4}],7:[function(require,module,exports){ 497 | 'use strict'; 498 | 499 | function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } 500 | 501 | var lie = _interopDefault(require('lie')); 502 | 503 | /* istanbul ignore next */ 504 | var PouchPromise = typeof Promise === 'function' ? Promise : lie; 505 | 506 | module.exports = PouchPromise; 507 | },{"lie":6}],8:[function(require,module,exports){ 508 | // shim for using process in browser 509 | 510 | var process = module.exports = {}; 511 | 512 | // cached from whatever global is present so that test runners that stub it 513 | // don't break things. But we need to wrap it in a try catch in case it is 514 | // wrapped in strict mode code which doesn't define any globals. It's inside a 515 | // function because try/catches deoptimize in certain engines. 516 | 517 | var cachedSetTimeout; 518 | var cachedClearTimeout; 519 | 520 | (function () { 521 | try { 522 | cachedSetTimeout = setTimeout; 523 | } catch (e) { 524 | cachedSetTimeout = function () { 525 | throw new Error('setTimeout is not defined'); 526 | } 527 | } 528 | try { 529 | cachedClearTimeout = clearTimeout; 530 | } catch (e) { 531 | cachedClearTimeout = function () { 532 | throw new Error('clearTimeout is not defined'); 533 | } 534 | } 535 | } ()) 536 | var queue = []; 537 | var draining = false; 538 | var currentQueue; 539 | var queueIndex = -1; 540 | 541 | function cleanUpNextTick() { 542 | if (!draining || !currentQueue) { 543 | return; 544 | } 545 | draining = false; 546 | if (currentQueue.length) { 547 | queue = currentQueue.concat(queue); 548 | } else { 549 | queueIndex = -1; 550 | } 551 | if (queue.length) { 552 | drainQueue(); 553 | } 554 | } 555 | 556 | function drainQueue() { 557 | if (draining) { 558 | return; 559 | } 560 | var timeout = cachedSetTimeout(cleanUpNextTick); 561 | draining = true; 562 | 563 | var len = queue.length; 564 | while(len) { 565 | currentQueue = queue; 566 | queue = []; 567 | while (++queueIndex < len) { 568 | if (currentQueue) { 569 | currentQueue[queueIndex].run(); 570 | } 571 | } 572 | queueIndex = -1; 573 | len = queue.length; 574 | } 575 | currentQueue = null; 576 | draining = false; 577 | cachedClearTimeout(timeout); 578 | } 579 | 580 | process.nextTick = function (fun) { 581 | var args = new Array(arguments.length - 1); 582 | if (arguments.length > 1) { 583 | for (var i = 1; i < arguments.length; i++) { 584 | args[i - 1] = arguments[i]; 585 | } 586 | } 587 | queue.push(new Item(fun, args)); 588 | if (queue.length === 1 && !draining) { 589 | cachedSetTimeout(drainQueue, 0); 590 | } 591 | }; 592 | 593 | // v8 likes predictible objects 594 | function Item(fun, array) { 595 | this.fun = fun; 596 | this.array = array; 597 | } 598 | Item.prototype.run = function () { 599 | this.fun.apply(null, this.array); 600 | }; 601 | process.title = 'browser'; 602 | process.browser = true; 603 | process.env = {}; 604 | process.argv = []; 605 | process.version = ''; // empty string to avoid regexp issues 606 | process.versions = {}; 607 | 608 | function noop() {} 609 | 610 | process.on = noop; 611 | process.addListener = noop; 612 | process.once = noop; 613 | process.off = noop; 614 | process.removeListener = noop; 615 | process.removeAllListeners = noop; 616 | process.emit = noop; 617 | 618 | process.binding = function (name) { 619 | throw new Error('process.binding is not supported'); 620 | }; 621 | 622 | process.cwd = function () { return '/' }; 623 | process.chdir = function (dir) { 624 | throw new Error('process.chdir is not supported'); 625 | }; 626 | process.umask = function() { return 0; }; 627 | 628 | },{}],9:[function(require,module,exports){ 629 | 'use strict'; 630 | 631 | // Simple FIFO queue implementation to avoid having to do shift() 632 | // on an array, which is slow. 633 | 634 | function Queue() { 635 | this.length = 0; 636 | } 637 | 638 | Queue.prototype.push = function (item) { 639 | var node = {item: item}; 640 | if (this.last) { 641 | this.last = this.last.next = node; 642 | } else { 643 | this.last = this.first = node; 644 | } 645 | this.length++; 646 | }; 647 | 648 | Queue.prototype.shift = function () { 649 | var node = this.first; 650 | if (node) { 651 | this.first = node.next; 652 | if (!(--this.length)) { 653 | this.last = undefined; 654 | } 655 | return node.item; 656 | } 657 | }; 658 | 659 | Queue.prototype.slice = function (start, end) { 660 | start = typeof start === 'undefined' ? 0 : start; 661 | end = typeof end === 'undefined' ? Infinity : end; 662 | 663 | var output = []; 664 | 665 | var i = 0; 666 | for (var node = this.first; node; node = node.next) { 667 | if (--end < 0) { 668 | break; 669 | } else if (++i > start) { 670 | output.push(node.item); 671 | } 672 | } 673 | return output; 674 | } 675 | 676 | module.exports = Queue; 677 | 678 | },{}],10:[function(require,module,exports){ 679 | 'use strict'; 680 | 681 | var utils = require('./pouch-utils'); 682 | var TaskQueue = require('./taskqueue'); 683 | 684 | var PREFIX = "db_"; 685 | 686 | function prefixed(dbName) { 687 | //A database name starting with an underscore is valid, but a document 688 | //id starting with an underscore is not in most cases. Because of 689 | //that, they're prefixed in the all dbs database. See issue #7 for 690 | //more info. 691 | return PREFIX + dbName; 692 | } 693 | 694 | function unprefixed(dbName) { 695 | return dbName.slice(PREFIX.length); 696 | } 697 | 698 | module.exports = function (Pouch) { 699 | 700 | var ALL_DBS_NAME = 'pouch__all_dbs__'; 701 | var pouch; 702 | var cache; 703 | var queue = new TaskQueue(); 704 | 705 | function log(err) { 706 | /* istanbul ignore if */ 707 | if (err) { 708 | console.error(err); // shouldn't happen 709 | } 710 | } 711 | 712 | function init() { 713 | queue.add(function (callback) { 714 | if (pouch) { 715 | return callback(); 716 | } 717 | pouch = new Pouch(ALL_DBS_NAME); 718 | callback(); 719 | }); 720 | } 721 | 722 | function normalize(name) { 723 | return name.replace(/^_pouch_/, ''); // TODO: remove when fixed in Pouch 724 | } 725 | 726 | function canIgnore(dbName) { 727 | return (dbName === ALL_DBS_NAME) || 728 | // TODO: get rid of this when we have a real 'onDependentDbRegistered' 729 | // event (pouchdb/pouchdb#2438) 730 | (dbName.indexOf('-mrview-') !== -1) || 731 | // TODO: might be a better way to detect remote DBs 732 | (/^https?:\/\//.test(dbName)); 733 | } 734 | 735 | Pouch.on('created', function (dbName) { 736 | dbName = normalize(dbName); 737 | if (canIgnore(dbName)) { 738 | return; 739 | } 740 | dbName = prefixed(dbName); 741 | init(); 742 | queue.add(function (callback) { 743 | pouch.get(dbName).then(function () { 744 | // db exists, nothing to do 745 | })["catch"](function (err) { 746 | /* istanbul ignore if */ 747 | if (err.name !== 'not_found') { 748 | throw err; 749 | } 750 | return pouch.put({_id: dbName}); 751 | }).then(function () { 752 | if (cache) { 753 | cache[dbName] = true; 754 | } 755 | callback(); 756 | }, callback); 757 | }, log); 758 | }); 759 | 760 | Pouch.on('destroyed', function (dbName) { 761 | dbName = normalize(dbName); 762 | if (canIgnore(dbName)) { 763 | return; 764 | } 765 | dbName = prefixed(dbName); 766 | init(); 767 | queue.add(function (callback) { 768 | pouch.get(dbName).then(function (doc) { 769 | return pouch.remove(doc); 770 | })["catch"](/* istanbul ignore next */ function (err) { 771 | // normally a not_found error; nothing to do 772 | if (err.name !== 'not_found') { 773 | throw err; 774 | } 775 | }).then(function () { 776 | /* istanbul ignore else */ 777 | if (cache) { 778 | delete cache[dbName]; 779 | } 780 | callback(); 781 | }, callback); 782 | }, log); 783 | }); 784 | 785 | Pouch.allDbs = utils.toPromise(function (callback) { 786 | init(); 787 | queue.add(function (callback) { 788 | 789 | if (cache) { 790 | return callback(null, Object.keys(cache).map(unprefixed)); 791 | } 792 | 793 | // older versions of this module didn't have prefixes, so check here 794 | var opts = {startkey: PREFIX, endkey: (PREFIX + '\uffff')}; 795 | pouch.allDocs(opts).then(function (res) { 796 | cache = {}; 797 | var dbs = []; 798 | res.rows.forEach(function (row) { 799 | dbs.push(unprefixed(row.key)); 800 | cache[row.key] = true; 801 | }); 802 | callback(null, dbs); 803 | })["catch"](/* istanbul ignore next */ function (err) { 804 | console.error(err); 805 | callback(err); 806 | }); 807 | }, callback); 808 | }); 809 | 810 | Pouch.resetAllDbs = utils.toPromise(function (callback) { 811 | queue.add(function (callback) { 812 | pouch.destroy().then(function () { 813 | pouch = null; 814 | cache = null; 815 | callback(); 816 | })["catch"](/* istanbul ignore next */ function (err) { 817 | console.error(err); 818 | callback(err); 819 | }); 820 | }, callback); 821 | }); 822 | }; 823 | 824 | /* istanbul ignore next */ 825 | if (typeof window !== 'undefined' && window.PouchDB) { 826 | module.exports(window.PouchDB); 827 | } 828 | 829 | },{"./pouch-utils":1,"./taskqueue":2}]},{},[10]); 830 | -------------------------------------------------------------------------------- /dist/pouchdb.all-dbs.min.js: -------------------------------------------------------------------------------- 1 | !function t(e,n,r){function o(u,c){if(!n[u]){if(!e[u]){var s="function"==typeof require&&require;if(!c&&s)return s(u,!0);if(i)return i(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var a=n[u]={exports:{}};e[u][0].call(a.exports,function(t){var n=e[u][1][t];return o(n?n:t)},a,a.exports,t,e,n,r)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u1)for(var n=1;nt&&n.push(o.item);return n},e.exports=r},{}],10:[function(t,e,n){"use strict";function r(t){return c+t}function o(t){return t.slice(c.length)}var i=t("./pouch-utils"),u=t("./taskqueue"),c="db_";e.exports=function(t){function e(t){t&&console.error(t)}function n(){p.add(function(e){return a?e():(a=new t(h),void e())})}function s(t){return t.replace(/^_pouch_/,"")}function f(t){return t===h||-1!==t.indexOf("-mrview-")||/^https?:\/\//.test(t)}var a,l,h="pouch__all_dbs__",p=new u;t.on("created",function(t){t=s(t),f(t)||(t=r(t),n(),p.add(function(e){a.get(t).then(function(){})["catch"](function(e){if("not_found"!==e.name)throw e;return a.put({_id:t})}).then(function(){l&&(l[t]=!0),e()},e)},e))}),t.on("destroyed",function(t){t=s(t),f(t)||(t=r(t),n(),p.add(function(e){a.get(t).then(function(t){return a.remove(t)})["catch"](function(t){if("not_found"!==t.name)throw t}).then(function(){l&&delete l[t],e()},e)},e))}),t.allDbs=i.toPromise(function(t){n(),p.add(function(t){if(l)return t(null,Object.keys(l).map(o));var e={startkey:c,endkey:c+"￿"};a.allDocs(e).then(function(e){l={};var n=[];e.rows.forEach(function(t){n.push(o(t.key)),l[t.key]=!0}),t(null,n)})["catch"](function(e){console.error(e),t(e)})},t)}),t.resetAllDbs=i.toPromise(function(t){p.add(function(t){a.destroy().then(function(){a=null,l=null,t()})["catch"](function(e){console.error(e),t(e)})},t)})},"undefined"!=typeof window&&window.PouchDB&&e.exports(window.PouchDB)},{"./pouch-utils":1,"./taskqueue":2}]},{},[10]); 2 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var utils = require('./pouch-utils'); 4 | var TaskQueue = require('./taskqueue'); 5 | 6 | var PREFIX = "db_"; 7 | 8 | function prefixed(dbName) { 9 | //A database name starting with an underscore is valid, but a document 10 | //id starting with an underscore is not in most cases. Because of 11 | //that, they're prefixed in the all dbs database. See issue #7 for 12 | //more info. 13 | return PREFIX + dbName; 14 | } 15 | 16 | function unprefixed(dbName) { 17 | return dbName.slice(PREFIX.length); 18 | } 19 | 20 | module.exports = function (Pouch) { 21 | 22 | var ALL_DBS_NAME = 'pouch__all_dbs__'; 23 | var pouch; 24 | var cache; 25 | var queue = new TaskQueue(); 26 | 27 | function log(err) { 28 | /* istanbul ignore if */ 29 | if (err) { 30 | console.error(err); // shouldn't happen 31 | } 32 | } 33 | 34 | function init() { 35 | queue.add(function (callback) { 36 | if (pouch) { 37 | return callback(); 38 | } 39 | pouch = new Pouch(ALL_DBS_NAME); 40 | callback(); 41 | }); 42 | } 43 | 44 | function normalize(name) { 45 | return name.replace(/^_pouch_/, ''); // TODO: remove when fixed in Pouch 46 | } 47 | 48 | function canIgnore(dbName) { 49 | return (dbName === ALL_DBS_NAME) || 50 | // TODO: get rid of this when we have a real 'onDependentDbRegistered' 51 | // event (pouchdb/pouchdb#2438) 52 | (dbName.indexOf('-mrview-') !== -1) || 53 | // TODO: might be a better way to detect remote DBs 54 | (/^https?:\/\//.test(dbName)); 55 | } 56 | 57 | Pouch.on('created', function (dbName) { 58 | dbName = normalize(dbName); 59 | if (canIgnore(dbName)) { 60 | return; 61 | } 62 | dbName = prefixed(dbName); 63 | init(); 64 | queue.add(function (callback) { 65 | pouch.get(dbName).then(function () { 66 | // db exists, nothing to do 67 | }).catch(function (err) { 68 | /* istanbul ignore if */ 69 | if (err.name !== 'not_found') { 70 | throw err; 71 | } 72 | return pouch.put({_id: dbName}); 73 | }).then(function () { 74 | if (cache) { 75 | cache[dbName] = true; 76 | } 77 | callback(); 78 | }, callback); 79 | }, log); 80 | }); 81 | 82 | Pouch.on('destroyed', function (dbName) { 83 | dbName = normalize(dbName); 84 | if (canIgnore(dbName)) { 85 | return; 86 | } 87 | dbName = prefixed(dbName); 88 | init(); 89 | queue.add(function (callback) { 90 | pouch.get(dbName).then(function (doc) { 91 | return pouch.remove(doc); 92 | }).catch(/* istanbul ignore next */ function (err) { 93 | // normally a not_found error; nothing to do 94 | if (err.name !== 'not_found') { 95 | throw err; 96 | } 97 | }).then(function () { 98 | /* istanbul ignore else */ 99 | if (cache) { 100 | delete cache[dbName]; 101 | } 102 | callback(); 103 | }, callback); 104 | }, log); 105 | }); 106 | 107 | Pouch.allDbs = utils.toPromise(function (callback) { 108 | init(); 109 | queue.add(function (callback) { 110 | 111 | if (cache) { 112 | return callback(null, Object.keys(cache).map(unprefixed)); 113 | } 114 | 115 | // older versions of this module didn't have prefixes, so check here 116 | var opts = {startkey: PREFIX, endkey: (PREFIX + '\uffff')}; 117 | pouch.allDocs(opts).then(function (res) { 118 | cache = {}; 119 | var dbs = []; 120 | res.rows.forEach(function (row) { 121 | dbs.push(unprefixed(row.key)); 122 | cache[row.key] = true; 123 | }); 124 | callback(null, dbs); 125 | }).catch(/* istanbul ignore next */ function (err) { 126 | console.error(err); 127 | callback(err); 128 | }); 129 | }, callback); 130 | }); 131 | 132 | Pouch.resetAllDbs = utils.toPromise(function (callback) { 133 | queue.add(function (callback) { 134 | pouch.destroy().then(function () { 135 | pouch = null; 136 | cache = null; 137 | callback(); 138 | }).catch(/* istanbul ignore next */ function (err) { 139 | console.error(err); 140 | callback(err); 141 | }); 142 | }, callback); 143 | }); 144 | }; 145 | 146 | /* istanbul ignore next */ 147 | if (typeof window !== 'undefined' && window.PouchDB) { 148 | module.exports(window.PouchDB); 149 | } 150 | -------------------------------------------------------------------------------- /lib/pouch-utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* istanbul ignore next */ 4 | function _interopDefault (ex) { 5 | return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; 6 | } 7 | 8 | var Promise = _interopDefault(require('pouchdb-promise')); 9 | /* istanbul ignore next */ 10 | exports.once = function (fun) { 11 | var called = false; 12 | return exports.getArguments(function (args) { 13 | if (called) { 14 | console.trace(); 15 | throw new Error('once called more than once'); 16 | } else { 17 | called = true; 18 | fun.apply(this, args); 19 | } 20 | }); 21 | }; 22 | /* istanbul ignore next */ 23 | exports.getArguments = function (fun) { 24 | return function () { 25 | var len = arguments.length; 26 | var args = new Array(len); 27 | var i = -1; 28 | while (++i < len) { 29 | args[i] = arguments[i]; 30 | } 31 | return fun.call(this, args); 32 | }; 33 | }; 34 | /* istanbul ignore next */ 35 | exports.toPromise = function (func) { 36 | //create the function we will be returning 37 | return exports.getArguments(function (args) { 38 | var self = this; 39 | var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false; 40 | // if the last argument is a function, assume its a callback 41 | var usedCB; 42 | if (tempCB) { 43 | // if it was a callback, create a new callback which calls it, 44 | // but do so async so we don't trap any errors 45 | usedCB = function (err, resp) { 46 | process.nextTick(function () { 47 | tempCB(err, resp); 48 | }); 49 | }; 50 | } 51 | var promise = new Promise(function (fulfill, reject) { 52 | try { 53 | var callback = exports.once(function (err, mesg) { 54 | if (err) { 55 | reject(err); 56 | } else { 57 | fulfill(mesg); 58 | } 59 | }); 60 | // create a callback for this invocation 61 | // apply the function in the orig context 62 | args.push(callback); 63 | func.apply(self, args); 64 | } catch (e) { 65 | reject(e); 66 | } 67 | }); 68 | // if there is a callback, call it back 69 | if (usedCB) { 70 | promise.then(function (result) { 71 | usedCB(null, result); 72 | }, usedCB); 73 | } 74 | promise.cancel = function () { 75 | return this; 76 | }; 77 | return promise; 78 | }); 79 | }; 80 | 81 | exports.inherits = require('inherits'); 82 | -------------------------------------------------------------------------------- /lib/taskqueue.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var argsarray = require('argsarray'); 4 | var Queue = require('tiny-queue'); 5 | 6 | // see http://stackoverflow.com/a/15349865/680742 7 | /* istanbul ignore next */ 8 | var nextTick = global.setImmediate || process.nextTick; 9 | 10 | function TaskQueue() { 11 | this.queue = new Queue(); 12 | this.running = false; 13 | } 14 | 15 | TaskQueue.prototype.add = function (fun, callback) { 16 | callback = callback || function () {}; 17 | this.queue.push({fun: fun, callback: callback}); 18 | this.processNext(); 19 | }; 20 | 21 | TaskQueue.prototype.processNext = function () { 22 | var self = this; 23 | if (self.running || !self.queue.length) { 24 | return; 25 | } 26 | self.running = true; 27 | 28 | var task = self.queue.shift(); 29 | nextTick(function () { 30 | task.fun(argsarray(function (args) { 31 | task.callback.apply(null, args); 32 | self.running = false; 33 | self.processNext(); 34 | })); 35 | }); 36 | }; 37 | 38 | module.exports = TaskQueue; 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pouchdb-all-dbs", 3 | "version": "1.1.1", 4 | "description": "PouchDB allDbs plugin", 5 | "main": "lib/index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/nolanlawson/pouchdb-all-dbs.git" 9 | }, 10 | "keywords": [ 11 | "pouch", 12 | "pouchdb", 13 | "plugin", 14 | "allDbs", 15 | "couch", 16 | "couchdb" 17 | ], 18 | "author": "", 19 | "license": "Apache-2.0", 20 | "bugs": { 21 | "url": "https://github.com/nolanlawson/pouchdb-all-dbs/issues" 22 | }, 23 | "scripts": { 24 | "test-node": "TEST_DB=testdb nyc mocha --include test/test.js --exclude test/webrunner.js", 25 | "test-browser": "./bin/test-browser.js", 26 | "jshint": "jshint -c .jshintrc lib/*.js test/test.js", 27 | "test": "npm run jshint && ./bin/run-test.sh", 28 | "build": "mkdir -p dist && browserify . -o dist/pouchdb.all-dbs.js && npm run min", 29 | "min": "uglifyjs dist/pouchdb.all-dbs.js -mc > dist/pouchdb.all-dbs.min.js", 30 | "dev": "browserify test/test.js > test/test-bundle.js && npm run dev-server", 31 | "dev-server": "./bin/dev-server.js", 32 | "coverage": "npm test --coverage && nyc check-coverage --lines 100 --function 100 --statements 100 --branches 100" 33 | }, 34 | "dependencies": { 35 | "argsarray": "0.0.1", 36 | "es3ify": "^0.2.2", 37 | "inherits": "~2.0.1", 38 | "pouchdb-promise": "6.4.3", 39 | "tiny-queue": "^0.2.0" 40 | }, 41 | "devDependencies": { 42 | "bluebird": "^3.7.2", 43 | "browserify": "^17.0.0", 44 | "chai": "^4.3.0", 45 | "chai-as-promised": "^7.1.1", 46 | "http-server": "~0.12.3", 47 | "jshint": "~2.12.0", 48 | "mocha": "^8.3.0", 49 | "nyc": "^15.1.0", 50 | "phantomjs-prebuilt": "^2.1.7", 51 | "pouchdb": "^7.2.2", 52 | "request": "^2.36.0", 53 | "sauce-connect-launcher": "^1.3.2", 54 | "selenium-standalone": "^6.23.0", 55 | "uglify-js": "^3.12.7", 56 | "watchify": "^4.0.0", 57 | "wd": "^1.14.0" 58 | }, 59 | "browser": { 60 | "crypto": false 61 | }, 62 | "browserify": { 63 | "transform": [ 64 | "es3ify" 65 | ] 66 | }, 67 | "files": [ 68 | "lib", 69 | "dist" 70 | ] 71 | } 72 | -------------------------------------------------------------------------------- /test/bind-polyfill.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | 'use strict'; 3 | // minimal polyfill for phantomjs; in the future, we should do ES5_SHIM=true like pouchdb 4 | if (!Function.prototype.bind) { 5 | Function.prototype.bind = function (oThis) { 6 | if (typeof this !== "function") { 7 | // closest thing possible to the ECMAScript 5 8 | // internal IsCallable function 9 | throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 10 | } 11 | 12 | var aArgs = Array.prototype.slice.call(arguments, 1), 13 | fToBind = this, 14 | fNOP = function () {}, 15 | fBound = function () { 16 | return fToBind.apply(this instanceof fNOP && oThis 17 | ? this 18 | : oThis, 19 | aArgs.concat(Array.prototype.slice.call(arguments))); 20 | }; 21 | 22 | fNOP.prototype = this.prototype; 23 | fBound.prototype = new fNOP(); 24 | 25 | return fBound; 26 | }; 27 | } 28 | })(); 29 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Mocha Tests 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | /*jshint expr:true */ 2 | 'use strict'; 3 | 4 | var PouchDB = require('pouchdb'); 5 | 6 | // 7 | // your plugin goes here 8 | // 9 | var plugin = require('../'); 10 | plugin(PouchDB); 11 | 12 | var chai = require('chai'); 13 | chai.use(require("chai-as-promised")); 14 | 15 | // 16 | // more variables you might want 17 | // 18 | chai.should(); // var should = chai.should(); 19 | var Promise = require('bluebird'); // var Promise = require('bluebird'); 20 | 21 | var dbs; 22 | if (process.browser) { 23 | dbs = 'testdb' + Math.random(); 24 | } else { 25 | dbs = process.env.TEST_DB; 26 | } 27 | 28 | dbs.split(',').forEach(function (db) { 29 | var dbType = /^http/.test(db) ? 'http' : 'local'; 30 | tests(db, dbType); 31 | }); 32 | 33 | function tests(dbName) { 34 | describe('allDbs', function () { 35 | this.timeout(10000); 36 | 37 | var dbs = []; 38 | 39 | afterEach(function () { 40 | // Remove old allDbs to prevent DOM exception 41 | return Promise.all(dbs.map(function (db) { 42 | return new PouchDB(db).destroy(); 43 | })).then(function () { 44 | return PouchDB.resetAllDbs(); 45 | }); 46 | }); 47 | 48 | it('new Pouch registered in allDbs', function (done) { 49 | this.timeout(15000); 50 | var pouchName = dbName; 51 | dbs = [dbName]; 52 | function after(err) { 53 | new PouchDB(pouchName).destroy(function (er) { 54 | if (er) { 55 | done(er); 56 | } else { 57 | done(err); 58 | } 59 | }); 60 | } 61 | // create db 62 | var newPouch = new PouchDB(pouchName); 63 | newPouch.info().then(function() { 64 | PouchDB.allDbs(function (err, dbs) { 65 | if (err) { 66 | return after(err); 67 | } 68 | // check if pouchName exists in _all_db 69 | dbs.some(function (dbname) { 70 | return dbname === pouchName; 71 | }).should.equal(true, 'pouch exists in allDbs database, dbs are ' + 72 | JSON.stringify(dbs) + ', tested against ' + pouchName); 73 | after(); 74 | }); 75 | }); 76 | }); 77 | 78 | it('new Pouch registered in allDbs with a promise', function (done) { 79 | this.timeout(15000); 80 | var pouchName = dbName; 81 | dbs = [dbName]; 82 | function after(err) { 83 | new PouchDB(pouchName).destroy(function (er) { 84 | if (er) { 85 | done(er); 86 | } else { 87 | done(err); 88 | } 89 | }); 90 | } 91 | // create db 92 | 93 | var newPouch = new PouchDB(pouchName); 94 | newPouch.info().then(function() { 95 | PouchDB.allDbs().then(function (dbs) { 96 | // check if pouchName exists in _all_db 97 | dbs.some(function (dbname) { 98 | return dbname === pouchName; 99 | }).should.equal(true, 'pouch exists in allDbs database, dbs are ' + 100 | JSON.stringify(dbs) + ', tested against ' + pouchName); 101 | after(); 102 | }).catch(after); 103 | }); 104 | }); 105 | 106 | 107 | it('Pouch.destroy removes pouch from allDbs', function (done) { 108 | var pouchName = dbName; 109 | dbs = [dbName]; 110 | // create db 111 | var newPouch = new PouchDB(pouchName); 112 | newPouch.info().then(function() { 113 | PouchDB.allDbs(function (err, dbs) { 114 | if (err) { 115 | return done(err); 116 | } 117 | // check if pouchName exists in _all_db 118 | dbs.some(function (dbname) { 119 | return dbname === pouchName; 120 | }).should.equal(true, 'pouch exists in allDbs database, dbs are ' + 121 | JSON.stringify(dbs) + ', tested against ' + pouchName); 122 | // remove db 123 | new PouchDB(pouchName).destroy(function (err) { 124 | if (err) { 125 | return done(err); 126 | } 127 | PouchDB.allDbs(function (err, dbs) { 128 | if (err) { 129 | return done(err); 130 | } 131 | // check if pouchName still exists in _all_db 132 | dbs.some(function (dbname) { 133 | return dbname === pouchName; 134 | }).should.equal(false, 135 | 'pouch no longer exists in allDbs database, dbs are ' + 136 | JSON.stringify(dbs) + ', tested against ' + pouchName); 137 | done(); 138 | }); 139 | }); 140 | }); 141 | }); 142 | }); 143 | it('Create Multiple Pouches', function (done) { 144 | var pouchNames = [dbName + '_1', dbName + '_2']; 145 | dbs = pouchNames; 146 | 147 | Promise.all(pouchNames.map(function (pouch) { 148 | var newPouch = new PouchDB(pouch); 149 | return newPouch.info(); 150 | })).then(function () { 151 | PouchDB.allDbs(function (err, dbs) { 152 | if (err) { 153 | return done(err); 154 | } 155 | pouchNames.forEach(function (pouch) { 156 | // check if pouchName exists in _all_db 157 | dbs.some(function (dbname) { 158 | return dbname === pouch; 159 | }).should.equal(true, 'pouch name not found in allDbs, dbs are ' + 160 | JSON.stringify(dbs) + ', tested against ' + pouch); 161 | }); 162 | // destroy remaining pouches 163 | Promise.all(pouchNames.map(function (pouch) { 164 | return new PouchDB(pouch).destroy(); 165 | })).then(function() { 166 | done(); 167 | }).catch(function (err) { 168 | done(err); 169 | }); 170 | }); 171 | }).catch(function (err) { 172 | done(err); 173 | }); 174 | }); 175 | it('Create and Destroy Multiple Pouches', function (done) { 176 | var pouchNames = [dbName + '_1', dbName + '_2']; 177 | dbs = pouchNames; 178 | 179 | Promise.all(pouchNames.map(function (pouch) { 180 | var newPouch = new PouchDB(pouch); 181 | return newPouch.info(); 182 | })).then(function () { 183 | PouchDB.allDbs(function (err, dbs) { 184 | if (err) { 185 | return done(err); 186 | } 187 | // check if pouchName exists in _all_db 188 | pouchNames.forEach(function (pouch) { 189 | dbs.some(function (dbname) { 190 | return dbname === pouch; 191 | }).should.equal(true); 192 | }); 193 | // 194 | // Destroy all Pouches 195 | // 196 | Promise.all(pouchNames.map(function (pouch) { 197 | return new PouchDB(pouch).destroy(); 198 | })).then(function() { 199 | PouchDB.allDbs(function (err, dbs) { 200 | if (err) { 201 | return done(err); 202 | } 203 | // check if pouchName exists in _all_db 204 | pouchNames.forEach(function (pouch) { 205 | dbs.some(function (dbname) { 206 | return dbname === pouch; 207 | }).should.equal(false, 208 | 'pouch name found in allDbs after its destroyed, dbs are ' + 209 | JSON.stringify(dbs) + ', tested against ' + pouch); 210 | }); 211 | done(); 212 | }); 213 | }).catch(function (err) { 214 | done(err); 215 | }); 216 | }); 217 | }).catch(function (err) { 218 | done(err); 219 | }); 220 | }); 221 | it('doesn\'t return the mapreduce db', function (done) { 222 | var pouchName = dbName; 223 | dbs = [dbName]; 224 | // create db 225 | var db = new PouchDB(pouchName); 226 | db.info().then(function() { 227 | var ddoc = { 228 | _id: "_design/foo", 229 | views: { 230 | foo: { 231 | map: function () {}.toString() 232 | } 233 | } 234 | }; 235 | db.put(ddoc).then(function (info) { 236 | ddoc._rev = info.rev; 237 | return db.query('foo'); 238 | }).then(function () { 239 | return PouchDB.allDbs(); 240 | }).then(function (dbs) { 241 | dbs.should.have.length(1); 242 | return db.remove(ddoc); 243 | }).then(function () { 244 | return db.viewCleanup(); 245 | }).then(function () { 246 | return PouchDB.allDbs(); 247 | }).then(function (dbs) { 248 | dbs.should.have.length(1); 249 | }).then(function () { done(); }, done); 250 | }).catch(function(err) { 251 | done(err); 252 | }); 253 | }); 254 | 255 | // Test for return value of allDbs 256 | // The format should follow the following rules: 257 | // 1. if an adapter is specified upon Pouch creation, the dbname will 258 | // include the adapter prefix 259 | // - eg. "idb://testdb" 260 | // 2. Otherwise, the dbname will just contain the dbname (without the 261 | // adapter prefix) 262 | it('Create and Destroy Pouches with and without adapter prefixes', 263 | function (done) { 264 | var pouchNames = [dbName + '_1', dbName + '_2']; 265 | dbs = pouchNames; 266 | Promise.all(pouchNames.map(function (pouch) { 267 | var newPouch = new PouchDB(pouch); 268 | return newPouch.info(); 269 | })).then(function () { 270 | // check allDbs output 271 | PouchDB.allDbs(function (err, dbs) { 272 | if (err) { 273 | return done(err); 274 | } 275 | pouchNames.forEach(function (pouch) { 276 | // check if pouchName exists in allDbs 277 | dbs.some(function (dbname) { 278 | return dbname === pouch; 279 | }).should.equal(true, 'pouch name not found in allDbs, dbs are ' + 280 | JSON.stringify(dbs) + ', tested against ' + pouch); 281 | }); 282 | // destroy pouches 283 | Promise.all(pouchNames.map(function (pouch) { 284 | return new PouchDB(pouch).destroy(); 285 | })).then(function() { 286 | if (err) { 287 | return done(err); 288 | } 289 | // Check that pouches no longer exist in allDbs 290 | PouchDB.allDbs(function (err, dbs) { 291 | if (err) { 292 | return done(err); 293 | } 294 | // check if pouchName exists in _all_db 295 | pouchNames.forEach(function (pouch) { 296 | dbs.some(function (dbname) { 297 | return dbname === pouch; 298 | }).should.equal(false, 299 | 'pouch name found in allDbs after its destroyed, dbs are ' + 300 | JSON.stringify(dbs) + ', tested against ' + pouch); 301 | }); 302 | done(); 303 | }); 304 | }).catch(function (err) { 305 | done(err); 306 | }); 307 | }); 308 | }).catch(function (err) { 309 | done(err); 310 | }); 311 | }); 312 | 313 | it('saves databases with names starting with an underscore.', function (done) { 314 | var pouchName = "_" + dbName; 315 | dbs = [pouchName]; 316 | // create db 317 | 318 | var db = new PouchDB(pouchName); 319 | db.info().then(function() { 320 | PouchDB.allDbs(function (err, allDbs) { 321 | if (err) { 322 | return done(err); 323 | } 324 | allDbs.should.deep.equal(dbs); 325 | done(); 326 | }); 327 | }).catch(function(err) { 328 | done(err); 329 | }); 330 | }); 331 | }); 332 | } 333 | -------------------------------------------------------------------------------- /test/webrunner.js: -------------------------------------------------------------------------------- 1 | /* global mocha: true */ 2 | 3 | (function () { 4 | 'use strict'; 5 | var runner = mocha.run(); 6 | window.results = { 7 | lastPassed: '', 8 | passed: 0, 9 | failed: 0, 10 | failures: [] 11 | }; 12 | 13 | runner.on('pass', function (e) { 14 | window.results.lastPassed = e.title; 15 | window.results.passed++; 16 | }); 17 | 18 | runner.on('fail', function (e) { 19 | window.results.failed++; 20 | window.results.failures.push({ 21 | title: e.title, 22 | message: e.err.message, 23 | stack: e.err.stack 24 | }); 25 | }); 26 | 27 | runner.on('end', function () { 28 | window.results.completed = true; 29 | window.results.passed++; 30 | }); 31 | })(); 32 | 33 | 34 | --------------------------------------------------------------------------------