From c18660a2ed0d9b09e92f125c7f4adaded76f699b Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Fri, 16 May 2014 12:37:34 -0400 Subject: [PATCH 01/31] Initial work on getting tests to run, some working --- package.json | 5 ++- tests/lib/test-utils.js | 2 +- tests/node-runner.js | 82 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 tests/node-runner.js diff --git a/package.json b/package.json index 324abd5..49af3a1 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,9 @@ "grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck", "grunt-prompt": "^1.1.0", "habitat": "^1.1.0", - "semver": "^2.3.0" + "semver": "^2.3.0", + "requirejs": "~2.1.11", + "mocha": "~1.18.2", + "chai": "~1.9.1" } } diff --git a/tests/lib/test-utils.js b/tests/lib/test-utils.js index e189c52..4419e2e 100644 --- a/tests/lib/test-utils.js +++ b/tests/lib/test-utils.js @@ -60,7 +60,7 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) { // Create a file system and wait for it to get setup _provider.init(); - +console.log('here!'); function complete(err, fs) { if(err) throw err; _fs = fs; diff --git a/tests/node-runner.js b/tests/node-runner.js new file mode 100644 index 0000000..f478f97 --- /dev/null +++ b/tests/node-runner.js @@ -0,0 +1,82 @@ +var requirejs = require('requirejs'); +//var Mocha = require('mocha'); + +requirejs.config({ + paths: { + "tests": "../tests", + "src": "../src", + "spec": "../tests/spec", + "bugs": "../tests/bugs", + "util": "../tests/lib/test-utils", + "Filer": "../dist/filer" + }, + baseUrl: "./lib", + optimize: "none", + shim: { + // TextEncoder and TextDecoder shims. encoding-indexes must get loaded first, + // and we use a fake one for reduced size, since we only care about utf8. + "encoding": { + deps: ["encoding-indexes-shim"] + } +//, +// "mocha": { +// init: function() { +// this.mocha = new Mocha(); +// this.mocha.setup("bdd").timeout(5000).slow(250); +// this.mocha.setup("bdd"); +// GLOBAL.describe = mocha.describe; +// return this.mocha; +// } +// } + }, + nodeRequire: require +}); + +GLOBAL.window = GLOBAL; +GLOBAL.expect = require('chai').expect; +console.log('here 1'); + + describe("one test", function() { + it('should work', function(done){ + require('assert').ok(true); + done(); + }); + }); + +//requirejs(function() { + requirejs(["tests/test-manifest"], function() { + +console.log('here 2'); +//console.dir(mocha); + + describe("two test", function() { + it('should work', function(done){ + require('assert').ok(true); + done(); + }); + }); + +console.log('here 3'); + +// mocha.run(function() { +// console.log('running'); +// }); + +console.log('here 4'); + + +/** + + mocha.run(function() { + console.log('here 4'); + }).on('fail', function(test) { + console.log('fail', test); + }).on('pass', function(test) { + console.log('pass', test); + }); + }); + +**/ +}); + +//setTimeout(function(){}, 3000); From e041c2d904a47e3fb46b883a1776177781402ada Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Fri, 16 May 2014 13:18:13 -0400 Subject: [PATCH 02/31] Tests running now --- tests/lib/test-utils.js | 8 +++-- tests/node-runner.js | 66 ++++++++--------------------------------- 2 files changed, 18 insertions(+), 56 deletions(-) diff --git a/tests/lib/test-utils.js b/tests/lib/test-utils.js index 4419e2e..acea1e0 100644 --- a/tests/lib/test-utils.js +++ b/tests/lib/test-utils.js @@ -12,10 +12,14 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) { } function findBestProvider() { + if(typeof module !== 'undefined' && module.exports) { + return MemoryTestProvider; + } + // When running tests, and when no explicit provider is defined, // prefer providers in this order: IndexedDB, WebSQL, Memory. // However, if we're running in PhantomJS, use Memory first. - if(navigator.userAgent.indexOf('PhantomJS') > -1) { + if(typeof navigator !== 'undefined' && navigator.userAgent.indexOf('PhantomJS') > -1) { return MemoryTestProvider; } @@ -60,7 +64,7 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) { // Create a file system and wait for it to get setup _provider.init(); -console.log('here!'); + function complete(err, fs) { if(err) throw err; _fs = fs; diff --git a/tests/node-runner.js b/tests/node-runner.js index f478f97..ecaeb4b 100644 --- a/tests/node-runner.js +++ b/tests/node-runner.js @@ -1,5 +1,4 @@ var requirejs = require('requirejs'); -//var Mocha = require('mocha'); requirejs.config({ paths: { @@ -18,65 +17,24 @@ requirejs.config({ "encoding": { deps: ["encoding-indexes-shim"] } -//, -// "mocha": { -// init: function() { -// this.mocha = new Mocha(); -// this.mocha.setup("bdd").timeout(5000).slow(250); -// this.mocha.setup("bdd"); -// GLOBAL.describe = mocha.describe; -// return this.mocha; -// } -// } }, nodeRequire: require }); -GLOBAL.window = GLOBAL; +GLOBAL.document = {}; +GLOBAL.navigator = { userAgent: ""}; +GLOBAL.window = { + addEventListener: function(){}, + navigator: navigator, + document: document, + setTimeout: setTimeout +}; GLOBAL.expect = require('chai').expect; -console.log('here 1'); - describe("one test", function() { - it('should work', function(done){ - require('assert').ok(true); - done(); - }); +describe("Mocha needs one test in order to wait on requirejs tests", function() { + it('should wait for other tests', function(){ + require('assert').ok(true); }); - -//requirejs(function() { - requirejs(["tests/test-manifest"], function() { - -console.log('here 2'); -//console.dir(mocha); - - describe("two test", function() { - it('should work', function(done){ - require('assert').ok(true); - done(); - }); - }); - -console.log('here 3'); - -// mocha.run(function() { -// console.log('running'); -// }); - -console.log('here 4'); - - -/** - - mocha.run(function() { - console.log('here 4'); - }).on('fail', function(test) { - console.log('fail', test); - }).on('pass', function(test) { - console.log('pass', test); - }); - }); - -**/ }); -//setTimeout(function(){}, 3000); +requirejs(["tests/test-manifest"]); From 2d6b4644dfc2561929cdfc57cdc61d7ee01a8a5d Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Fri, 16 May 2014 13:28:48 -0400 Subject: [PATCH 03/31] Make it possible to run node tests from npm/grunt --- gruntfile.js | 22 +++++----------------- package.json | 1 + 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/gruntfile.js b/gruntfile.js index beb6b3f..1440ec6 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -51,22 +51,9 @@ module.exports = function(grunt) { ] }, - connect: { - server: { - options: { - port: 9001, - hostname: '127.0.0.1', - base: '.' - } - } - }, - - mocha: { - test: { - options: { - log: true, - urls: [ 'http://127.0.0.1:9001/tests/index.html' ] - } + shell: { + mocha: { + command: './node_modules/.bin/mocha --reporter list --no-exit tests/node-runner.js' } }, @@ -179,11 +166,11 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-npm'); grunt.loadNpmTasks('grunt-git'); grunt.loadNpmTasks('grunt-prompt'); + grunt.loadNpmTasks('grunt-shell'); grunt.registerTask('develop', ['clean', 'requirejs']); grunt.registerTask('release', ['develop', 'uglify']); grunt.registerTask('check', ['jshint']); - grunt.registerTask('test', ['check', 'connect', 'mocha']); grunt.registerTask('publish', 'Publish filer as a new version to NPM, bower and github.', function(patchLevel) { var allLevels = ['patch', 'minor', 'major']; @@ -214,6 +201,7 @@ module.exports = function(grunt) { 'npm-publish' ]); }); + grunt.registerTask('test', ['check', 'shell:mocha']); grunt.registerTask('default', ['develop']); }; diff --git a/package.json b/package.json index 49af3a1..2eea605 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "grunt-contrib-uglify": "~0.1.2", "grunt-contrib-watch": "~0.3.1", "grunt-git": "0.2.10", + "grunt-shell": "~0.7.0", "grunt-mocha": "0.4.10", "grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck", "grunt-prompt": "^1.1.0", From b0744a7489fb35e9d24263d2d009ca9edd670ecb Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Fri, 16 May 2014 14:34:01 -0400 Subject: [PATCH 04/31] Fix grunt to rebuild dist/filer.js on test runs, alter default grunt task to be test --- gruntfile.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gruntfile.js b/gruntfile.js index 1440ec6..5d911fa 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -201,7 +201,7 @@ module.exports = function(grunt) { 'npm-publish' ]); }); - grunt.registerTask('test', ['check', 'shell:mocha']); + grunt.registerTask('test', ['check', 'develop', 'shell:mocha']); - grunt.registerTask('default', ['develop']); + grunt.registerTask('default', ['test']); }; From 89c44f2f72884a53f3c09c127c6d6eb0c35b272e Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Fri, 16 May 2014 14:46:02 -0400 Subject: [PATCH 05/31] Fix time-based tests to not fail in node, since operations on Memory run faster --- tests/spec/fs.utimes.spec.js | 4 +- tests/spec/time-flags.spec.js | 4 +- tests/spec/times.spec.js | 72 +++++++++++++++++------------------ 3 files changed, 40 insertions(+), 40 deletions(-) diff --git a/tests/spec/fs.utimes.spec.js b/tests/spec/fs.utimes.spec.js index cdf5213..4cddbb1 100644 --- a/tests/spec/fs.utimes.spec.js +++ b/tests/spec/fs.utimes.spec.js @@ -168,8 +168,8 @@ define(["Filer", "util"], function(Filer, util) { // Note: testing estimation as time may differ by a couple of milliseconds // This number should be increased if tests are on slow systems var delta = Date.now() - then; - expect(then - stat.atime).to.be.below(delta); - expect(then - stat.mtime).to.be.below(delta); + expect(then - stat.atime).to.be.at.most(delta); + expect(then - stat.mtime).to.be.at.most(delta); done(); }); }); diff --git a/tests/spec/time-flags.spec.js b/tests/spec/time-flags.spec.js index 49b17a4..3208e1f 100644 --- a/tests/spec/time-flags.spec.js +++ b/tests/spec/time-flags.spec.js @@ -91,9 +91,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(fs, filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); diff --git a/tests/spec/times.spec.js b/tests/spec/times.spec.js index 835b005..f1d9a41 100644 --- a/tests/spec/times.spec.js +++ b/tests/spec/times.spec.js @@ -40,9 +40,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(newfilename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -60,9 +60,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -83,9 +83,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); fs.close(fd, done); }); @@ -188,9 +188,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -250,9 +250,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(dirname, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -273,9 +273,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat('/', function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -294,9 +294,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat('/', function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -367,9 +367,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat('/myfile', function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -447,9 +447,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -466,9 +466,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); - expect(stats2.mtime).to.be.above(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); + expect(stats2.mtime).to.be.at.least(stats1.mtime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -485,9 +485,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -507,9 +507,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -580,9 +580,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); @@ -606,9 +606,9 @@ define(["Filer", "util"], function(Filer, util) { if(error) throw error; stat(filename, function(stats2) { - expect(stats2.ctime).to.be.above(stats1.ctime); + expect(stats2.ctime).to.be.at.least(stats1.ctime); expect(stats2.mtime).to.equal(stats1.mtime); - expect(stats2.atime).to.be.above(stats1.atime); + expect(stats2.atime).to.be.at.least(stats1.atime); done(); }); }); From 9426a700b51f01ef1afad66b2d64882065106e65 Mon Sep 17 00:00:00 2001 From: David Humphrey Date: Sat, 17 May 2014 14:44:29 -0400 Subject: [PATCH 06/31] Generate separate filer for testing in node so we don't overwrite dist/filer.js --- .gitignore | 1 + gruntfile.js | 31 ++++++++++++++++++++++++++++--- tests/node-runner.js | 3 ++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 3af4620..7fd5ccb 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules bower_components .env *~ +dist/filer-test.js diff --git a/gruntfile.js b/gruntfile.js index 5d911fa..a92b69f 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -15,7 +15,7 @@ module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), - clean: ['dist/'], + clean: ['dist/filer-test.js'], uglify: { options: { @@ -81,6 +81,30 @@ module.exports = function(grunt) { } } } + }, + test: { + options: { + paths: { + "src": "../src", + "build": "../build" + }, + baseUrl: "lib", + name: "build/almond", + include: ["src/index"], + out: "dist/filer-test.js", + optimize: "none", + wrap: { + startFile: 'build/wrap.start', + endFile: 'build/wrap.end' + }, + shim: { + // TextEncoder and TextDecoder shims. encoding-indexes must get loaded first, + // and we use a fake one for reduced size, since we only care about utf8. + "encoding": { + deps: ["encoding-indexes-shim"] + } + } + } } }, @@ -168,7 +192,8 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-prompt'); grunt.loadNpmTasks('grunt-shell'); - grunt.registerTask('develop', ['clean', 'requirejs']); + grunt.registerTask('develop', ['clean', 'requirejs:develop']); + grunt.registerTask('filer-test', ['clean', 'requirejs:test']); grunt.registerTask('release', ['develop', 'uglify']); grunt.registerTask('check', ['jshint']); @@ -201,7 +226,7 @@ module.exports = function(grunt) { 'npm-publish' ]); }); - grunt.registerTask('test', ['check', 'develop', 'shell:mocha']); + grunt.registerTask('test', ['check', 'filer-test', 'shell:mocha']); grunt.registerTask('default', ['test']); }; diff --git a/tests/node-runner.js b/tests/node-runner.js index ecaeb4b..260f152 100644 --- a/tests/node-runner.js +++ b/tests/node-runner.js @@ -7,7 +7,8 @@ requirejs.config({ "spec": "../tests/spec", "bugs": "../tests/bugs", "util": "../tests/lib/test-utils", - "Filer": "../dist/filer" + // see gruntfile.js for how dist/filer-test.js gets built + "Filer": "../dist/filer-test" }, baseUrl: "./lib", optimize: "none", From 81b4d26b9087d7732bd54faf8b673c264f300ba6 Mon Sep 17 00:00:00 2001 From: David Humphrey Date: Sat, 17 May 2014 15:17:09 -0400 Subject: [PATCH 07/31] Finish test suite changes for node.js --- tests/lib/indexeddb.js | 18 +++++++++++------- tests/lib/test-utils.js | 6 ++++-- tests/lib/websql.js | 8 +++++--- tests/node-runner.js | 19 ++++++++++--------- 4 files changed, 30 insertions(+), 21 deletions(-) diff --git a/tests/lib/indexeddb.js b/tests/lib/indexeddb.js index 7857ede..aeb467f 100644 --- a/tests/lib/indexeddb.js +++ b/tests/lib/indexeddb.js @@ -1,14 +1,18 @@ define(["Filer"], function(Filer) { - var indexedDB = window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB; + var indexedDB = (function(window) { + return window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; + }(this)); var needsCleanup = []; - window.addEventListener('beforeunload', function() { - needsCleanup.forEach(function(f) { f(); }); - }); + if(typeof window !== 'undefined') { + window.addEventListener('beforeunload', function() { + needsCleanup.forEach(function(f) { f(); }); + }); + } function IndexedDBTestProvider(name) { var _done = false; diff --git a/tests/lib/test-utils.js b/tests/lib/test-utils.js index acea1e0..84d2f3b 100644 --- a/tests/lib/test-utils.js +++ b/tests/lib/test-utils.js @@ -38,7 +38,8 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) { // (e.g., ?filer-provider=IndexedDB). If not specified, we use // the Memory provider by default. See test/require-config.js // for definition of window.filerArgs. - var providerType = window.filerArgs && window.filerArgs.provider ? + var providerType = (typeof window !== 'undefined' && + window.filerArgs && window.filerArgs.provider) ? window.filerArgs.provider : 'Memory'; var name = uniqueName(); @@ -59,7 +60,8 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) { } // Allow passing FS flags on query string - var flags = window.filerArgs && window.filerArgs.flags ? + var flags = (typeof window !== 'undefined' && + window && window.filerArgs && window.filerArgs.flags) ? window.filerArgs.flags : 'FORMAT'; // Create a file system and wait for it to get setup diff --git a/tests/lib/websql.js b/tests/lib/websql.js index ac59498..35f363a 100644 --- a/tests/lib/websql.js +++ b/tests/lib/websql.js @@ -1,9 +1,11 @@ define(["Filer"], function(Filer) { var needsCleanup = []; - window.addEventListener('beforeunload', function() { - needsCleanup.forEach(function(f) { f(); }); - }); + if(typeof window !== 'undefined') { + window.addEventListener('beforeunload', function() { + needsCleanup.forEach(function(f) { f(); }); + }); + } function WebSQLTestProvider(name) { var _done = false; diff --git a/tests/node-runner.js b/tests/node-runner.js index 260f152..7b524f8 100644 --- a/tests/node-runner.js +++ b/tests/node-runner.js @@ -1,5 +1,12 @@ -var requirejs = require('requirejs'); +// If there's something broken in filer or a test, +// requirejs can blow up, and mocha sees it as tests +// not getting added (i.e., it just exists with only +// 1 test run). Display an error so it's clear what happened. +process.on('uncaughtException', function(err) { + console.error('Error in require.js trying to build test suite, filer:\n', err.stack); +}); +var requirejs = require('requirejs'); requirejs.config({ paths: { "tests": "../tests", @@ -22,16 +29,10 @@ requirejs.config({ nodeRequire: require }); -GLOBAL.document = {}; -GLOBAL.navigator = { userAgent: ""}; -GLOBAL.window = { - addEventListener: function(){}, - navigator: navigator, - document: document, - setTimeout: setTimeout -}; +// We use Chai's expect assertions in all the tests via a global GLOBAL.expect = require('chai').expect; +// Workaround for Mocha bug, see https://github.com/visionmedia/mocha/issues/362 describe("Mocha needs one test in order to wait on requirejs tests", function() { it('should wait for other tests', function(){ require('assert').ok(true); From 5fcd313e2f0d640de472a7689261a7a68fac0dea Mon Sep 17 00:00:00 2001 From: David Humphrey Date: Sat, 17 May 2014 15:18:32 -0400 Subject: [PATCH 08/31] Fix issue #56: Support Filer in node.js as an fs alternative --- lib/intercom.js | 17 ++++++++++++----- src/providers/indexeddb.js | 10 ++++++---- src/providers/websql.js | 2 +- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/intercom.js b/lib/intercom.js index 6c3bae8..dfe52e0 100644 --- a/lib/intercom.js +++ b/lib/intercom.js @@ -31,7 +31,8 @@ define(function(require) { } var localStorage = (function(window) { - if (typeof window.localStorage === 'undefined') { + if (typeof window === 'undefined' || + typeof window.localStorage === 'undefined') { return { getItem : function() {}, setItem : function() {}, @@ -53,6 +54,12 @@ define(function(require) { var storageHandler = function() { self._onStorageEvent.apply(self, arguments); }; + + // If we're in node.js, skip event registration + if (typeof window === 'undefined' || typeof document === 'undefined') { + return; + } + if (document.attachEvent) { document.attachEvent('onstorage', storageHandler); } else { @@ -80,7 +87,7 @@ define(function(require) { self._on('storage', lock); listening = true; } - waitTimer = window.setTimeout(lock, WAIT); + waitTimer = setTimeout(lock, WAIT); return; } executed = true; @@ -95,7 +102,7 @@ define(function(require) { self._off('storage', lock); } if (waitTimer) { - window.clearTimeout(waitTimer); + clearTimeout(waitTimer); } localStorage.removeItem(INDEX_LOCK); } @@ -240,7 +247,7 @@ define(function(require) { localStorage.setItem(INDEX_EMIT, data); self.trigger(name, message); - window.setTimeout(function() { + setTimeout(function() { self._cleanup_emit(); }, 50); }); @@ -277,7 +284,7 @@ define(function(require) { localStorage.setItem(INDEX_ONCE, JSON.stringify(data)); fn(); - window.setTimeout(function() { + setTimeout(function() { self._cleanup_once(); }, 50); }); diff --git a/src/providers/indexeddb.js b/src/providers/indexeddb.js index 4975d60..8a42f87 100644 --- a/src/providers/indexeddb.js +++ b/src/providers/indexeddb.js @@ -2,10 +2,12 @@ define(function(require) { var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; - var indexedDB = window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB; + var indexedDB = (function(window) { + return window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; + }(this)); var IDB_RW = require('src/constants').IDB_RW; var IDB_RO = require('src/constants').IDB_RO; diff --git a/src/providers/websql.js b/src/providers/websql.js index c765f8a..67ed6b1 100644 --- a/src/providers/websql.js +++ b/src/providers/websql.js @@ -98,7 +98,7 @@ define(function(require) { this.db = null; } WebSQL.isSupported = function() { - return !!window.openDatabase; + return typeof window === 'undefined' ? false : !!window.openDatabase; }; WebSQL.prototype.open = function(callback) { From 9f33d8503ed17307d86c73dc161bf4636e600744 Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Mon, 19 May 2014 16:47:24 -0400 Subject: [PATCH 09/31] Swapped out XMLHttpRequest for a custom module We made a module to encapsulate the logic that chooses the nodejs or browser dependency that actually downloads a file when the module is used. --- gruntfile.js | 21 ++++++++++- package.json | 11 ++++-- src/network.js | 82 +++++++++++++++++++++++++++++++++++++++++ src/shell/shell.js | 19 +++------- tests/require-config.js | 38 +++++++++++++------ tests/spec/lib.spec.js | 44 ++++++++++++++++++++++ tests/test-manifest.js | 1 + 7 files changed, 185 insertions(+), 31 deletions(-) create mode 100644 src/network.js create mode 100644 tests/spec/lib.spec.js diff --git a/gruntfile.js b/gruntfile.js index a92b69f..b76c968 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -175,6 +175,21 @@ module.exports = function(grunt) { remote: GIT_REMOTE, branch: 'gh-pages', force: true + }, + } + }, + connect: { + server_for_node: { + options: { + port: 1234, + base: '.' + } + }, + server_for_browser: { + options: { + port: 1234, + base: '.', + keepalive: true } } } @@ -191,6 +206,7 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-git'); grunt.loadNpmTasks('grunt-prompt'); grunt.loadNpmTasks('grunt-shell'); + grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask('develop', ['clean', 'requirejs:develop']); grunt.registerTask('filer-test', ['clean', 'requirejs:test']); @@ -214,7 +230,6 @@ module.exports = function(grunt) { ' to ' + semver.inc(currentVersion, patchLevel).yellow + '?'; grunt.config('prompt.confirm.options', promptOpts); - // TODO: ADD NPM RELEASE grunt.task.run([ 'prompt:confirm', 'checkBranch', @@ -226,7 +241,9 @@ module.exports = function(grunt) { 'npm-publish' ]); }); - grunt.registerTask('test', ['check', 'filer-test', 'shell:mocha']); + grunt.registerTask('test-node', ['check', 'filer-test', 'connect:server_for_node', 'shell:mocha']); + grunt.registerTask('test-browser', ['check', 'filer-test', 'connect:server_for_browser']); + grunt.registerTask('test', ['test-node']); grunt.registerTask('default', ['test']); }; diff --git a/package.json b/package.json index 2eea605..d06dcc2 100644 --- a/package.json +++ b/package.json @@ -25,15 +25,17 @@ "url": "https://github.com/js-platform/filer.git" }, "dependencies": { - "bower": "~1.0.0" + "bower": "~1.0.0", + "request": "^2.36.0" }, "devDependencies": { + "chai": "~1.9.1", "grunt": "~0.4.0", "grunt-bump": "0.0.13", "grunt-contrib-clean": "~0.4.0", "grunt-contrib-compress": "~0.4.1", "grunt-contrib-concat": "~0.1.3", - "grunt-contrib-connect": "~0.7.1", + "grunt-contrib-connect": "^0.7.1", "grunt-contrib-jshint": "~0.7.1", "grunt-contrib-requirejs": "~0.4.0", "grunt-contrib-uglify": "~0.1.2", @@ -47,6 +49,7 @@ "semver": "^2.3.0", "requirejs": "~2.1.11", "mocha": "~1.18.2", - "chai": "~1.9.1" - } + "requirejs": "~2.1.11" + }, + "main": "dist/filer_node.js" } diff --git a/src/network.js b/src/network.js new file mode 100644 index 0000000..2a8d46a --- /dev/null +++ b/src/network.js @@ -0,0 +1,82 @@ +define(function(require) { + // Pull in node's request module if possible/needed + if (typeof XMLHttpRequest === 'undefined') { + // This is a stupid workaround for the fact that + // the r.js optimizer checks every require() call + // during optimization and throws an error if it + // can't find the module. + // + // This is only an issue with our browser build + // using `almond` (https://github.com/jrburke/almond) + // which doesn't fallback to node's require when we + // need it to. + var node_req = require; + var request = node_req('request'); + } + + function browserDownload(uri, callback) { + var query = new XMLHttpRequest(); + query.onload = function() { + var err = query.status != 200 ? { message: query.statusText, code: query.status } : null, + data = err ? null : new Uint8Array(query.response); + + callback(err, data); + }; + query.open("GET", uri); + if("withCredentials" in query) { + query.withCredentials = true; + } + + query.responseType = "arraybuffer"; + query.send(); + } + + function nodeDownload(uri, callback) { + request({ + url: uri, + method: "GET", + encoding: null + }, function(err, msg, body) { + var data = null, + arrayBuffer, + statusCode, + arrayLength = body && body.length, + error; + + msg = msg || null; + statusCode = msg && msg.statusCode; + + error = statusCode != 200 ? { message: err || 'Not found!', code: statusCode } : null; + + arrayBuffer = arrayLength && new ArrayBuffer(arrayLength); + + // Convert buffer to Uint8Array + if (arrayBuffer && (statusCode == 200)) { + data = new Uint8Array(arrayBuffer); + for (var i = 0; i < body.length; ++i) { + data[i] = body[i]; + } + } + + callback(error, data); + }); + } + + return { + download: function(uri, callback) { + if (!uri) { + throw('Uri required!'); + } + + if (!callback) { + throw('Callback required'); + } + + if (typeof XMLHttpRequest === "undefined") { + nodeDownload(uri, callback); + } else { + browserDownload(uri, callback); + } + } + }; +}); diff --git a/src/shell/shell.js b/src/shell/shell.js index 0966fd2..167b1b0 100644 --- a/src/shell/shell.js +++ b/src/shell/shell.js @@ -5,6 +5,7 @@ define(function(require) { var Errors = require('src/errors'); var Environment = require('src/shell/environment'); var async = require('async'); + var Network = require('src/network'); require('zip'); require('unzip'); @@ -447,20 +448,18 @@ define(function(require) { // Grab whatever is after the last / (assuming there is one) and // remove any non-filename type chars(i.e., : and /). Like the real // wget, we leave query string or hash portions in tact. - var path = options.filename || url.replace(/[:/]/g, '').split('/').pop(); + var path = options.filename || url.replace(/[:/]/, '').split('/').pop(); path = Path.resolve(fs.cwd, path); function onerror() { - callback(new Error('unable to get resource')); + callback(new Error('unable to get resource')); } - var request = new XMLHttpRequest(); - request.onload = function() { - if(request.status !== 200) { + Network.download('get', url, function(err, data) { + if (err || !data) { return onerror(); } - var data = new Uint8Array(request.response); fs.writeFile(path, data, function(err) { if(err) { callback(err); @@ -468,15 +467,7 @@ define(function(require) { callback(null, path); } }); - }; - request.onerror = onerror; - request.open("GET", url, true); - if("withCredentials" in request) { - request.withCredentials = true; } - - request.responseType = "arraybuffer"; - request.send(); }; Shell.prototype.unzip = function(zipfile, options, callback) { diff --git a/tests/require-config.js b/tests/require-config.js index 2415177..6fb739c 100644 --- a/tests/require-config.js +++ b/tests/require-config.js @@ -7,7 +7,8 @@ // // ?filer-dist/filer.js --> use dist/filer.js // ?filer-dist/filer.min.js --> use dist/filer.min.js -// ? --> (default) use src/filer.js with require +// ?filer-src/filer.js --> use src/filer.js with require +// ? --> (default) use dist/filer-test.js with require var filerArgs = window.filerArgs = {}; var config = (function() { var query = window.location.search.substring(1); @@ -51,24 +52,39 @@ var config = (function() { } // Support src/ filer via require + if(filerArgs['filer-src/filer.js']) { + return { + paths: { + "tests": "../tests", + "src": "../src", + "spec": "../tests/spec", + "bugs": "../tests/bugs", + "util": "../tests/lib/test-utils", + "Filer": "../src/index" + }, + baseUrl: "../lib", + optimize: "none", + shim: { + // TextEncoder and TextDecoder shims. encoding-indexes must get loaded first, + // and we use a fake one for reduced size, since we only care about utf8. + "encoding": { + deps: ["encoding-indexes-shim"] + } + } + }; + } + + // Support dist/filer-test.js return { paths: { "tests": "../tests", - "src": "../src", "spec": "../tests/spec", "bugs": "../tests/bugs", "util": "../tests/lib/test-utils", - "Filer": "../src/index" + "Filer": "../dist/filer-test" }, baseUrl: "../lib", - optimize: "none", - shim: { - // TextEncoder and TextDecoder shims. encoding-indexes must get loaded first, - // and we use a fake one for reduced size, since we only care about utf8. - "encoding": { - deps: ["encoding-indexes-shim"] - } - } + optimize: "none" }; }()); diff --git a/tests/spec/lib.spec.js b/tests/spec/lib.spec.js new file mode 100644 index 0000000..93b76ee --- /dev/null +++ b/tests/spec/lib.spec.js @@ -0,0 +1,44 @@ +define(['../../src/network'], function(network) { + + describe('Network download tool', function() { + if(typeof XMLHttpRequest === "undefined") { + it('should connect to server',function(done) { + var request = require('request'); + request({ + url: 'http://localhost:8080/package.json', + method: 'GET', + encoding: 'utf-8' + }, function(error, msg, body) { + expect(error).not.to.exist; + done(); + }); + }); + } + + it('should throw an exception when a URI is not passed', function(done) { + expect(function() { + network.download(undefined, function(error, data, statusCode) {}); + }).to.throwError; + done(); + }); + + it('should get an error when a non-existent path is specified', function(done) { + network.download('http://localhost:8080/file-non-existent', function(error, data, statusCode) { + expect(error).not.to.exist; + expect(statusCode).to.eql('404'); + expect(data).to.be.a(null); + done(); + }); + }); + + it('should download a resource from the server', function(done) { + network.download('http://localhost:8080/package.json', function(error, data, statusCode) { + expect(error).not.to.exist; + expect(statusCode).to.eql('200'); + expect(data).to.exist; + expect(data).to.have.length.above(0); + done(); + }); + }); + }); +}); diff --git a/tests/test-manifest.js b/tests/test-manifest.js index 668964b..740643b 100644 --- a/tests/test-manifest.js +++ b/tests/test-manifest.js @@ -38,6 +38,7 @@ define([ "spec/time-flags.spec", "spec/fs.watch.spec", "spec/errors.spec", + "spec/lib.spec", // Filer.FileSystem.providers.* "spec/providers/providers.spec", From 3ef2a4e07d01bb599d8e34e3e92c0a9ed0bdb4e1 Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Wed, 21 May 2014 13:06:37 -0400 Subject: [PATCH 10/31] Split the distribution of Filer into two files The AMD-module system Filer uses can't handle require() calls that reference a node module. By creating two distributions we allow the node version to use a full implementation of RequireJS, which gracefully falls back to Node's require() when RequireJS can't find the module in its registered paths. --- .gitignore | 1 + build/{wrap.end => browser_wrap.end} | 0 build/{wrap.start => browser_wrap.start} | 5 +- build/node_wrap.end | 7 + build/node_wrap.start | 16 + dist/filer_node.js | 7920 ++++++++++++++++++++++ gruntfile.js | 68 +- tests/node-runner.js | 2 +- 8 files changed, 8005 insertions(+), 14 deletions(-) rename build/{wrap.end => browser_wrap.end} (100%) rename build/{wrap.start => browser_wrap.start} (92%) create mode 100644 build/node_wrap.end create mode 100644 build/node_wrap.start create mode 100644 dist/filer_node.js diff --git a/.gitignore b/.gitignore index 7fd5ccb..f44e6a2 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ bower_components .env *~ dist/filer-test.js +/dist/filer_node-test.js diff --git a/build/wrap.end b/build/browser_wrap.end similarity index 100% rename from build/wrap.end rename to build/browser_wrap.end diff --git a/build/wrap.start b/build/browser_wrap.start similarity index 92% rename from build/wrap.start rename to build/browser_wrap.start index eba0241..4d12824 100644 --- a/build/wrap.start +++ b/build/browser_wrap.start @@ -13,10 +13,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND (function( root, factory ) { - if ( typeof exports === "object" ) { - // Node - module.exports = factory(); - } else if (typeof define === "function" && define.amd) { + if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define( factory ); } else if( !root.Filer ) { diff --git a/build/node_wrap.end b/build/node_wrap.end new file mode 100644 index 0000000..0515f54 --- /dev/null +++ b/build/node_wrap.end @@ -0,0 +1,7 @@ + + var Filer = require( "src/index" ); + + return Filer; + +})); + diff --git a/build/node_wrap.start b/build/node_wrap.start new file mode 100644 index 0000000..cb49677 --- /dev/null +++ b/build/node_wrap.start @@ -0,0 +1,16 @@ +/* +Copyright (c) 2013, Alan Kligman +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function( root, factory ) { + module.exports = factory(); +}( this, function() { diff --git a/dist/filer_node.js b/dist/filer_node.js new file mode 100644 index 0000000..17954a2 --- /dev/null +++ b/dist/filer_node.js @@ -0,0 +1,7920 @@ +/* +Copyright (c) 2013, Alan Kligman +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function( root, factory ) { + if (typeof exports === "object") { + module.exports = factory(); + } else if (typeof define === "function" && define.amd) { + // AMD. Register as an anonymous module. + define( factory ); + } +}( this, function() { +// Cherry-picked bits of underscore.js, lodash.js + +/** + * Lo-Dash 2.4.0 + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +define('nodash',['require'],function(require) { + + var ArrayProto = Array.prototype; + var nativeForEach = ArrayProto.forEach; + var nativeIndexOf = ArrayProto.indexOf; + var nativeSome = ArrayProto.some; + + var ObjProto = Object.prototype; + var hasOwnProperty = ObjProto.hasOwnProperty; + var nativeKeys = Object.keys; + + var breaker = {}; + + function has(obj, key) { + return hasOwnProperty.call(obj, key); + } + + var keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (has(obj, key)) keys.push(key); + return keys; + }; + + function size(obj) { + if (obj == null) return 0; + return (obj.length === +obj.length) ? obj.length : keys(obj).length; + } + + function identity(value) { + return value; + } + + function each(obj, iterator, context) { + var i, length; + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (i = 0, length = obj.length; i < length; i++) { + if (iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + var keys = keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; + } + } + }; + + function any(obj, iterator, context) { + iterator || (iterator = identity); + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result || (result = iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + function contains(obj, target) { + if (obj == null) return false; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + return any(obj, function(value) { + return value === target; + }); + }; + + function Wrapped(value) { + this.value = value; + } + Wrapped.prototype.has = function(key) { + return has(this.value, key); + }; + Wrapped.prototype.contains = function(target) { + return contains(this.value, target); + }; + Wrapped.prototype.size = function() { + return size(this.value); + }; + + function nodash(value) { + // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor + return (value && typeof value == 'object' && !Array.isArray(value) && hasOwnProperty.call(value, '__wrapped__')) + ? value + : new Wrapped(value); + } + + return nodash; + +}); + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js +define('src/path',[],function() { + + // resolves . and .. elements in a path array with directory names there + // must be no slashes, empty elements, or device names (c:\) in the array + // (so also no leading and trailing slashes - it does not distinguish + // relative and absolute paths) + function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; + } + + // Split a filename into [root, dir, basename, ext], unix version + // 'root' is just a slash, or nothing. + var splitPathRe = + /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/; + var splitPath = function(filename) { + var result = splitPathRe.exec(filename); + return [result[1] || '', result[2] || '', result[3] || '', result[4] || '']; + }; + + // path.resolve([from ...], to) + function resolve() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + // XXXidbfs: we don't have process.cwd() so we use '/' as a fallback + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string' || !path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; + } + + // path.normalize(path) + function normalize(path) { + var isAbsolute = path.charAt(0) === '/', + trailingSlash = path.substr(-1) === '/'; + + // Normalize the path + path = normalizeArray(path.split('/').filter(function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + /* + if (path && trailingSlash) { + path += '/'; + } + */ + + return (isAbsolute ? '/' : '') + path; + } + + function join() { + var paths = Array.prototype.slice.call(arguments, 0); + return normalize(paths.filter(function(p, index) { + return p && typeof p === 'string'; + }).join('/')); + } + + // path.relative(from, to) + function relative(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); + } + + function dirname(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; + } + + function basename(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + // XXXidbfs: node.js just does `return f` + return f === "" ? "/" : f; + } + + function extname(path) { + return splitPath(path)[3]; + } + + function isAbsolute(path) { + if(path.charAt(0) === '/') { + return true; + } + return false; + } + + function isNull(path) { + if (('' + path).indexOf('\u0000') !== -1) { + return true; + } + return false; + } + + // XXXidbfs: we don't support path.exists() or path.existsSync(), which + // are deprecated, and need a FileSystem instance to work. Use fs.stat(). + + return { + normalize: normalize, + resolve: resolve, + join: join, + relative: relative, + sep: '/', + delimiter: ':', + dirname: dirname, + basename: basename, + extname: extname, + isAbsolute: isAbsolute, + isNull: isNull + }; + +}); + +/* +CryptoJS v3.0.2 +code.google.com/p/crypto-js +(c) 2009-2012 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +var CryptoJS=CryptoJS||function(i,p){var f={},q=f.lib={},j=q.Base=function(){function a(){}return{extend:function(h){a.prototype=this;var d=new a;h&&d.mixIn(h);d.$super=this;return d},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var d in a)a.hasOwnProperty(d)&&(this[d]=a[d]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),k=q.WordArray=j.extend({init:function(a,h){a= +this.words=a||[];this.sigBytes=h!=p?h:4*a.length},toString:function(a){return(a||m).stringify(this)},concat:function(a){var h=this.words,d=a.words,c=this.sigBytes,a=a.sigBytes;this.clamp();if(c%4)for(var b=0;b>>2]|=(d[b>>>2]>>>24-8*(b%4)&255)<<24-8*((c+b)%4);else if(65535>>2]=d[b>>>2];else h.push.apply(h,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<32-8*(b%4);a.length=i.ceil(b/4)},clone:function(){var a= +j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],d=0;d>>2]>>>24-8*(c%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>3]|=parseInt(a.substr(c,2),16)<<24-4*(c%8);return k.create(d,b/2)}},s=r.Latin1={stringify:function(a){for(var b= +a.words,a=a.sigBytes,d=[],c=0;c>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return k.create(d,b)}},g=r.Utf8={stringify:function(a){try{return decodeURIComponent(escape(s.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return s.parse(unescape(encodeURIComponent(a)))}},b=q.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=k.create(); +this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=g.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,c=b.sigBytes,e=this.blockSize,f=c/(4*e),f=a?i.ceil(f):i.max((f|0)-this._minBufferSize,0),a=f*e,c=i.min(4*a,c);if(a){for(var g=0;ge;)f(b)&&(8>e&&(k[e]=g(i.pow(b,0.5))),r[e]=g(i.pow(b,1/3)),e++),b++})();var m=[],j=j.SHA256=f.extend({_doReset:function(){this._hash=q.create(k.slice(0))},_doProcessBlock:function(f,g){for(var b=this._hash.words,e=b[0],a=b[1],h=b[2],d=b[3],c=b[4],i=b[5],j=b[6],k=b[7],l=0;64> +l;l++){if(16>l)m[l]=f[g+l]|0;else{var n=m[l-15],o=m[l-2];m[l]=((n<<25|n>>>7)^(n<<14|n>>>18)^n>>>3)+m[l-7]+((o<<15|o>>>17)^(o<<13|o>>>19)^o>>>10)+m[l-16]}n=k+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&i^~c&j)+r[l]+m[l];o=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&a^e&h^a&h);k=j;j=i;i=c;c=d+n|0;d=h;h=a;a=e;e=n+o|0}b[0]=b[0]+e|0;b[1]=b[1]+a|0;b[2]=b[2]+h|0;b[3]=b[3]+d|0;b[4]=b[4]+c|0;b[5]=b[5]+i|0;b[6]=b[6]+j|0;b[7]=b[7]+k|0},_doFinalize:function(){var f=this._data,g=f.words,b=8*this._nDataBytes, +e=8*f.sigBytes;g[e>>>5]|=128<<24-e%32;g[(e+64>>>9<<4)+15]=b;f.sigBytes=4*g.length;this._process()}});p.SHA256=f._createHelper(j);p.HmacSHA256=f._createHmacHelper(j)})(Math); + +define("crypto-js/rollups/sha256", function(){}); + +define('src/shared',['require','crypto-js/rollups/sha256'],function(require) { + + require("crypto-js/rollups/sha256"); var Crypto = CryptoJS; + + function guid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); + return v.toString(16); + }).toUpperCase(); + } + + function hash(string) { + return Crypto.SHA256(string).toString(Crypto.enc.hex); + } + + function nop() {} + + /** + * Convert a Uint8Array to a regular array + */ + function u8toArray(u8) { + var array = []; + var len = u8.length; + for(var i = 0; i < len; i++) { + array[i] = u8[i]; + } + return array; + } + + return { + guid: guid, + hash: hash, + u8toArray: u8toArray, + nop: nop + }; + +}); + +define('src/constants',['require'],function(require) { + + var O_READ = 'READ'; + var O_WRITE = 'WRITE'; + var O_CREATE = 'CREATE'; + var O_EXCLUSIVE = 'EXCLUSIVE'; + var O_TRUNCATE = 'TRUNCATE'; + var O_APPEND = 'APPEND'; + var XATTR_CREATE = 'CREATE'; + var XATTR_REPLACE = 'REPLACE'; + + return { + FILE_SYSTEM_NAME: 'local', + + FILE_STORE_NAME: 'files', + + IDB_RO: 'readonly', + IDB_RW: 'readwrite', + + WSQL_VERSION: "1", + WSQL_SIZE: 5 * 1024 * 1024, + WSQL_DESC: "FileSystem Storage", + + MODE_FILE: 'FILE', + MODE_DIRECTORY: 'DIRECTORY', + MODE_SYMBOLIC_LINK: 'SYMLINK', + MODE_META: 'META', + + SYMLOOP_MAX: 10, + + BINARY_MIME_TYPE: 'application/octet-stream', + JSON_MIME_TYPE: 'application/json', + + ROOT_DIRECTORY_NAME: '/', // basename(normalize(path)) + + // FS Mount Flags + FS_FORMAT: 'FORMAT', + FS_NOCTIME: 'NOCTIME', + FS_NOMTIME: 'NOMTIME', + + // FS File Open Flags + O_READ: O_READ, + O_WRITE: O_WRITE, + O_CREATE: O_CREATE, + O_EXCLUSIVE: O_EXCLUSIVE, + O_TRUNCATE: O_TRUNCATE, + O_APPEND: O_APPEND, + + O_FLAGS: { + 'r': [O_READ], + 'r+': [O_READ, O_WRITE], + 'w': [O_WRITE, O_CREATE, O_TRUNCATE], + 'w+': [O_WRITE, O_READ, O_CREATE, O_TRUNCATE], + 'wx': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], + 'wx+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], + 'a': [O_WRITE, O_CREATE, O_APPEND], + 'a+': [O_WRITE, O_READ, O_CREATE, O_APPEND], + 'ax': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_APPEND], + 'ax+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_APPEND] + }, + + XATTR_CREATE: XATTR_CREATE, + XATTR_REPLACE: XATTR_REPLACE, + + FS_READY: 'READY', + FS_PENDING: 'PENDING', + FS_ERROR: 'ERROR', + + SUPER_NODE_ID: '00000000-0000-0000-0000-000000000000', + + ENVIRONMENT: { + TMP: '/tmp', + PATH: '' + } + }; + +}); +define('src/errors',['require'],function(require) { + var errors = {}; + [ + /** + * node.js errors + */ + '-1:UNKNOWN:unknown error', + '0:OK:success', + '1:EOF:end of file', + '2:EADDRINFO:getaddrinfo error', + '3:EACCES:permission denied', + '4:EAGAIN:resource temporarily unavailable', + '5:EADDRINUSE:address already in use', + '6:EADDRNOTAVAIL:address not available', + '7:EAFNOSUPPORT:address family not supported', + '8:EALREADY:connection already in progress', + '9:EBADF:bad file descriptor', + '10:EBUSY:resource busy or locked', + '11:ECONNABORTED:software caused connection abort', + '12:ECONNREFUSED:connection refused', + '13:ECONNRESET:connection reset by peer', + '14:EDESTADDRREQ:destination address required', + '15:EFAULT:bad address in system call argument', + '16:EHOSTUNREACH:host is unreachable', + '17:EINTR:interrupted system call', + '18:EINVAL:invalid argument', + '19:EISCONN:socket is already connected', + '20:EMFILE:too many open files', + '21:EMSGSIZE:message too long', + '22:ENETDOWN:network is down', + '23:ENETUNREACH:network is unreachable', + '24:ENFILE:file table overflow', + '25:ENOBUFS:no buffer space available', + '26:ENOMEM:not enough memory', + '27:ENOTDIR:not a directory', + '28:EISDIR:illegal operation on a directory', + '29:ENONET:machine is not on the network', + // errno 30 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js + '31:ENOTCONN:socket is not connected', + '32:ENOTSOCK:socket operation on non-socket', + '33:ENOTSUP:operation not supported on socket', + '34:ENOENT:no such file or directory', + '35:ENOSYS:function not implemented', + '36:EPIPE:broken pipe', + '37:EPROTO:protocol error', + '38:EPROTONOSUPPORT:protocol not supported', + '39:EPROTOTYPE:protocol wrong type for socket', + '40:ETIMEDOUT:connection timed out', + '41:ECHARSET:invalid Unicode character', + '42:EAIFAMNOSUPPORT:address family for hostname not supported', + // errno 43 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js + '44:EAISERVICE:servname not supported for ai_socktype', + '45:EAISOCKTYPE:ai_socktype not supported', + '46:ESHUTDOWN:cannot send after transport endpoint shutdown', + '47:EEXIST:file already exists', + '48:ESRCH:no such process', + '49:ENAMETOOLONG:name too long', + '50:EPERM:operation not permitted', + '51:ELOOP:too many symbolic links encountered', + '52:EXDEV:cross-device link not permitted', + '53:ENOTEMPTY:directory not empty', + '54:ENOSPC:no space left on device', + '55:EIO:i/o error', + '56:EROFS:read-only file system', + '57:ENODEV:no such device', + '58:ESPIPE:invalid seek', + '59:ECANCELED:operation canceled', + + /** + * Filer specific errors + */ + '1000:ENOTMOUNTED:not mounted', + '1001:EFILESYSTEMERROR:missing super node, use \'FORMAT\' flag to format filesystem.', + '1002:ENOATTR:attribute does not exist' + ].forEach(function(e) { + e = e.split(':'); + var errno = e[0], + err = e[1], + message = e[2]; + + function ctor(m) { + this.message = m || message; + } + var proto = ctor.prototype = new Error(); + proto.errno = errno; + proto.code = err; + proto.constructor = ctor; + + // We expose the error as both Errors.EINVAL and Errors[18] + errors[err] = errors[errno] = ctor; + }); + + return errors; +}); + +define('src/providers/indexeddb',['require','src/constants','src/constants','src/constants','src/constants','src/errors'],function(require) { + var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; + var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; + + var indexedDB = (function(window) { + return window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; + }(this)); + + var IDB_RW = require('src/constants').IDB_RW; + var IDB_RO = require('src/constants').IDB_RO; + var Errors = require('src/errors'); + + function IndexedDBContext(db, mode) { + var transaction = db.transaction(FILE_STORE_NAME, mode); + this.objectStore = transaction.objectStore(FILE_STORE_NAME); + } + IndexedDBContext.prototype.clear = function(callback) { + try { + var request = this.objectStore.clear(); + request.onsuccess = function(event) { + callback(); + }; + request.onerror = function(error) { + callback(error); + }; + } catch(e) { + callback(e); + } + }; + IndexedDBContext.prototype.get = function(key, callback) { + try { + var request = this.objectStore.get(key); + request.onsuccess = function onsuccess(event) { + var result = event.target.result; + callback(null, result); + }; + request.onerror = function onerror(error) { + callback(error); + }; + } catch(e) { + callback(e); + } + }; + IndexedDBContext.prototype.put = function(key, value, callback) { + try { + var request = this.objectStore.put(value, key); + request.onsuccess = function onsuccess(event) { + var result = event.target.result; + callback(null, result); + }; + request.onerror = function onerror(error) { + callback(error); + }; + } catch(e) { + callback(e); + } + }; + IndexedDBContext.prototype.delete = function(key, callback) { + try { + var request = this.objectStore.delete(key); + request.onsuccess = function onsuccess(event) { + var result = event.target.result; + callback(null, result); + }; + request.onerror = function(error) { + callback(error); + }; + } catch(e) { + callback(e); + } + }; + + + function IndexedDB(name) { + this.name = name || FILE_SYSTEM_NAME; + this.db = null; + } + IndexedDB.isSupported = function() { + return !!indexedDB; + }; + + IndexedDB.prototype.open = function(callback) { + var that = this; + + // Bail if we already have a db open + if( that.db ) { + callback(null, false); + return; + } + + // Keep track of whether we're accessing this db for the first time + // and therefore needs to get formatted. + var firstAccess = false; + + // NOTE: we're not using versioned databases. + var openRequest = indexedDB.open(that.name); + + // If the db doesn't exist, we'll create it + openRequest.onupgradeneeded = function onupgradeneeded(event) { + var db = event.target.result; + + if(db.objectStoreNames.contains(FILE_STORE_NAME)) { + db.deleteObjectStore(FILE_STORE_NAME); + } + db.createObjectStore(FILE_STORE_NAME); + + firstAccess = true; + }; + + openRequest.onsuccess = function onsuccess(event) { + that.db = event.target.result; + callback(null, firstAccess); + }; + openRequest.onerror = function onerror(error) { + callback(new Errors.EINVAL('IndexedDB cannot be accessed. If private browsing is enabled, disable it.')); + }; + }; + IndexedDB.prototype.getReadOnlyContext = function() { + // Due to timing issues in Chrome with readwrite vs. readonly indexeddb transactions + // always use readwrite so we can make sure pending commits finish before callbacks. + // See https://github.com/js-platform/filer/issues/128 + return new IndexedDBContext(this.db, IDB_RW); + }; + IndexedDB.prototype.getReadWriteContext = function() { + return new IndexedDBContext(this.db, IDB_RW); + }; + + return IndexedDB; +}); + +define('src/providers/websql',['require','src/constants','src/constants','src/constants','src/constants','src/constants','src/shared','src/errors'],function(require) { + var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; + var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; + var WSQL_VERSION = require('src/constants').WSQL_VERSION; + var WSQL_SIZE = require('src/constants').WSQL_SIZE; + var WSQL_DESC = require('src/constants').WSQL_DESC; + var u8toArray = require('src/shared').u8toArray; + var Errors = require('src/errors'); + + function WebSQLContext(db, isReadOnly) { + var that = this; + this.getTransaction = function(callback) { + if(that.transaction) { + callback(that.transaction); + return; + } + // Either do readTransaction() (read-only) or transaction() (read/write) + db[isReadOnly ? 'readTransaction' : 'transaction'](function(transaction) { + that.transaction = transaction; + callback(transaction); + }); + }; + } + WebSQLContext.prototype.clear = function(callback) { + function onError(transaction, error) { + callback(error); + } + function onSuccess(transaction, result) { + callback(null); + } + this.getTransaction(function(transaction) { + transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + ";", + [], onSuccess, onError); + }); + }; + WebSQLContext.prototype.get = function(key, callback) { + function onSuccess(transaction, result) { + // If the key isn't found, return null + var value = result.rows.length === 0 ? null : result.rows.item(0).data; + try { + if(value) { + value = JSON.parse(value); + // Deal with special-cased flattened typed arrays in WebSQL (see put() below) + if(value.__isUint8Array) { + value = new Uint8Array(value.__array); + } + } + callback(null, value); + } catch(e) { + callback(e); + } + } + function onError(transaction, error) { + callback(error); + } + this.getTransaction(function(transaction) { + transaction.executeSql("SELECT data FROM " + FILE_STORE_NAME + " WHERE id = ?;", + [key], onSuccess, onError); + }); + }; + WebSQLContext.prototype.put = function(key, value, callback) { + // We do extra work to make sure typed arrays survive + // being stored in the db and still get the right prototype later. + if(Object.prototype.toString.call(value) === "[object Uint8Array]") { + value = { + __isUint8Array: true, + __array: u8toArray(value) + }; + } + value = JSON.stringify(value); + function onSuccess(transaction, result) { + callback(null); + } + function onError(transaction, error) { + callback(error); + } + this.getTransaction(function(transaction) { + transaction.executeSql("INSERT OR REPLACE INTO " + FILE_STORE_NAME + " (id, data) VALUES (?, ?);", + [key, value], onSuccess, onError); + }); + }; + WebSQLContext.prototype.delete = function(key, callback) { + function onSuccess(transaction, result) { + callback(null); + } + function onError(transaction, error) { + callback(error); + } + this.getTransaction(function(transaction) { + transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + " WHERE id = ?;", + [key], onSuccess, onError); + }); + }; + + + function WebSQL(name) { + this.name = name || FILE_SYSTEM_NAME; + this.db = null; + } + WebSQL.isSupported = function() { + return typeof window === 'undefined' ? false : !!window.openDatabase; + }; + + WebSQL.prototype.open = function(callback) { + var that = this; + + // Bail if we already have a db open + if(that.db) { + callback(null, false); + return; + } + + var db = window.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE); + if(!db) { + callback("[WebSQL] Unable to open database."); + return; + } + + function onError(transaction, error) { + if (error.code === 5) { + callback(new Errors.EINVAL('WebSQL cannot be accessed. If private browsing is enabled, disable it.')); + } + callback(error); + } + function onSuccess(transaction, result) { + that.db = db; + + function gotCount(transaction, result) { + var firstAccess = result.rows.item(0).count === 0; + callback(null, firstAccess); + } + function onError(transaction, error) { + callback(error); + } + // Keep track of whether we're accessing this db for the first time + // and therefore needs to get formatted. + transaction.executeSql("SELECT COUNT(id) AS count FROM " + FILE_STORE_NAME + ";", + [], gotCount, onError); + } + + // Create the table and index we'll need to store the fs data. + db.transaction(function(transaction) { + function createIndex(transaction) { + transaction.executeSql("CREATE INDEX IF NOT EXISTS idx_" + FILE_STORE_NAME + "_id" + + " on " + FILE_STORE_NAME + " (id);", + [], onSuccess, onError); + } + transaction.executeSql("CREATE TABLE IF NOT EXISTS " + FILE_STORE_NAME + " (id unique, data TEXT);", + [], createIndex, onError); + }); + }; + WebSQL.prototype.getReadOnlyContext = function() { + return new WebSQLContext(this.db, true); + }; + WebSQL.prototype.getReadWriteContext = function() { + return new WebSQLContext(this.db, false); + }; + + return WebSQL; +}); + +/*global setImmediate: false, setTimeout: false, console: false */ + +/** + * https://raw.github.com/caolan/async/master/lib/async.js Feb 18, 2014 + * Used under MIT - https://github.com/caolan/async/blob/master/LICENSE + */ + +(function () { + + var async = {}; + + // global on the server, window in the browser + var root, previous_async; + + root = this; + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + var called = false; + return function() { + if (called) throw new Error("Callback was already called."); + called = true; + fn.apply(root, arguments); + } + } + + //// cross-browser compatiblity functions //// + + var _each = function (arr, iterator) { + if (arr.forEach) { + return arr.forEach(iterator); + } + for (var i = 0; i < arr.length; i += 1) { + iterator(arr[i], i, arr); + } + }; + + var _map = function (arr, iterator) { + if (arr.map) { + return arr.map(iterator); + } + var results = []; + _each(arr, function (x, i, a) { + results.push(iterator(x, i, a)); + }); + return results; + }; + + var _reduce = function (arr, iterator, memo) { + if (arr.reduce) { + return arr.reduce(iterator, memo); + } + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _keys = function (obj) { + if (Object.keys) { + return Object.keys(obj); + } + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + if (typeof process === 'undefined' || !(process.nextTick)) { + if (typeof setImmediate === 'function') { + async.nextTick = function (fn) { + // not a direct alias for IE10 compatibility + setImmediate(fn); + }; + async.setImmediate = async.nextTick; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (typeof setImmediate !== 'undefined') { + async.setImmediate = function (fn) { + // not a direct alias for IE10 compatibility + setImmediate(fn); + }; + } + else { + async.setImmediate = async.nextTick; + } + } + + async.each = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + _each(arr, function (x) { + iterator(x, only_once(function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(null); + } + } + })); + }); + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(null); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = function () {}; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || function () {}; + var keys = _keys(tasks); + if (!keys.length) { + return callback(null); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (_keys(results).length === keys.length) { + callback(null, results); + callback = function () {}; + } + }); + + _each(keys, function (k) { + var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; + var taskCallback = function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = function () {}; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.waterfall = function (tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor !== Array) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = function () {}; + } + else { + var args = Array.prototype.slice.call(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor === Array) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor === Array) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return fn.apply( + null, args.concat(Array.prototype.slice.call(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + if (test()) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + if (!test()) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + function _insert(q, data, pos, callback) { + if(data.constructor !== Array) { + data = [data]; + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + } + }; + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + push: function (data, callback) { + if(data.constructor !== Array) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain) cargo.drain(); + return; + } + + var ts = typeof payload === 'number' + ? tasks.splice(0, payload) + : tasks.splice(0); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + callback.apply(null, memo[key]); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = arguments; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.compose = function (/* functions... */) { + var fns = Array.prototype.reverse.call(arguments); + return function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = Array.prototype.slice.call(arguments, 1); + cb(err, nextargs); + }])) + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = Array.prototype.slice.call(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // AMD / RequireJS + if (typeof define !== 'undefined' && define.amd) { + define('async',[], function () { + return async; + }); + } + // Node.js + else if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // included directly via - +
diff --git a/tests/index.js b/tests/index.js new file mode 100644 index 0000000..ad8150c --- /dev/null +++ b/tests/index.js @@ -0,0 +1,8 @@ +// Tests to be run are defined in test-manifest.js + +// For Nodejs context, expose chai's expect method +if (typeof GLOBAL !== "undefined") { + GLOBAL.expect = require('chai').expect; +} + +require('./test-manifest.js'); From 823232fc678abe3402123f24478b228249daea7e Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Mon, 26 May 2014 16:57:08 -0400 Subject: [PATCH 23/31] Review fixes --- dist/filer_node.js | 7920 ----------------------------------- gruntfile.js | 34 +- tests/index.html | 6 +- tests/index.js | 6 - tests/spec/shell/cd.spec.js | 1 + 5 files changed, 13 insertions(+), 7954 deletions(-) delete mode 100644 dist/filer_node.js diff --git a/dist/filer_node.js b/dist/filer_node.js deleted file mode 100644 index 17954a2..0000000 --- a/dist/filer_node.js +++ /dev/null @@ -1,7920 +0,0 @@ -/* -Copyright (c) 2013, Alan Kligman -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -(function( root, factory ) { - if (typeof exports === "object") { - module.exports = factory(); - } else if (typeof define === "function" && define.amd) { - // AMD. Register as an anonymous module. - define( factory ); - } -}( this, function() { -// Cherry-picked bits of underscore.js, lodash.js - -/** - * Lo-Dash 2.4.0 - * Copyright 2012-2013 The Dojo Foundation - * Based on Underscore.js 1.5.2 - * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ - -define('nodash',['require'],function(require) { - - var ArrayProto = Array.prototype; - var nativeForEach = ArrayProto.forEach; - var nativeIndexOf = ArrayProto.indexOf; - var nativeSome = ArrayProto.some; - - var ObjProto = Object.prototype; - var hasOwnProperty = ObjProto.hasOwnProperty; - var nativeKeys = Object.keys; - - var breaker = {}; - - function has(obj, key) { - return hasOwnProperty.call(obj, key); - } - - var keys = nativeKeys || function(obj) { - if (obj !== Object(obj)) throw new TypeError('Invalid object'); - var keys = []; - for (var key in obj) if (has(obj, key)) keys.push(key); - return keys; - }; - - function size(obj) { - if (obj == null) return 0; - return (obj.length === +obj.length) ? obj.length : keys(obj).length; - } - - function identity(value) { - return value; - } - - function each(obj, iterator, context) { - var i, length; - if (obj == null) return; - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - } else if (obj.length === +obj.length) { - for (i = 0, length = obj.length; i < length; i++) { - if (iterator.call(context, obj[i], i, obj) === breaker) return; - } - } else { - var keys = keys(obj); - for (i = 0, length = keys.length; i < length; i++) { - if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; - } - } - }; - - function any(obj, iterator, context) { - iterator || (iterator = identity); - var result = false; - if (obj == null) return result; - if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); - each(obj, function(value, index, list) { - if (result || (result = iterator.call(context, value, index, list))) return breaker; - }); - return !!result; - }; - - function contains(obj, target) { - if (obj == null) return false; - if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; - return any(obj, function(value) { - return value === target; - }); - }; - - function Wrapped(value) { - this.value = value; - } - Wrapped.prototype.has = function(key) { - return has(this.value, key); - }; - Wrapped.prototype.contains = function(target) { - return contains(this.value, target); - }; - Wrapped.prototype.size = function() { - return size(this.value); - }; - - function nodash(value) { - // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor - return (value && typeof value == 'object' && !Array.isArray(value) && hasOwnProperty.call(value, '__wrapped__')) - ? value - : new Wrapped(value); - } - - return nodash; - -}); - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js -define('src/path',[],function() { - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/; - var splitPath = function(filename) { - var result = splitPathRe.exec(filename); - return [result[1] || '', result[2] || '', result[3] || '', result[4] || '']; - }; - - // path.resolve([from ...], to) - function resolve() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - // XXXidbfs: we don't have process.cwd() so we use '/' as a fallback - var path = (i >= 0) ? arguments[i] : '/'; - - // Skip empty and invalid entries - if (typeof path !== 'string' || !path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - } - - // path.normalize(path) - function normalize(path) { - var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.substr(-1) === '/'; - - // Normalize the path - path = normalizeArray(path.split('/').filter(function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - /* - if (path && trailingSlash) { - path += '/'; - } - */ - - return (isAbsolute ? '/' : '') + path; - } - - function join() { - var paths = Array.prototype.slice.call(arguments, 0); - return normalize(paths.filter(function(p, index) { - return p && typeof p === 'string'; - }).join('/')); - } - - // path.relative(from, to) - function relative(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - } - - function dirname(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - } - - function basename(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - // XXXidbfs: node.js just does `return f` - return f === "" ? "/" : f; - } - - function extname(path) { - return splitPath(path)[3]; - } - - function isAbsolute(path) { - if(path.charAt(0) === '/') { - return true; - } - return false; - } - - function isNull(path) { - if (('' + path).indexOf('\u0000') !== -1) { - return true; - } - return false; - } - - // XXXidbfs: we don't support path.exists() or path.existsSync(), which - // are deprecated, and need a FileSystem instance to work. Use fs.stat(). - - return { - normalize: normalize, - resolve: resolve, - join: join, - relative: relative, - sep: '/', - delimiter: ':', - dirname: dirname, - basename: basename, - extname: extname, - isAbsolute: isAbsolute, - isNull: isNull - }; - -}); - -/* -CryptoJS v3.0.2 -code.google.com/p/crypto-js -(c) 2009-2012 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -var CryptoJS=CryptoJS||function(i,p){var f={},q=f.lib={},j=q.Base=function(){function a(){}return{extend:function(h){a.prototype=this;var d=new a;h&&d.mixIn(h);d.$super=this;return d},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var d in a)a.hasOwnProperty(d)&&(this[d]=a[d]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),k=q.WordArray=j.extend({init:function(a,h){a= -this.words=a||[];this.sigBytes=h!=p?h:4*a.length},toString:function(a){return(a||m).stringify(this)},concat:function(a){var h=this.words,d=a.words,c=this.sigBytes,a=a.sigBytes;this.clamp();if(c%4)for(var b=0;b>>2]|=(d[b>>>2]>>>24-8*(b%4)&255)<<24-8*((c+b)%4);else if(65535>>2]=d[b>>>2];else h.push.apply(h,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<32-8*(b%4);a.length=i.ceil(b/4)},clone:function(){var a= -j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],d=0;d>>2]>>>24-8*(c%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>3]|=parseInt(a.substr(c,2),16)<<24-4*(c%8);return k.create(d,b/2)}},s=r.Latin1={stringify:function(a){for(var b= -a.words,a=a.sigBytes,d=[],c=0;c>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return k.create(d,b)}},g=r.Utf8={stringify:function(a){try{return decodeURIComponent(escape(s.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return s.parse(unescape(encodeURIComponent(a)))}},b=q.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=k.create(); -this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=g.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,c=b.sigBytes,e=this.blockSize,f=c/(4*e),f=a?i.ceil(f):i.max((f|0)-this._minBufferSize,0),a=f*e,c=i.min(4*a,c);if(a){for(var g=0;ge;)f(b)&&(8>e&&(k[e]=g(i.pow(b,0.5))),r[e]=g(i.pow(b,1/3)),e++),b++})();var m=[],j=j.SHA256=f.extend({_doReset:function(){this._hash=q.create(k.slice(0))},_doProcessBlock:function(f,g){for(var b=this._hash.words,e=b[0],a=b[1],h=b[2],d=b[3],c=b[4],i=b[5],j=b[6],k=b[7],l=0;64> -l;l++){if(16>l)m[l]=f[g+l]|0;else{var n=m[l-15],o=m[l-2];m[l]=((n<<25|n>>>7)^(n<<14|n>>>18)^n>>>3)+m[l-7]+((o<<15|o>>>17)^(o<<13|o>>>19)^o>>>10)+m[l-16]}n=k+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&i^~c&j)+r[l]+m[l];o=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&a^e&h^a&h);k=j;j=i;i=c;c=d+n|0;d=h;h=a;a=e;e=n+o|0}b[0]=b[0]+e|0;b[1]=b[1]+a|0;b[2]=b[2]+h|0;b[3]=b[3]+d|0;b[4]=b[4]+c|0;b[5]=b[5]+i|0;b[6]=b[6]+j|0;b[7]=b[7]+k|0},_doFinalize:function(){var f=this._data,g=f.words,b=8*this._nDataBytes, -e=8*f.sigBytes;g[e>>>5]|=128<<24-e%32;g[(e+64>>>9<<4)+15]=b;f.sigBytes=4*g.length;this._process()}});p.SHA256=f._createHelper(j);p.HmacSHA256=f._createHmacHelper(j)})(Math); - -define("crypto-js/rollups/sha256", function(){}); - -define('src/shared',['require','crypto-js/rollups/sha256'],function(require) { - - require("crypto-js/rollups/sha256"); var Crypto = CryptoJS; - - function guid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); - return v.toString(16); - }).toUpperCase(); - } - - function hash(string) { - return Crypto.SHA256(string).toString(Crypto.enc.hex); - } - - function nop() {} - - /** - * Convert a Uint8Array to a regular array - */ - function u8toArray(u8) { - var array = []; - var len = u8.length; - for(var i = 0; i < len; i++) { - array[i] = u8[i]; - } - return array; - } - - return { - guid: guid, - hash: hash, - u8toArray: u8toArray, - nop: nop - }; - -}); - -define('src/constants',['require'],function(require) { - - var O_READ = 'READ'; - var O_WRITE = 'WRITE'; - var O_CREATE = 'CREATE'; - var O_EXCLUSIVE = 'EXCLUSIVE'; - var O_TRUNCATE = 'TRUNCATE'; - var O_APPEND = 'APPEND'; - var XATTR_CREATE = 'CREATE'; - var XATTR_REPLACE = 'REPLACE'; - - return { - FILE_SYSTEM_NAME: 'local', - - FILE_STORE_NAME: 'files', - - IDB_RO: 'readonly', - IDB_RW: 'readwrite', - - WSQL_VERSION: "1", - WSQL_SIZE: 5 * 1024 * 1024, - WSQL_DESC: "FileSystem Storage", - - MODE_FILE: 'FILE', - MODE_DIRECTORY: 'DIRECTORY', - MODE_SYMBOLIC_LINK: 'SYMLINK', - MODE_META: 'META', - - SYMLOOP_MAX: 10, - - BINARY_MIME_TYPE: 'application/octet-stream', - JSON_MIME_TYPE: 'application/json', - - ROOT_DIRECTORY_NAME: '/', // basename(normalize(path)) - - // FS Mount Flags - FS_FORMAT: 'FORMAT', - FS_NOCTIME: 'NOCTIME', - FS_NOMTIME: 'NOMTIME', - - // FS File Open Flags - O_READ: O_READ, - O_WRITE: O_WRITE, - O_CREATE: O_CREATE, - O_EXCLUSIVE: O_EXCLUSIVE, - O_TRUNCATE: O_TRUNCATE, - O_APPEND: O_APPEND, - - O_FLAGS: { - 'r': [O_READ], - 'r+': [O_READ, O_WRITE], - 'w': [O_WRITE, O_CREATE, O_TRUNCATE], - 'w+': [O_WRITE, O_READ, O_CREATE, O_TRUNCATE], - 'wx': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], - 'wx+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], - 'a': [O_WRITE, O_CREATE, O_APPEND], - 'a+': [O_WRITE, O_READ, O_CREATE, O_APPEND], - 'ax': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_APPEND], - 'ax+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_APPEND] - }, - - XATTR_CREATE: XATTR_CREATE, - XATTR_REPLACE: XATTR_REPLACE, - - FS_READY: 'READY', - FS_PENDING: 'PENDING', - FS_ERROR: 'ERROR', - - SUPER_NODE_ID: '00000000-0000-0000-0000-000000000000', - - ENVIRONMENT: { - TMP: '/tmp', - PATH: '' - } - }; - -}); -define('src/errors',['require'],function(require) { - var errors = {}; - [ - /** - * node.js errors - */ - '-1:UNKNOWN:unknown error', - '0:OK:success', - '1:EOF:end of file', - '2:EADDRINFO:getaddrinfo error', - '3:EACCES:permission denied', - '4:EAGAIN:resource temporarily unavailable', - '5:EADDRINUSE:address already in use', - '6:EADDRNOTAVAIL:address not available', - '7:EAFNOSUPPORT:address family not supported', - '8:EALREADY:connection already in progress', - '9:EBADF:bad file descriptor', - '10:EBUSY:resource busy or locked', - '11:ECONNABORTED:software caused connection abort', - '12:ECONNREFUSED:connection refused', - '13:ECONNRESET:connection reset by peer', - '14:EDESTADDRREQ:destination address required', - '15:EFAULT:bad address in system call argument', - '16:EHOSTUNREACH:host is unreachable', - '17:EINTR:interrupted system call', - '18:EINVAL:invalid argument', - '19:EISCONN:socket is already connected', - '20:EMFILE:too many open files', - '21:EMSGSIZE:message too long', - '22:ENETDOWN:network is down', - '23:ENETUNREACH:network is unreachable', - '24:ENFILE:file table overflow', - '25:ENOBUFS:no buffer space available', - '26:ENOMEM:not enough memory', - '27:ENOTDIR:not a directory', - '28:EISDIR:illegal operation on a directory', - '29:ENONET:machine is not on the network', - // errno 30 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js - '31:ENOTCONN:socket is not connected', - '32:ENOTSOCK:socket operation on non-socket', - '33:ENOTSUP:operation not supported on socket', - '34:ENOENT:no such file or directory', - '35:ENOSYS:function not implemented', - '36:EPIPE:broken pipe', - '37:EPROTO:protocol error', - '38:EPROTONOSUPPORT:protocol not supported', - '39:EPROTOTYPE:protocol wrong type for socket', - '40:ETIMEDOUT:connection timed out', - '41:ECHARSET:invalid Unicode character', - '42:EAIFAMNOSUPPORT:address family for hostname not supported', - // errno 43 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js - '44:EAISERVICE:servname not supported for ai_socktype', - '45:EAISOCKTYPE:ai_socktype not supported', - '46:ESHUTDOWN:cannot send after transport endpoint shutdown', - '47:EEXIST:file already exists', - '48:ESRCH:no such process', - '49:ENAMETOOLONG:name too long', - '50:EPERM:operation not permitted', - '51:ELOOP:too many symbolic links encountered', - '52:EXDEV:cross-device link not permitted', - '53:ENOTEMPTY:directory not empty', - '54:ENOSPC:no space left on device', - '55:EIO:i/o error', - '56:EROFS:read-only file system', - '57:ENODEV:no such device', - '58:ESPIPE:invalid seek', - '59:ECANCELED:operation canceled', - - /** - * Filer specific errors - */ - '1000:ENOTMOUNTED:not mounted', - '1001:EFILESYSTEMERROR:missing super node, use \'FORMAT\' flag to format filesystem.', - '1002:ENOATTR:attribute does not exist' - ].forEach(function(e) { - e = e.split(':'); - var errno = e[0], - err = e[1], - message = e[2]; - - function ctor(m) { - this.message = m || message; - } - var proto = ctor.prototype = new Error(); - proto.errno = errno; - proto.code = err; - proto.constructor = ctor; - - // We expose the error as both Errors.EINVAL and Errors[18] - errors[err] = errors[errno] = ctor; - }); - - return errors; -}); - -define('src/providers/indexeddb',['require','src/constants','src/constants','src/constants','src/constants','src/errors'],function(require) { - var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; - var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; - - var indexedDB = (function(window) { - return window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB; - }(this)); - - var IDB_RW = require('src/constants').IDB_RW; - var IDB_RO = require('src/constants').IDB_RO; - var Errors = require('src/errors'); - - function IndexedDBContext(db, mode) { - var transaction = db.transaction(FILE_STORE_NAME, mode); - this.objectStore = transaction.objectStore(FILE_STORE_NAME); - } - IndexedDBContext.prototype.clear = function(callback) { - try { - var request = this.objectStore.clear(); - request.onsuccess = function(event) { - callback(); - }; - request.onerror = function(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.get = function(key, callback) { - try { - var request = this.objectStore.get(key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function onerror(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.put = function(key, value, callback) { - try { - var request = this.objectStore.put(value, key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function onerror(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.delete = function(key, callback) { - try { - var request = this.objectStore.delete(key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - - - function IndexedDB(name) { - this.name = name || FILE_SYSTEM_NAME; - this.db = null; - } - IndexedDB.isSupported = function() { - return !!indexedDB; - }; - - IndexedDB.prototype.open = function(callback) { - var that = this; - - // Bail if we already have a db open - if( that.db ) { - callback(null, false); - return; - } - - // Keep track of whether we're accessing this db for the first time - // and therefore needs to get formatted. - var firstAccess = false; - - // NOTE: we're not using versioned databases. - var openRequest = indexedDB.open(that.name); - - // If the db doesn't exist, we'll create it - openRequest.onupgradeneeded = function onupgradeneeded(event) { - var db = event.target.result; - - if(db.objectStoreNames.contains(FILE_STORE_NAME)) { - db.deleteObjectStore(FILE_STORE_NAME); - } - db.createObjectStore(FILE_STORE_NAME); - - firstAccess = true; - }; - - openRequest.onsuccess = function onsuccess(event) { - that.db = event.target.result; - callback(null, firstAccess); - }; - openRequest.onerror = function onerror(error) { - callback(new Errors.EINVAL('IndexedDB cannot be accessed. If private browsing is enabled, disable it.')); - }; - }; - IndexedDB.prototype.getReadOnlyContext = function() { - // Due to timing issues in Chrome with readwrite vs. readonly indexeddb transactions - // always use readwrite so we can make sure pending commits finish before callbacks. - // See https://github.com/js-platform/filer/issues/128 - return new IndexedDBContext(this.db, IDB_RW); - }; - IndexedDB.prototype.getReadWriteContext = function() { - return new IndexedDBContext(this.db, IDB_RW); - }; - - return IndexedDB; -}); - -define('src/providers/websql',['require','src/constants','src/constants','src/constants','src/constants','src/constants','src/shared','src/errors'],function(require) { - var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; - var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; - var WSQL_VERSION = require('src/constants').WSQL_VERSION; - var WSQL_SIZE = require('src/constants').WSQL_SIZE; - var WSQL_DESC = require('src/constants').WSQL_DESC; - var u8toArray = require('src/shared').u8toArray; - var Errors = require('src/errors'); - - function WebSQLContext(db, isReadOnly) { - var that = this; - this.getTransaction = function(callback) { - if(that.transaction) { - callback(that.transaction); - return; - } - // Either do readTransaction() (read-only) or transaction() (read/write) - db[isReadOnly ? 'readTransaction' : 'transaction'](function(transaction) { - that.transaction = transaction; - callback(transaction); - }); - }; - } - WebSQLContext.prototype.clear = function(callback) { - function onError(transaction, error) { - callback(error); - } - function onSuccess(transaction, result) { - callback(null); - } - this.getTransaction(function(transaction) { - transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + ";", - [], onSuccess, onError); - }); - }; - WebSQLContext.prototype.get = function(key, callback) { - function onSuccess(transaction, result) { - // If the key isn't found, return null - var value = result.rows.length === 0 ? null : result.rows.item(0).data; - try { - if(value) { - value = JSON.parse(value); - // Deal with special-cased flattened typed arrays in WebSQL (see put() below) - if(value.__isUint8Array) { - value = new Uint8Array(value.__array); - } - } - callback(null, value); - } catch(e) { - callback(e); - } - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("SELECT data FROM " + FILE_STORE_NAME + " WHERE id = ?;", - [key], onSuccess, onError); - }); - }; - WebSQLContext.prototype.put = function(key, value, callback) { - // We do extra work to make sure typed arrays survive - // being stored in the db and still get the right prototype later. - if(Object.prototype.toString.call(value) === "[object Uint8Array]") { - value = { - __isUint8Array: true, - __array: u8toArray(value) - }; - } - value = JSON.stringify(value); - function onSuccess(transaction, result) { - callback(null); - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("INSERT OR REPLACE INTO " + FILE_STORE_NAME + " (id, data) VALUES (?, ?);", - [key, value], onSuccess, onError); - }); - }; - WebSQLContext.prototype.delete = function(key, callback) { - function onSuccess(transaction, result) { - callback(null); - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + " WHERE id = ?;", - [key], onSuccess, onError); - }); - }; - - - function WebSQL(name) { - this.name = name || FILE_SYSTEM_NAME; - this.db = null; - } - WebSQL.isSupported = function() { - return typeof window === 'undefined' ? false : !!window.openDatabase; - }; - - WebSQL.prototype.open = function(callback) { - var that = this; - - // Bail if we already have a db open - if(that.db) { - callback(null, false); - return; - } - - var db = window.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE); - if(!db) { - callback("[WebSQL] Unable to open database."); - return; - } - - function onError(transaction, error) { - if (error.code === 5) { - callback(new Errors.EINVAL('WebSQL cannot be accessed. If private browsing is enabled, disable it.')); - } - callback(error); - } - function onSuccess(transaction, result) { - that.db = db; - - function gotCount(transaction, result) { - var firstAccess = result.rows.item(0).count === 0; - callback(null, firstAccess); - } - function onError(transaction, error) { - callback(error); - } - // Keep track of whether we're accessing this db for the first time - // and therefore needs to get formatted. - transaction.executeSql("SELECT COUNT(id) AS count FROM " + FILE_STORE_NAME + ";", - [], gotCount, onError); - } - - // Create the table and index we'll need to store the fs data. - db.transaction(function(transaction) { - function createIndex(transaction) { - transaction.executeSql("CREATE INDEX IF NOT EXISTS idx_" + FILE_STORE_NAME + "_id" + - " on " + FILE_STORE_NAME + " (id);", - [], onSuccess, onError); - } - transaction.executeSql("CREATE TABLE IF NOT EXISTS " + FILE_STORE_NAME + " (id unique, data TEXT);", - [], createIndex, onError); - }); - }; - WebSQL.prototype.getReadOnlyContext = function() { - return new WebSQLContext(this.db, true); - }; - WebSQL.prototype.getReadWriteContext = function() { - return new WebSQLContext(this.db, false); - }; - - return WebSQL; -}); - -/*global setImmediate: false, setTimeout: false, console: false */ - -/** - * https://raw.github.com/caolan/async/master/lib/async.js Feb 18, 2014 - * Used under MIT - https://github.com/caolan/async/blob/master/LICENSE - */ - -(function () { - - var async = {}; - - // global on the server, window in the browser - var root, previous_async; - - root = this; - if (root != null) { - previous_async = root.async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - var called = false; - return function() { - if (called) throw new Error("Callback was already called."); - called = true; - fn.apply(root, arguments); - } - } - - //// cross-browser compatiblity functions //// - - var _each = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _each(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _each(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - if (typeof setImmediate === 'function') { - async.nextTick = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - async.setImmediate = async.nextTick; - } - else { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - async.setImmediate = async.nextTick; - } - } - else { - async.nextTick = process.nextTick; - if (typeof setImmediate !== 'undefined') { - async.setImmediate = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - } - else { - async.setImmediate = async.nextTick; - } - } - - async.each = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - _each(arr, function (x) { - iterator(x, only_once(function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - } - })); - }); - }; - async.forEach = async.each; - - async.eachSeries = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - async.forEachSeries = async.eachSeries; - - async.eachLimit = function (arr, limit, iterator, callback) { - var fn = _eachLimit(limit); - fn.apply(null, [arr, iterator, callback]); - }; - async.forEachLimit = async.eachLimit; - - var _eachLimit = function (limit) { - - return function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length || limit <= 0) { - return callback(); - } - var completed = 0; - var started = 0; - var running = 0; - - (function replenish () { - if (completed >= arr.length) { - return callback(); - } - - while (running < limit && started < arr.length) { - started += 1; - running += 1; - iterator(arr[started - 1], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - running -= 1; - if (completed >= arr.length) { - callback(); - } - else { - replenish(); - } - } - }); - } - })(); - }; - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.each].concat(args)); - }; - }; - var doParallelLimit = function(limit, fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [_eachLimit(limit)].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.eachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = function (arr, limit, iterator, callback) { - return _mapLimit(limit)(arr, iterator, callback); - }; - - var _mapLimit = function(limit) { - return doParallelLimit(limit, _asyncMap); - }; - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.eachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - main_callback = function () {}; - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _each(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - callback = function () {}; - } - }); - - _each(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _each(_keys(results), function(rkey) { - safeResults[rkey] = results[rkey]; - }); - safeResults[k] = args; - callback(err, safeResults); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor !== Array) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback.apply(null, arguments); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.setImmediate(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - var _parallel = function(eachfn, tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - eachfn.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - eachfn.each(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.parallel = function (tasks, callback) { - _parallel({ map: async.map, each: async.each }, tasks, callback); - }; - - async.parallelLimit = function(tasks, limit, callback) { - _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.eachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doWhilst = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (test()) { - async.doWhilst(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doUntil = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (!test()) { - async.doUntil(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.queue = function (worker, concurrency) { - if (concurrency === undefined) { - concurrency = 1; - } - function _insert(q, data, pos, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - var item = { - data: task, - callback: typeof callback === 'function' ? callback : null - }; - - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } - - if (q.saturated && q.tasks.length === concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if (q.empty && q.tasks.length === 0) { - q.empty(); - } - workers += 1; - var next = function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if (q.drain && q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - var cb = only_once(next); - worker(task.data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - async.cargo = function (worker, payload) { - var working = false, - tasks = []; - - var cargo = { - tasks: tasks, - payload: payload, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - if (cargo.saturated && tasks.length === payload) { - cargo.saturated(); - } - }); - async.setImmediate(cargo.process); - }, - process: function process() { - if (working) return; - if (tasks.length === 0) { - if(cargo.drain) cargo.drain(); - return; - } - - var ts = typeof payload === 'number' - ? tasks.splice(0, payload) - : tasks.splice(0); - - var ds = _map(ts, function (task) { - return task.data; - }); - - if(cargo.empty) cargo.empty(); - working = true; - worker(ds, function () { - working = false; - - var args = arguments; - _each(ts, function (data) { - if (data.callback) { - data.callback.apply(null, args); - } - }); - - process(); - }); - }, - length: function () { - return tasks.length; - }, - running: function () { - return working; - } - }; - return cargo; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _each(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; - - async.times = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.map(counter, iterator, callback); - }; - - async.timesSeries = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.mapSeries(counter, iterator, callback); - }; - - async.compose = function (/* functions... */) { - var fns = Array.prototype.reverse.call(arguments); - return function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([function () { - var err = arguments[0]; - var nextargs = Array.prototype.slice.call(arguments, 1); - cb(err, nextargs); - }])) - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }; - }; - - var _applyEach = function (eachfn, fns /*args...*/) { - var go = function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - return eachfn(fns, function (fn, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }; - if (arguments.length > 2) { - var args = Array.prototype.slice.call(arguments, 2); - return go.apply(this, args); - } - else { - return go; - } - }; - async.applyEach = doParallel(_applyEach); - async.applyEachSeries = doSeries(_applyEach); - - async.forever = function (fn, callback) { - function next(err) { - if (err) { - if (callback) { - return callback(err); - } - throw err; - } - fn(next); - } - next(); - }; - - // AMD / RequireJS - if (typeof define !== 'undefined' && define.amd) { - define('async',[], function () { - return async; - }); - } - // Node.js - else if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - // included directly via - +
diff --git a/tests/index.js b/tests/index.js index ad8150c..da2939d 100644 --- a/tests/index.js +++ b/tests/index.js @@ -1,8 +1,2 @@ // Tests to be run are defined in test-manifest.js - -// For Nodejs context, expose chai's expect method -if (typeof GLOBAL !== "undefined") { - GLOBAL.expect = require('chai').expect; -} - require('./test-manifest.js'); diff --git a/tests/spec/shell/cd.spec.js b/tests/spec/shell/cd.spec.js index 5af2233..c3fc43a 100644 --- a/tests/spec/shell/cd.spec.js +++ b/tests/spec/shell/cd.spec.js @@ -1,5 +1,6 @@ var Filer = require('../../..'); var util = require('../../lib/test-utils.js'); +var expect = require('chai').expect; describe('FileSystemShell.cd', function() { beforeEach(util.setup); From ad64ac1b752df1d44fb194f678fa63833b11512b Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Mon, 26 May 2014 17:41:17 -0400 Subject: [PATCH 24/31] Moah fixes --- tests/index.js | 71 ++++++++++++++++++++++++++++++++++++++++-- tests/test-manifest.js | 69 ---------------------------------------- 2 files changed, 69 insertions(+), 71 deletions(-) delete mode 100644 tests/test-manifest.js diff --git a/tests/index.js b/tests/index.js index da2939d..c5890fa 100644 --- a/tests/index.js +++ b/tests/index.js @@ -1,2 +1,69 @@ -// Tests to be run are defined in test-manifest.js -require('./test-manifest.js'); +/** + * Add your test spec files to the list in order to + * get them running by default. + */ + +// Filer +require("./spec/filer.spec"); + +// Filer.FileSystem.* +require("./spec/fs.spec"); +require("./spec/fs.stat.spec"); +require("./spec/fs.lstat.spec"); +require("./spec/fs.exists.spec"); +require("./spec/fs.mknod.spec"); +require("./spec/fs.mkdir.spec"); +require("./spec/fs.readdir.spec"); +require("./spec/fs.rmdir.spec"); +require("./spec/fs.open.spec"); +require("./spec/fs.write.spec"); +require("./spec/fs.writeFile-readFile.spec"); +require("./spec/fs.appendFile.spec"); +require("./spec/fs.read.spec"); +require("./spec/fs.close.spec"); +require("./spec/fs.link.spec"); +require("./spec/fs.unlink.spec"); +require("./spec/fs.rename.spec"); +require("./spec/fs.lseek.spec"); +require("./spec/fs.symlink.spec"); +require("./spec/fs.readlink.spec"); +require("./spec/fs.truncate.spec"); +require("./spec/fs.utimes.spec"); +require("./spec/fs.xattr.spec"); +require("./spec/fs.stats.spec"); +require("./spec/path-resolution.spec"); +require("./spec/times.spec"); +require("./spec/time-flags.spec"); +require("./spec/fs.watch.spec"); +require("./spec/errors.spec"); + +// Filer.FileSystem.providers.* +require("./spec/providers/providers.spec"); +require("./spec/providers/providers.indexeddb.spec"); +require("./spec/providers/providers.websql.spec"); +require("./spec/providers/providers.memory.spec"); + +// Filer.FileSystemShell.* +require("./spec/shell/cd.spec"); +require("./spec/shell/touch.spec"); +require("./spec/shell/exec.spec"); +require("./spec/shell/cat.spec"); +require("./spec/shell/ls.spec"); +require("./spec/shell/rm.spec"); +require("./spec/shell/env.spec"); +require("./spec/shell/mkdirp.spec"); +require("./spec/shell/wget.spec"); +require("./spec/shell/zip-unzip.spec"); + +// Custom Filer library modules +require("./spec/libs/network.spec"); + +// Ported node.js tests (filenames match names in https://github.com/joyent/node/tree/master/test) +require("./spec/node-js/simple/test-fs-mkdir"); +require("./spec/node-js/simple/test-fs-null-bytes"); +require("./spec/node-js/simple/test-fs-watch"); +require("./spec/node-js/simple/test-fs-watch-recursive"); + +// Regressions; Bugs +require("./bugs/issue105"); +require("./bugs/issue106"); diff --git a/tests/test-manifest.js b/tests/test-manifest.js deleted file mode 100644 index c5890fa..0000000 --- a/tests/test-manifest.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Add your test spec files to the list in order to - * get them running by default. - */ - -// Filer -require("./spec/filer.spec"); - -// Filer.FileSystem.* -require("./spec/fs.spec"); -require("./spec/fs.stat.spec"); -require("./spec/fs.lstat.spec"); -require("./spec/fs.exists.spec"); -require("./spec/fs.mknod.spec"); -require("./spec/fs.mkdir.spec"); -require("./spec/fs.readdir.spec"); -require("./spec/fs.rmdir.spec"); -require("./spec/fs.open.spec"); -require("./spec/fs.write.spec"); -require("./spec/fs.writeFile-readFile.spec"); -require("./spec/fs.appendFile.spec"); -require("./spec/fs.read.spec"); -require("./spec/fs.close.spec"); -require("./spec/fs.link.spec"); -require("./spec/fs.unlink.spec"); -require("./spec/fs.rename.spec"); -require("./spec/fs.lseek.spec"); -require("./spec/fs.symlink.spec"); -require("./spec/fs.readlink.spec"); -require("./spec/fs.truncate.spec"); -require("./spec/fs.utimes.spec"); -require("./spec/fs.xattr.spec"); -require("./spec/fs.stats.spec"); -require("./spec/path-resolution.spec"); -require("./spec/times.spec"); -require("./spec/time-flags.spec"); -require("./spec/fs.watch.spec"); -require("./spec/errors.spec"); - -// Filer.FileSystem.providers.* -require("./spec/providers/providers.spec"); -require("./spec/providers/providers.indexeddb.spec"); -require("./spec/providers/providers.websql.spec"); -require("./spec/providers/providers.memory.spec"); - -// Filer.FileSystemShell.* -require("./spec/shell/cd.spec"); -require("./spec/shell/touch.spec"); -require("./spec/shell/exec.spec"); -require("./spec/shell/cat.spec"); -require("./spec/shell/ls.spec"); -require("./spec/shell/rm.spec"); -require("./spec/shell/env.spec"); -require("./spec/shell/mkdirp.spec"); -require("./spec/shell/wget.spec"); -require("./spec/shell/zip-unzip.spec"); - -// Custom Filer library modules -require("./spec/libs/network.spec"); - -// Ported node.js tests (filenames match names in https://github.com/joyent/node/tree/master/test) -require("./spec/node-js/simple/test-fs-mkdir"); -require("./spec/node-js/simple/test-fs-null-bytes"); -require("./spec/node-js/simple/test-fs-watch"); -require("./spec/node-js/simple/test-fs-watch-recursive"); - -// Regressions; Bugs -require("./bugs/issue105"); -require("./bugs/issue106"); From 215e4c3f49d68114268387447c13c3fd7c8b3c4f Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Mon, 26 May 2014 17:46:10 -0400 Subject: [PATCH 25/31] Remove grunt-mocha --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index dea45d9..c93ed21 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,6 @@ "grunt-contrib-uglify": "~0.1.2", "grunt-contrib-watch": "~0.3.1", "grunt-git": "0.2.10", - "grunt-mocha": "0.4.10", "grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck", "grunt-prompt": "^1.1.0", "grunt-shell": "~0.7.0", From 747dadb1c36c94ae617a74a7688e65e8b6abbf1e Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Mon, 26 May 2014 19:20:42 -0400 Subject: [PATCH 26/31] Remove grunt-mocha from gruntfile too --- gruntfile.js | 1 - 1 file changed, 1 deletion(-) diff --git a/gruntfile.js b/gruntfile.js index 9856743..a23e283 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -168,7 +168,6 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-mocha'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-npm'); From baf593ee82de51813cc9a34ffa77c1e4db2751b3 Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Tue, 27 May 2014 10:32:41 -0400 Subject: [PATCH 27/31] Excluded the request module from browserify builds and updated CONTRIBUTING.md --- CONTRIBUTING.md | 6 ++---- gruntfile.js | 3 ++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a4d015f..041ee88 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,13 +32,11 @@ to the `AUTHORS` file. ======= ### Releasing a new version ======= -### Releasing a new version -**NOTE:** This step should only ever be attempted by the owner of the repo (@modeswitch). `grunt publish` will: * Run the `grunt release` task -* Bump `bower.json` & `package.json` version numbers according to a [Semver](http://semver.org/) compatible scheme (see "How to Publish" below) +* Bump `bower.json` & `package.json` version numbers according to a [Semver](http://semver.org/) compatible scheme (see ["How to Publish"](#how-to-publish) below) * Create a git tag at the new version number * Create a release commit including `dist/filer.js`, `dist/filer.min.js`, `bower.json` and `package.json` * Push tag & commit to `origin/develop` @@ -64,7 +62,7 @@ The user *must* be on their local `develop` branch before running any form of `g ## Tests Tests are writting using [Mocha](http://visionmedia.github.io/mocha/) and [Chai](http://chaijs.com/api/bdd/). -You can run the tests in your browser by running `grunt test-browser` and opening the `tests` directory @ `http://localhost:1234/tests`. +You can run the tests in your browser by running `grunt test-browser` and opening the `tests` directory @ `http://localhost:1234/tests`, or in a nodejs context by running `grunt test` or `grunt test-node`. There are a number of configurable options for the test suite, which are set via query string params. First, you can choose which filer source to use (i.e., src/, dist/filer-test.js, dist/filer.js or dist/filer.min.js). diff --git a/gruntfile.js b/gruntfile.js index 9856743..a04e56a 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -60,7 +60,8 @@ module.exports = function(grunt) { browserifyOptions: { builtins: false, commondir: false - } + }, + exclude: ["./node_modules/request/index.js"] } }, filerTest: { From 2c1ccdd9f1088bfa99c823cf7afe2afbd40c066d Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Tue, 27 May 2014 10:46:23 -0400 Subject: [PATCH 28/31] Make browserify point to the correct Filer distribution when including filer in 3rd party browserify builds --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index dea45d9..8aa4157 100644 --- a/package.json +++ b/package.json @@ -49,5 +49,6 @@ "mocha": "~1.18.2", "semver": "^2.3.0" }, - "main": "./src/index.js" + "main": "./src/index.js", + "browser": "./dist/filer.min.js" } From a8397c5057e68718e03f54c24f0ece1cb5e10f48 Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Tue, 27 May 2014 10:47:47 -0400 Subject: [PATCH 29/31] corrected CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 041ee88..ae679ae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,7 +62,7 @@ The user *must* be on their local `develop` branch before running any form of `g ## Tests Tests are writting using [Mocha](http://visionmedia.github.io/mocha/) and [Chai](http://chaijs.com/api/bdd/). -You can run the tests in your browser by running `grunt test-browser` and opening the `tests` directory @ `http://localhost:1234/tests`, or in a nodejs context by running `grunt test` or `grunt test-node`. +You can run the tests in your browser by running `grunt test-browser` and opening the `tests` directory @ `http://localhost:1234/tests`, or in a nodejs context by running `grunt test`. There are a number of configurable options for the test suite, which are set via query string params. First, you can choose which filer source to use (i.e., src/, dist/filer-test.js, dist/filer.js or dist/filer.min.js). From 95691f4e897c3462258d8911c797ea02acec887c Mon Sep 17 00:00:00 2001 From: Kieran Sedgwick Date: Tue, 27 May 2014 14:26:16 -0400 Subject: [PATCH 30/31] removed browser attribute from package.json --- dist/filer.js | 8560 --------------------------------------------- dist/filer.min.js | 6 - package.json | 3 +- 3 files changed, 1 insertion(+), 8568 deletions(-) delete mode 100644 dist/filer.js delete mode 100644 dist/filer.min.js diff --git a/dist/filer.js b/dist/filer.js deleted file mode 100644 index bf9b7c4..0000000 --- a/dist/filer.js +++ /dev/null @@ -1,8560 +0,0 @@ -/* -Copyright (c) 2013, Alan Kligman -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -(function( root, factory ) { - - if ( typeof exports === "object" ) { - // Node - module.exports = factory(); - } else if (typeof define === "function" && define.amd) { - // AMD. Register as an anonymous module. - define( factory ); - } else if( !root.Filer ) { - // Browser globals - root.Filer = factory(); - } - -}( this, function() { -/** - * almond 0.2.5 Copyright (c) 2011-2012, The Dojo Foundation All Rights Reserved. - * Available via the MIT or new BSD license. - * see: http://github.com/jrburke/almond for details - */ -//Going sloppy to avoid 'use strict' string cost, but strict practices should -//be followed. -/*jslint sloppy: true */ -/*global setTimeout: false */ - -var requirejs, require, define; -(function (undef) { - var main, req, makeMap, handlers, - defined = {}, - waiting = {}, - config = {}, - defining = {}, - hasOwn = Object.prototype.hasOwnProperty, - aps = [].slice; - - function hasProp(obj, prop) { - return hasOwn.call(obj, prop); - } - - /** - * Given a relative module name, like ./something, normalize it to - * a real name that can be mapped to a path. - * @param {String} name the relative name - * @param {String} baseName a real name that the name arg is relative - * to. - * @returns {String} normalized name - */ - function normalize(name, baseName) { - var nameParts, nameSegment, mapValue, foundMap, - foundI, foundStarMap, starI, i, j, part, - baseParts = baseName && baseName.split("/"), - map = config.map, - starMap = (map && map['*']) || {}; - - //Adjust any relative paths. - if (name && name.charAt(0) === ".") { - //If have a base name, try to normalize against it, - //otherwise, assume it is a top-level require that will - //be relative to baseUrl in the end. - if (baseName) { - //Convert baseName to array, and lop off the last part, - //so that . matches that "directory" and not name of the baseName's - //module. For instance, baseName of "one/two/three", maps to - //"one/two/three.js", but we want the directory, "one/two" for - //this normalization. - baseParts = baseParts.slice(0, baseParts.length - 1); - - name = baseParts.concat(name.split("/")); - - //start trimDots - for (i = 0; i < name.length; i += 1) { - part = name[i]; - if (part === ".") { - name.splice(i, 1); - i -= 1; - } else if (part === "..") { - if (i === 1 && (name[2] === '..' || name[0] === '..')) { - //End of the line. Keep at least one non-dot - //path segment at the front so it can be mapped - //correctly to disk. Otherwise, there is likely - //no path mapping for a path starting with '..'. - //This can still fail, but catches the most reasonable - //uses of .. - break; - } else if (i > 0) { - name.splice(i - 1, 2); - i -= 2; - } - } - } - //end trimDots - - name = name.join("/"); - } else if (name.indexOf('./') === 0) { - // No baseName, so this is ID is resolved relative - // to baseUrl, pull off the leading dot. - name = name.substring(2); - } - } - - //Apply map config if available. - if ((baseParts || starMap) && map) { - nameParts = name.split('/'); - - for (i = nameParts.length; i > 0; i -= 1) { - nameSegment = nameParts.slice(0, i).join("/"); - - if (baseParts) { - //Find the longest baseName segment match in the config. - //So, do joins on the biggest to smallest lengths of baseParts. - for (j = baseParts.length; j > 0; j -= 1) { - mapValue = map[baseParts.slice(0, j).join('/')]; - - //baseName segment has config, find if it has one for - //this name. - if (mapValue) { - mapValue = mapValue[nameSegment]; - if (mapValue) { - //Match, update name to the new value. - foundMap = mapValue; - foundI = i; - break; - } - } - } - } - - if (foundMap) { - break; - } - - //Check for a star map match, but just hold on to it, - //if there is a shorter segment match later in a matching - //config, then favor over this star map. - if (!foundStarMap && starMap && starMap[nameSegment]) { - foundStarMap = starMap[nameSegment]; - starI = i; - } - } - - if (!foundMap && foundStarMap) { - foundMap = foundStarMap; - foundI = starI; - } - - if (foundMap) { - nameParts.splice(0, foundI, foundMap); - name = nameParts.join('/'); - } - } - - return name; - } - - function makeRequire(relName, forceSync) { - return function () { - //A version of a require function that passes a moduleName - //value for items that may need to - //look up paths relative to the moduleName - return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); - }; - } - - function makeNormalize(relName) { - return function (name) { - return normalize(name, relName); - }; - } - - function makeLoad(depName) { - return function (value) { - defined[depName] = value; - }; - } - - function callDep(name) { - if (hasProp(waiting, name)) { - var args = waiting[name]; - delete waiting[name]; - defining[name] = true; - main.apply(undef, args); - } - - if (!hasProp(defined, name) && !hasProp(defining, name)) { - throw new Error('No ' + name); - } - return defined[name]; - } - - //Turns a plugin!resource to [plugin, resource] - //with the plugin being undefined if the name - //did not have a plugin prefix. - function splitPrefix(name) { - var prefix, - index = name ? name.indexOf('!') : -1; - if (index > -1) { - prefix = name.substring(0, index); - name = name.substring(index + 1, name.length); - } - return [prefix, name]; - } - - /** - * Makes a name map, normalizing the name, and using a plugin - * for normalization if necessary. Grabs a ref to plugin - * too, as an optimization. - */ - makeMap = function (name, relName) { - var plugin, - parts = splitPrefix(name), - prefix = parts[0]; - - name = parts[1]; - - if (prefix) { - prefix = normalize(prefix, relName); - plugin = callDep(prefix); - } - - //Normalize according - if (prefix) { - if (plugin && plugin.normalize) { - name = plugin.normalize(name, makeNormalize(relName)); - } else { - name = normalize(name, relName); - } - } else { - name = normalize(name, relName); - parts = splitPrefix(name); - prefix = parts[0]; - name = parts[1]; - if (prefix) { - plugin = callDep(prefix); - } - } - - //Using ridiculous property names for space reasons - return { - f: prefix ? prefix + '!' + name : name, //fullName - n: name, - pr: prefix, - p: plugin - }; - }; - - function makeConfig(name) { - return function () { - return (config && config.config && config.config[name]) || {}; - }; - } - - handlers = { - require: function (name) { - return makeRequire(name); - }, - exports: function (name) { - var e = defined[name]; - if (typeof e !== 'undefined') { - return e; - } else { - return (defined[name] = {}); - } - }, - module: function (name) { - return { - id: name, - uri: '', - exports: defined[name], - config: makeConfig(name) - }; - } - }; - - main = function (name, deps, callback, relName) { - var cjsModule, depName, ret, map, i, - args = [], - usingExports; - - //Use name if no relName - relName = relName || name; - - //Call the callback to define the module, if necessary. - if (typeof callback === 'function') { - - //Pull out the defined dependencies and pass the ordered - //values to the callback. - //Default to [require, exports, module] if no deps - deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; - for (i = 0; i < deps.length; i += 1) { - map = makeMap(deps[i], relName); - depName = map.f; - - //Fast path CommonJS standard dependencies. - if (depName === "require") { - args[i] = handlers.require(name); - } else if (depName === "exports") { - //CommonJS module spec 1.1 - args[i] = handlers.exports(name); - usingExports = true; - } else if (depName === "module") { - //CommonJS module spec 1.1 - cjsModule = args[i] = handlers.module(name); - } else if (hasProp(defined, depName) || - hasProp(waiting, depName) || - hasProp(defining, depName)) { - args[i] = callDep(depName); - } else if (map.p) { - map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); - args[i] = defined[depName]; - } else { - throw new Error(name + ' missing ' + depName); - } - } - - ret = callback.apply(defined[name], args); - - if (name) { - //If setting exports via "module" is in play, - //favor that over return value and exports. After that, - //favor a non-undefined return value over exports use. - if (cjsModule && cjsModule.exports !== undef && - cjsModule.exports !== defined[name]) { - defined[name] = cjsModule.exports; - } else if (ret !== undef || !usingExports) { - //Use the return value from the function. - defined[name] = ret; - } - } - } else if (name) { - //May just be an object definition for the module. Only - //worry about defining if have a module name. - defined[name] = callback; - } - }; - - requirejs = require = req = function (deps, callback, relName, forceSync, alt) { - if (typeof deps === "string") { - if (handlers[deps]) { - //callback in this case is really relName - return handlers[deps](callback); - } - //Just return the module wanted. In this scenario, the - //deps arg is the module name, and second arg (if passed) - //is just the relName. - //Normalize module name, if it contains . or .. - return callDep(makeMap(deps, callback).f); - } else if (!deps.splice) { - //deps is a config object, not an array. - config = deps; - if (callback.splice) { - //callback is an array, which means it is a dependency list. - //Adjust args if there are dependencies - deps = callback; - callback = relName; - relName = null; - } else { - deps = undef; - } - } - - //Support require(['a']) - callback = callback || function () {}; - - //If relName is a function, it is an errback handler, - //so remove it. - if (typeof relName === 'function') { - relName = forceSync; - forceSync = alt; - } - - //Simulate async callback; - if (forceSync) { - main(undef, deps, callback, relName); - } else { - //Using a non-zero value because of concern for what old browsers - //do, and latest browsers "upgrade" to 4 if lower value is used: - //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: - //If want a value immediately, use require('id') instead -- something - //that works in almond on the global level, but not guaranteed and - //unlikely to work in other AMD implementations. - setTimeout(function () { - main(undef, deps, callback, relName); - }, 4); - } - - return req; - }; - - /** - * Just drops the config on the floor, but returns req in case - * the config return value is used. - */ - req.config = function (cfg) { - config = cfg; - if (config.deps) { - req(config.deps, config.callback); - } - return req; - }; - - define = function (name, deps, callback) { - - //This module may not have dependencies - if (!deps.splice) { - //deps is not an array, so probably means - //an object literal or factory function for - //the value. Adjust args. - callback = deps; - deps = []; - } - - if (!hasProp(defined, name) && !hasProp(waiting, name)) { - waiting[name] = [name, deps, callback]; - } - }; - - define.amd = { - jQuery: true - }; -}()); - -define("build/almond", function(){}); - -// Cherry-picked bits of underscore.js, lodash.js - -/** - * Lo-Dash 2.4.0 - * Copyright 2012-2013 The Dojo Foundation - * Based on Underscore.js 1.5.2 - * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ - -define('nodash',['require'],function(require) { - - var ArrayProto = Array.prototype; - var nativeForEach = ArrayProto.forEach; - var nativeIndexOf = ArrayProto.indexOf; - var nativeSome = ArrayProto.some; - - var ObjProto = Object.prototype; - var hasOwnProperty = ObjProto.hasOwnProperty; - var nativeKeys = Object.keys; - - var breaker = {}; - - function has(obj, key) { - return hasOwnProperty.call(obj, key); - } - - var keys = nativeKeys || function(obj) { - if (obj !== Object(obj)) throw new TypeError('Invalid object'); - var keys = []; - for (var key in obj) if (has(obj, key)) keys.push(key); - return keys; - }; - - function size(obj) { - if (obj == null) return 0; - return (obj.length === +obj.length) ? obj.length : keys(obj).length; - } - - function identity(value) { - return value; - } - - function each(obj, iterator, context) { - var i, length; - if (obj == null) return; - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - } else if (obj.length === +obj.length) { - for (i = 0, length = obj.length; i < length; i++) { - if (iterator.call(context, obj[i], i, obj) === breaker) return; - } - } else { - var keys = keys(obj); - for (i = 0, length = keys.length; i < length; i++) { - if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; - } - } - }; - - function any(obj, iterator, context) { - iterator || (iterator = identity); - var result = false; - if (obj == null) return result; - if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); - each(obj, function(value, index, list) { - if (result || (result = iterator.call(context, value, index, list))) return breaker; - }); - return !!result; - }; - - function contains(obj, target) { - if (obj == null) return false; - if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; - return any(obj, function(value) { - return value === target; - }); - }; - - function Wrapped(value) { - this.value = value; - } - Wrapped.prototype.has = function(key) { - return has(this.value, key); - }; - Wrapped.prototype.contains = function(target) { - return contains(this.value, target); - }; - Wrapped.prototype.size = function() { - return size(this.value); - }; - - function nodash(value) { - // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor - return (value && typeof value == 'object' && !Array.isArray(value) && hasOwnProperty.call(value, '__wrapped__')) - ? value - : new Wrapped(value); - } - - return nodash; - -}); - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js -define('src/path',[],function() { - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/; - var splitPath = function(filename) { - var result = splitPathRe.exec(filename); - return [result[1] || '', result[2] || '', result[3] || '', result[4] || '']; - }; - - // path.resolve([from ...], to) - function resolve() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - // XXXidbfs: we don't have process.cwd() so we use '/' as a fallback - var path = (i >= 0) ? arguments[i] : '/'; - - // Skip empty and invalid entries - if (typeof path !== 'string' || !path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - } - - // path.normalize(path) - function normalize(path) { - var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.substr(-1) === '/'; - - // Normalize the path - path = normalizeArray(path.split('/').filter(function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - /* - if (path && trailingSlash) { - path += '/'; - } - */ - - return (isAbsolute ? '/' : '') + path; - } - - function join() { - var paths = Array.prototype.slice.call(arguments, 0); - return normalize(paths.filter(function(p, index) { - return p && typeof p === 'string'; - }).join('/')); - } - - // path.relative(from, to) - function relative(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - } - - function dirname(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - } - - function basename(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - // XXXidbfs: node.js just does `return f` - return f === "" ? "/" : f; - } - - function extname(path) { - return splitPath(path)[3]; - } - - function isAbsolute(path) { - if(path.charAt(0) === '/') { - return true; - } - return false; - } - - function isNull(path) { - if (('' + path).indexOf('\u0000') !== -1) { - return true; - } - return false; - } - - // XXXidbfs: we don't support path.exists() or path.existsSync(), which - // are deprecated, and need a FileSystem instance to work. Use fs.stat(). - - return { - normalize: normalize, - resolve: resolve, - join: join, - relative: relative, - sep: '/', - delimiter: ':', - dirname: dirname, - basename: basename, - extname: extname, - isAbsolute: isAbsolute, - isNull: isNull - }; - -}); - -/* -CryptoJS v3.0.2 -code.google.com/p/crypto-js -(c) 2009-2012 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -var CryptoJS=CryptoJS||function(i,p){var f={},q=f.lib={},j=q.Base=function(){function a(){}return{extend:function(h){a.prototype=this;var d=new a;h&&d.mixIn(h);d.$super=this;return d},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var d in a)a.hasOwnProperty(d)&&(this[d]=a[d]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),k=q.WordArray=j.extend({init:function(a,h){a= -this.words=a||[];this.sigBytes=h!=p?h:4*a.length},toString:function(a){return(a||m).stringify(this)},concat:function(a){var h=this.words,d=a.words,c=this.sigBytes,a=a.sigBytes;this.clamp();if(c%4)for(var b=0;b>>2]|=(d[b>>>2]>>>24-8*(b%4)&255)<<24-8*((c+b)%4);else if(65535>>2]=d[b>>>2];else h.push.apply(h,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<32-8*(b%4);a.length=i.ceil(b/4)},clone:function(){var a= -j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],d=0;d>>2]>>>24-8*(c%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>3]|=parseInt(a.substr(c,2),16)<<24-4*(c%8);return k.create(d,b/2)}},s=r.Latin1={stringify:function(a){for(var b= -a.words,a=a.sigBytes,d=[],c=0;c>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return k.create(d,b)}},g=r.Utf8={stringify:function(a){try{return decodeURIComponent(escape(s.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return s.parse(unescape(encodeURIComponent(a)))}},b=q.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=k.create(); -this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=g.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,c=b.sigBytes,e=this.blockSize,f=c/(4*e),f=a?i.ceil(f):i.max((f|0)-this._minBufferSize,0),a=f*e,c=i.min(4*a,c);if(a){for(var g=0;ge;)f(b)&&(8>e&&(k[e]=g(i.pow(b,0.5))),r[e]=g(i.pow(b,1/3)),e++),b++})();var m=[],j=j.SHA256=f.extend({_doReset:function(){this._hash=q.create(k.slice(0))},_doProcessBlock:function(f,g){for(var b=this._hash.words,e=b[0],a=b[1],h=b[2],d=b[3],c=b[4],i=b[5],j=b[6],k=b[7],l=0;64> -l;l++){if(16>l)m[l]=f[g+l]|0;else{var n=m[l-15],o=m[l-2];m[l]=((n<<25|n>>>7)^(n<<14|n>>>18)^n>>>3)+m[l-7]+((o<<15|o>>>17)^(o<<13|o>>>19)^o>>>10)+m[l-16]}n=k+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&i^~c&j)+r[l]+m[l];o=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&a^e&h^a&h);k=j;j=i;i=c;c=d+n|0;d=h;h=a;a=e;e=n+o|0}b[0]=b[0]+e|0;b[1]=b[1]+a|0;b[2]=b[2]+h|0;b[3]=b[3]+d|0;b[4]=b[4]+c|0;b[5]=b[5]+i|0;b[6]=b[6]+j|0;b[7]=b[7]+k|0},_doFinalize:function(){var f=this._data,g=f.words,b=8*this._nDataBytes, -e=8*f.sigBytes;g[e>>>5]|=128<<24-e%32;g[(e+64>>>9<<4)+15]=b;f.sigBytes=4*g.length;this._process()}});p.SHA256=f._createHelper(j);p.HmacSHA256=f._createHmacHelper(j)})(Math); - -define("crypto-js/rollups/sha256", function(){}); - -define('src/shared',['require','crypto-js/rollups/sha256'],function(require) { - - require("crypto-js/rollups/sha256"); var Crypto = CryptoJS; - - function guid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); - return v.toString(16); - }).toUpperCase(); - } - - function hash(string) { - return Crypto.SHA256(string).toString(Crypto.enc.hex); - } - - function nop() {} - - /** - * Convert a Uint8Array to a regular array - */ - function u8toArray(u8) { - var array = []; - var len = u8.length; - for(var i = 0; i < len; i++) { - array[i] = u8[i]; - } - return array; - } - - return { - guid: guid, - hash: hash, - u8toArray: u8toArray, - nop: nop - }; - -}); - -define('src/constants',['require'],function(require) { - - var O_READ = 'READ'; - var O_WRITE = 'WRITE'; - var O_CREATE = 'CREATE'; - var O_EXCLUSIVE = 'EXCLUSIVE'; - var O_TRUNCATE = 'TRUNCATE'; - var O_APPEND = 'APPEND'; - var XATTR_CREATE = 'CREATE'; - var XATTR_REPLACE = 'REPLACE'; - - return { - FILE_SYSTEM_NAME: 'local', - - FILE_STORE_NAME: 'files', - - IDB_RO: 'readonly', - IDB_RW: 'readwrite', - - WSQL_VERSION: "1", - WSQL_SIZE: 5 * 1024 * 1024, - WSQL_DESC: "FileSystem Storage", - - MODE_FILE: 'FILE', - MODE_DIRECTORY: 'DIRECTORY', - MODE_SYMBOLIC_LINK: 'SYMLINK', - MODE_META: 'META', - - SYMLOOP_MAX: 10, - - BINARY_MIME_TYPE: 'application/octet-stream', - JSON_MIME_TYPE: 'application/json', - - ROOT_DIRECTORY_NAME: '/', // basename(normalize(path)) - - // FS Mount Flags - FS_FORMAT: 'FORMAT', - FS_NOCTIME: 'NOCTIME', - FS_NOMTIME: 'NOMTIME', - - // FS File Open Flags - O_READ: O_READ, - O_WRITE: O_WRITE, - O_CREATE: O_CREATE, - O_EXCLUSIVE: O_EXCLUSIVE, - O_TRUNCATE: O_TRUNCATE, - O_APPEND: O_APPEND, - - O_FLAGS: { - 'r': [O_READ], - 'r+': [O_READ, O_WRITE], - 'w': [O_WRITE, O_CREATE, O_TRUNCATE], - 'w+': [O_WRITE, O_READ, O_CREATE, O_TRUNCATE], - 'wx': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], - 'wx+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_TRUNCATE], - 'a': [O_WRITE, O_CREATE, O_APPEND], - 'a+': [O_WRITE, O_READ, O_CREATE, O_APPEND], - 'ax': [O_WRITE, O_CREATE, O_EXCLUSIVE, O_APPEND], - 'ax+': [O_WRITE, O_READ, O_CREATE, O_EXCLUSIVE, O_APPEND] - }, - - XATTR_CREATE: XATTR_CREATE, - XATTR_REPLACE: XATTR_REPLACE, - - FS_READY: 'READY', - FS_PENDING: 'PENDING', - FS_ERROR: 'ERROR', - - SUPER_NODE_ID: '00000000-0000-0000-0000-000000000000', - - //Reserved FileDescriptors for streams - STDIN: 0, - STDOUT: 1, - STDERR: 2, - FIRST_DESCRIPTOR: 3, - - ENVIRONMENT: { - TMP: '/tmp', - PATH: '' - } - }; - -}); -define('src/errors',['require'],function(require) { - var errors = {}; - [ - /** - * node.js errors - */ - '-1:UNKNOWN:unknown error', - '0:OK:success', - '1:EOF:end of file', - '2:EADDRINFO:getaddrinfo error', - '3:EACCES:permission denied', - '4:EAGAIN:resource temporarily unavailable', - '5:EADDRINUSE:address already in use', - '6:EADDRNOTAVAIL:address not available', - '7:EAFNOSUPPORT:address family not supported', - '8:EALREADY:connection already in progress', - '9:EBADF:bad file descriptor', - '10:EBUSY:resource busy or locked', - '11:ECONNABORTED:software caused connection abort', - '12:ECONNREFUSED:connection refused', - '13:ECONNRESET:connection reset by peer', - '14:EDESTADDRREQ:destination address required', - '15:EFAULT:bad address in system call argument', - '16:EHOSTUNREACH:host is unreachable', - '17:EINTR:interrupted system call', - '18:EINVAL:invalid argument', - '19:EISCONN:socket is already connected', - '20:EMFILE:too many open files', - '21:EMSGSIZE:message too long', - '22:ENETDOWN:network is down', - '23:ENETUNREACH:network is unreachable', - '24:ENFILE:file table overflow', - '25:ENOBUFS:no buffer space available', - '26:ENOMEM:not enough memory', - '27:ENOTDIR:not a directory', - '28:EISDIR:illegal operation on a directory', - '29:ENONET:machine is not on the network', - // errno 30 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js - '31:ENOTCONN:socket is not connected', - '32:ENOTSOCK:socket operation on non-socket', - '33:ENOTSUP:operation not supported on socket', - '34:ENOENT:no such file or directory', - '35:ENOSYS:function not implemented', - '36:EPIPE:broken pipe', - '37:EPROTO:protocol error', - '38:EPROTONOSUPPORT:protocol not supported', - '39:EPROTOTYPE:protocol wrong type for socket', - '40:ETIMEDOUT:connection timed out', - '41:ECHARSET:invalid Unicode character', - '42:EAIFAMNOSUPPORT:address family for hostname not supported', - // errno 43 skipped, as per https://github.com/rvagg/node-errno/blob/master/errno.js - '44:EAISERVICE:servname not supported for ai_socktype', - '45:EAISOCKTYPE:ai_socktype not supported', - '46:ESHUTDOWN:cannot send after transport endpoint shutdown', - '47:EEXIST:file already exists', - '48:ESRCH:no such process', - '49:ENAMETOOLONG:name too long', - '50:EPERM:operation not permitted', - '51:ELOOP:too many symbolic links encountered', - '52:EXDEV:cross-device link not permitted', - '53:ENOTEMPTY:directory not empty', - '54:ENOSPC:no space left on device', - '55:EIO:i/o error', - '56:EROFS:read-only file system', - '57:ENODEV:no such device', - '58:ESPIPE:invalid seek', - '59:ECANCELED:operation canceled', - - /** - * Filer specific errors - */ - '1000:ENOTMOUNTED:not mounted', - '1001:EFILESYSTEMERROR:missing super node, use \'FORMAT\' flag to format filesystem.', - '1002:ENOATTR:attribute does not exist' - ].forEach(function(e) { - e = e.split(':'); - var errno = e[0], - err = e[1], - message = e[2]; - - function ctor(m) { - this.message = m || message; - } - var proto = ctor.prototype = new Error(); - proto.errno = errno; - proto.code = err; - proto.constructor = ctor; - - // We expose the error as both Errors.EINVAL and Errors[18] - errors[err] = errors[errno] = ctor; - }); - - return errors; -}); - -define('src/providers/indexeddb',['require','src/constants','src/constants','src/constants','src/constants','src/errors'],function(require) { - var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; - var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; - - var indexedDB = window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB; - - var IDB_RW = require('src/constants').IDB_RW; - var IDB_RO = require('src/constants').IDB_RO; - var Errors = require('src/errors'); - - function IndexedDBContext(db, mode) { - var transaction = db.transaction(FILE_STORE_NAME, mode); - this.objectStore = transaction.objectStore(FILE_STORE_NAME); - } - IndexedDBContext.prototype.clear = function(callback) { - try { - var request = this.objectStore.clear(); - request.onsuccess = function(event) { - callback(); - }; - request.onerror = function(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.get = function(key, callback) { - try { - var request = this.objectStore.get(key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function onerror(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.put = function(key, value, callback) { - try { - var request = this.objectStore.put(value, key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function onerror(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - IndexedDBContext.prototype.delete = function(key, callback) { - try { - var request = this.objectStore.delete(key); - request.onsuccess = function onsuccess(event) { - var result = event.target.result; - callback(null, result); - }; - request.onerror = function(error) { - callback(error); - }; - } catch(e) { - callback(e); - } - }; - - - function IndexedDB(name) { - this.name = name || FILE_SYSTEM_NAME; - this.db = null; - } - IndexedDB.isSupported = function() { - return !!indexedDB; - }; - - IndexedDB.prototype.open = function(callback) { - var that = this; - - // Bail if we already have a db open - if( that.db ) { - callback(null, false); - return; - } - - // Keep track of whether we're accessing this db for the first time - // and therefore needs to get formatted. - var firstAccess = false; - - // NOTE: we're not using versioned databases. - var openRequest = indexedDB.open(that.name); - - // If the db doesn't exist, we'll create it - openRequest.onupgradeneeded = function onupgradeneeded(event) { - var db = event.target.result; - - if(db.objectStoreNames.contains(FILE_STORE_NAME)) { - db.deleteObjectStore(FILE_STORE_NAME); - } - db.createObjectStore(FILE_STORE_NAME); - - firstAccess = true; - }; - - openRequest.onsuccess = function onsuccess(event) { - that.db = event.target.result; - callback(null, firstAccess); - }; - openRequest.onerror = function onerror(error) { - callback(new Errors.EINVAL('IndexedDB cannot be accessed. If private browsing is enabled, disable it.')); - }; - }; - IndexedDB.prototype.getReadOnlyContext = function() { - // Due to timing issues in Chrome with readwrite vs. readonly indexeddb transactions - // always use readwrite so we can make sure pending commits finish before callbacks. - // See https://github.com/js-platform/filer/issues/128 - return new IndexedDBContext(this.db, IDB_RW); - }; - IndexedDB.prototype.getReadWriteContext = function() { - return new IndexedDBContext(this.db, IDB_RW); - }; - - return IndexedDB; -}); - -define('src/providers/websql',['require','src/constants','src/constants','src/constants','src/constants','src/constants','src/shared','src/errors'],function(require) { - var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; - var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; - var WSQL_VERSION = require('src/constants').WSQL_VERSION; - var WSQL_SIZE = require('src/constants').WSQL_SIZE; - var WSQL_DESC = require('src/constants').WSQL_DESC; - var u8toArray = require('src/shared').u8toArray; - var Errors = require('src/errors'); - - function WebSQLContext(db, isReadOnly) { - var that = this; - this.getTransaction = function(callback) { - if(that.transaction) { - callback(that.transaction); - return; - } - // Either do readTransaction() (read-only) or transaction() (read/write) - db[isReadOnly ? 'readTransaction' : 'transaction'](function(transaction) { - that.transaction = transaction; - callback(transaction); - }); - }; - } - WebSQLContext.prototype.clear = function(callback) { - function onError(transaction, error) { - callback(error); - } - function onSuccess(transaction, result) { - callback(null); - } - this.getTransaction(function(transaction) { - transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + ";", - [], onSuccess, onError); - }); - }; - WebSQLContext.prototype.get = function(key, callback) { - function onSuccess(transaction, result) { - // If the key isn't found, return null - var value = result.rows.length === 0 ? null : result.rows.item(0).data; - try { - if(value) { - value = JSON.parse(value); - // Deal with special-cased flattened typed arrays in WebSQL (see put() below) - if(value.__isUint8Array) { - value = new Uint8Array(value.__array); - } - } - callback(null, value); - } catch(e) { - callback(e); - } - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("SELECT data FROM " + FILE_STORE_NAME + " WHERE id = ?;", - [key], onSuccess, onError); - }); - }; - WebSQLContext.prototype.put = function(key, value, callback) { - // We do extra work to make sure typed arrays survive - // being stored in the db and still get the right prototype later. - if(Object.prototype.toString.call(value) === "[object Uint8Array]") { - value = { - __isUint8Array: true, - __array: u8toArray(value) - }; - } - value = JSON.stringify(value); - function onSuccess(transaction, result) { - callback(null); - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("INSERT OR REPLACE INTO " + FILE_STORE_NAME + " (id, data) VALUES (?, ?);", - [key, value], onSuccess, onError); - }); - }; - WebSQLContext.prototype.delete = function(key, callback) { - function onSuccess(transaction, result) { - callback(null); - } - function onError(transaction, error) { - callback(error); - } - this.getTransaction(function(transaction) { - transaction.executeSql("DELETE FROM " + FILE_STORE_NAME + " WHERE id = ?;", - [key], onSuccess, onError); - }); - }; - - - function WebSQL(name) { - this.name = name || FILE_SYSTEM_NAME; - this.db = null; - } - WebSQL.isSupported = function() { - return !!window.openDatabase; - }; - - WebSQL.prototype.open = function(callback) { - var that = this; - - // Bail if we already have a db open - if(that.db) { - callback(null, false); - return; - } - - var db = window.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE); - if(!db) { - callback("[WebSQL] Unable to open database."); - return; - } - - function onError(transaction, error) { - if (error.code === 5) { - callback(new Errors.EINVAL('WebSQL cannot be accessed. If private browsing is enabled, disable it.')); - } - callback(error); - } - function onSuccess(transaction, result) { - that.db = db; - - function gotCount(transaction, result) { - var firstAccess = result.rows.item(0).count === 0; - callback(null, firstAccess); - } - function onError(transaction, error) { - callback(error); - } - // Keep track of whether we're accessing this db for the first time - // and therefore needs to get formatted. - transaction.executeSql("SELECT COUNT(id) AS count FROM " + FILE_STORE_NAME + ";", - [], gotCount, onError); - } - - // Create the table and index we'll need to store the fs data. - db.transaction(function(transaction) { - function createIndex(transaction) { - transaction.executeSql("CREATE INDEX IF NOT EXISTS idx_" + FILE_STORE_NAME + "_id" + - " on " + FILE_STORE_NAME + " (id);", - [], onSuccess, onError); - } - transaction.executeSql("CREATE TABLE IF NOT EXISTS " + FILE_STORE_NAME + " (id unique, data TEXT);", - [], createIndex, onError); - }); - }; - WebSQL.prototype.getReadOnlyContext = function() { - return new WebSQLContext(this.db, true); - }; - WebSQL.prototype.getReadWriteContext = function() { - return new WebSQLContext(this.db, false); - }; - - return WebSQL; -}); - -/*global setImmediate: false, setTimeout: false, console: false */ - -/** - * https://raw.github.com/caolan/async/master/lib/async.js Feb 18, 2014 - * Used under MIT - https://github.com/caolan/async/blob/master/LICENSE - */ - -(function () { - - var async = {}; - - // global on the server, window in the browser - var root, previous_async; - - root = this; - if (root != null) { - previous_async = root.async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - var called = false; - return function() { - if (called) throw new Error("Callback was already called."); - called = true; - fn.apply(root, arguments); - } - } - - //// cross-browser compatiblity functions //// - - var _each = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _each(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _each(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - if (typeof setImmediate === 'function') { - async.nextTick = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - async.setImmediate = async.nextTick; - } - else { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - async.setImmediate = async.nextTick; - } - } - else { - async.nextTick = process.nextTick; - if (typeof setImmediate !== 'undefined') { - async.setImmediate = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - } - else { - async.setImmediate = async.nextTick; - } - } - - async.each = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - _each(arr, function (x) { - iterator(x, only_once(function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - } - })); - }); - }; - async.forEach = async.each; - - async.eachSeries = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - async.forEachSeries = async.eachSeries; - - async.eachLimit = function (arr, limit, iterator, callback) { - var fn = _eachLimit(limit); - fn.apply(null, [arr, iterator, callback]); - }; - async.forEachLimit = async.eachLimit; - - var _eachLimit = function (limit) { - - return function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length || limit <= 0) { - return callback(); - } - var completed = 0; - var started = 0; - var running = 0; - - (function replenish () { - if (completed >= arr.length) { - return callback(); - } - - while (running < limit && started < arr.length) { - started += 1; - running += 1; - iterator(arr[started - 1], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - running -= 1; - if (completed >= arr.length) { - callback(); - } - else { - replenish(); - } - } - }); - } - })(); - }; - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.each].concat(args)); - }; - }; - var doParallelLimit = function(limit, fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [_eachLimit(limit)].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.eachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = function (arr, limit, iterator, callback) { - return _mapLimit(limit)(arr, iterator, callback); - }; - - var _mapLimit = function(limit) { - return doParallelLimit(limit, _asyncMap); - }; - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.eachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - main_callback = function () {}; - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _each(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - callback = function () {}; - } - }); - - _each(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _each(_keys(results), function(rkey) { - safeResults[rkey] = results[rkey]; - }); - safeResults[k] = args; - callback(err, safeResults); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor !== Array) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback.apply(null, arguments); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.setImmediate(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - var _parallel = function(eachfn, tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - eachfn.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - eachfn.each(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.parallel = function (tasks, callback) { - _parallel({ map: async.map, each: async.each }, tasks, callback); - }; - - async.parallelLimit = function(tasks, limit, callback) { - _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.eachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doWhilst = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (test()) { - async.doWhilst(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doUntil = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (!test()) { - async.doUntil(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.queue = function (worker, concurrency) { - if (concurrency === undefined) { - concurrency = 1; - } - function _insert(q, data, pos, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - var item = { - data: task, - callback: typeof callback === 'function' ? callback : null - }; - - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } - - if (q.saturated && q.tasks.length === concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if (q.empty && q.tasks.length === 0) { - q.empty(); - } - workers += 1; - var next = function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if (q.drain && q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - var cb = only_once(next); - worker(task.data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - async.cargo = function (worker, payload) { - var working = false, - tasks = []; - - var cargo = { - tasks: tasks, - payload: payload, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - if (cargo.saturated && tasks.length === payload) { - cargo.saturated(); - } - }); - async.setImmediate(cargo.process); - }, - process: function process() { - if (working) return; - if (tasks.length === 0) { - if(cargo.drain) cargo.drain(); - return; - } - - var ts = typeof payload === 'number' - ? tasks.splice(0, payload) - : tasks.splice(0); - - var ds = _map(ts, function (task) { - return task.data; - }); - - if(cargo.empty) cargo.empty(); - working = true; - worker(ds, function () { - working = false; - - var args = arguments; - _each(ts, function (data) { - if (data.callback) { - data.callback.apply(null, args); - } - }); - - process(); - }); - }, - length: function () { - return tasks.length; - }, - running: function () { - return working; - } - }; - return cargo; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _each(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; - - async.times = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.map(counter, iterator, callback); - }; - - async.timesSeries = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.mapSeries(counter, iterator, callback); - }; - - async.compose = function (/* functions... */) { - var fns = Array.prototype.reverse.call(arguments); - return function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([function () { - var err = arguments[0]; - var nextargs = Array.prototype.slice.call(arguments, 1); - cb(err, nextargs); - }])) - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }; - }; - - var _applyEach = function (eachfn, fns /*args...*/) { - var go = function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - return eachfn(fns, function (fn, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }; - if (arguments.length > 2) { - var args = Array.prototype.slice.call(arguments, 2); - return go.apply(this, args); - } - else { - return go; - } - }; - async.applyEach = doParallel(_applyEach); - async.applyEachSeries = doSeries(_applyEach); - - async.forever = function (fn, callback) { - function next(err) { - if (err) { - if (callback) { - return callback(err); - } - throw err; - } - fn(next); - } - next(); - }; - - // AMD / RequireJS - if (typeof define !== 'undefined' && define.amd) { - define('async',[], function () { - return async; - }); - } - // Node.js - else if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - // included directly via