Merge pull request #198 from humphd/browserify

Fixes #56
This commit is contained in:
Alan K 2014-05-27 14:35:56 -04:00
commit c9a968b009
104 changed files with 8132 additions and 21388 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@ node_modules
bower_components bower_components
.env .env
*~ *~
dist/filer-test.js

View File

@ -1,6 +1,6 @@
language: node_js language: node_js
node_js: node_js:
- "0.11" - "0.10"
before_install: npm install -g grunt-cli before_install: npm install -g grunt-cli
notifications: notifications:
email: false email: false

View File

@ -21,7 +21,8 @@ You can now run the following grunt tasks:
* `grunt check` will run [JSHint](http://www.jshint.com/) on your code (do this before submitting a pull request) to catch errors * `grunt check` will run [JSHint](http://www.jshint.com/) on your code (do this before submitting a pull request) to catch errors
* `grunt develop` will create a single file version of the library for testing in `dist/idbfs.js` * `grunt develop` will create a single file version of the library for testing in `dist/idbfs.js`
* `grunt release` like `develop` but will also create a minified version of the library in `dist/idbfs.min.js` * `grunt release` like `develop` but will also create a minified version of the library in `dist/idbfs.min.js`
* `grunt test` will run [JSHint](http://www.jshint.com/) on your code and the test suite in [PhantomJS](http://phantomjs.org/) * `grunt test` or `grunt test-node` will run [JSHint](http://www.jshint.com/) on your code and the test suite in the context of `nodejs`
* `grunt test-browser` will run [JSHint](http://www.jshint.com/) and start a localhost server on port `1234`. Navigating to `localhost:1234/tests/index.html` will run the test suite in the context of the browser. **NOTE:** When finished, you will have to manually shut off the server by pressing `cmd/ctrl`+`c` in the same terminal session you ran `grunt test-browser`.
Once you've done some hacking and you'd like to have your work merged, you'll need to Once you've done some hacking and you'd like to have your work merged, you'll need to
make a pull request. If you're patch includes code, make sure to check that all the make a pull request. If you're patch includes code, make sure to check that all the
@ -31,13 +32,11 @@ to the `AUTHORS` file.
======= =======
### Releasing a new version ### 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: `grunt publish` will:
* Run the `grunt release` task * 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 git tag at the new version number
* Create a release commit including `dist/filer.js`, `dist/filer.min.js`, `bower.json` and `package.json` * Create a release commit including `dist/filer.js`, `dist/filer.min.js`, `bower.json` and `package.json`
* Push tag & commit to `origin/develop` * Push tag & commit to `origin/develop`
@ -63,14 +62,14 @@ The user *must* be on their local `develop` branch before running any form of `g
## Tests ## Tests
Tests are writting using [Mocha](http://visionmedia.github.io/mocha/) and [Chai](http://chaijs.com/api/bdd/). 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 opening the `tests` directory. You can also run them 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`.
[here](http://js-platform.github.io/filer/tests/).
There are a number of configurable options for the test suite, which are set via query string params. 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.js or dist/filer.min.js). First, you can choose which filer source to use (i.e., src/, dist/filer-test.js, dist/filer.js or dist/filer.min.js).
The default is to use what is in /src, and you can switch to built versions like so: The default is to use what is in /dist/filer-test.js, and you can switch to other versions like so:
* tests/index.html?filer-dist/filer.js * tests/index.html?filer-dist/filer.js
* tests/index.html?filer-dist/filer.min.js * tests/index.html?filer-dist/filer.min.js
* tests/index.html?filer-src/filer.js (from src)
Second, you can specify which provider to use for all non-provider specific tests (i.e., most of the tests). Second, you can specify which provider to use for all non-provider specific tests (i.e., most of the tests).
The default provider is `Memory`, and you can switch it like so: The default provider is `Memory`, and you can switch it like so:

View File

@ -161,33 +161,6 @@ if( Filer.FileSystem.providers.WebSQL.isSupported() ) {
You can also write your own provider if you need a different backend. See the code in `src/providers` for details. You can also write your own provider if you need a different backend. See the code in `src/providers` for details.
####Filer.FileSystem.adapters - Adapters for Storage Providers
Filer based file systems can acquire new functionality by using adapters. These wrapper objects extend the abilities
of storage providers without altering them in anway. An adapter can be used with any provider, and multiple
adapters can be used together in order to compose complex functionality on top of a provider.
There are currently 2 adapters available:
* `FileSystem.adapters.Compression(provider)` - a compression adapter that uses [Zlib](https://github.com/imaya/zlib.js)
* `FileSystem.adapters.Encryption(passphrase, provider)` - an encryption adapter that uses [AES encryption](http://code.google.com/p/crypto-js/#AES)
```javascript
var FileSystem = Filer.FileSystem;
var providers = FileSystem.providers;
var adapters = FileSystem.adapters;
// Create a WebSQL-based, Encrypted, Compressed File System by
// composing a provider and adatpers.
var webSQLProvider = new providers.WebSQL();
var encryptionAdatper = new adapters.Encryption('super-secret-passphrase', webSQLProvider);
var compressionAdatper = new adatpers.Compression(encryptionAdapter);
var fs = new FileSystem({ provider: compressionAdapter });
```
You can also write your own adapter if you need to add new capabilities to the providers. Adapters share the same
interface as providers. See the code in `src/providers` and `src/adapters` for many examples.
####Filer.Path<a name="FilerPath"></a> ####Filer.Path<a name="FilerPath"></a>
The node.js [path module](http://nodejs.org/api/path.html) is available via the `Filer.Path` object. It is The node.js [path module](http://nodejs.org/api/path.html) is available via the `Filer.Path` object. It is

View File

@ -1,405 +0,0 @@
/**
* 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
};
}());

View File

@ -1,7 +0,0 @@
var Filer = require( "src/index" );
return Filer;
}));

View File

@ -1,27 +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() {

8560
dist/filer.js vendored

File diff suppressed because it is too large Load Diff

6
dist/filer.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -15,7 +15,7 @@ module.exports = function(grunt) {
grunt.initConfig({ grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), pkg: grunt.file.readJSON('package.json'),
clean: ['dist/'], clean: ['dist/filer-test.js', 'dist/filer_node-test.js'],
uglify: { uglify: {
options: { options: {
@ -51,49 +51,31 @@ module.exports = function(grunt) {
] ]
}, },
connect: { browserify: {
server: { filerDist: {
src: "./src/index.js",
dest: "./dist/filer.js",
options: { options: {
port: 9001, standalone: 'Filer',
hostname: '127.0.0.1', browserifyOptions: {
base: '.' builtins: false,
commondir: false
},
exclude: ["./node_modules/request/index.js"]
}
},
filerTest: {
src: "./tests/index.js",
dest: "./dist/filer-test.js",
options: {
standalone: 'FilerTest'
} }
} }
}, },
shell: {
mocha: { mocha: {
test: { command: './node_modules/.bin/mocha --reporter list tests/index.js'
options: {
log: true,
urls: [ 'http://127.0.0.1:9001/tests/index.html' ]
}
}
},
requirejs: {
develop: {
options: {
paths: {
"src": "../src",
"build": "../build"
},
baseUrl: "lib",
name: "build/almond",
include: ["src/index"],
out: "dist/filer.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"]
}
}
}
} }
}, },
@ -164,6 +146,21 @@ module.exports = function(grunt) {
remote: GIT_REMOTE, remote: GIT_REMOTE,
branch: 'gh-pages', branch: 'gh-pages',
force: true force: true
},
}
},
connect: {
serverForNode: {
options: {
port: 1234,
base: '.'
}
},
serverForBrowser: {
options: {
port: 1234,
base: '.',
keepalive: true
} }
} }
} }
@ -171,19 +168,19 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha');
grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-npm'); grunt.loadNpmTasks('grunt-npm');
grunt.loadNpmTasks('grunt-git'); grunt.loadNpmTasks('grunt-git');
grunt.loadNpmTasks('grunt-prompt'); grunt.loadNpmTasks('grunt-prompt');
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('develop', ['clean', 'requirejs']); grunt.registerTask('develop', ['clean', 'browserify:filerDist']);
grunt.registerTask('build-tests', ['clean', 'browserify:filerTest']);
grunt.registerTask('release', ['develop', 'uglify']); 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) { grunt.registerTask('publish', 'Publish filer as a new version to NPM, bower and github.', function(patchLevel) {
var allLevels = ['patch', 'minor', 'major']; var allLevels = ['patch', 'minor', 'major'];
@ -202,10 +199,10 @@ module.exports = function(grunt) {
' to ' + semver.inc(currentVersion, patchLevel).yellow + '?'; ' to ' + semver.inc(currentVersion, patchLevel).yellow + '?';
grunt.config('prompt.confirm.options', promptOpts); grunt.config('prompt.confirm.options', promptOpts);
// TODO: ADD NPM RELEASE
grunt.task.run([ grunt.task.run([
'prompt:confirm', 'prompt:confirm',
'checkBranch', 'checkBranch',
'test-node',
'release', 'release',
'bump:' + patchLevel, 'bump:' + patchLevel,
'gitcheckout:publish', 'gitcheckout:publish',
@ -214,6 +211,9 @@ module.exports = function(grunt) {
'npm-publish' 'npm-publish'
]); ]);
}); });
grunt.registerTask('test-node', ['jshint', 'clean', 'connect:serverForNode', 'shell:mocha']);
grunt.registerTask('test-browser', ['jshint', 'build-tests', 'connect:serverForBrowser']);
grunt.registerTask('test', ['test-node']);
grunt.registerTask('default', ['develop']); grunt.registerTask('default', ['test']);
}; };

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,19 @@
define(function(require) { // Based on https://github.com/diy/intercom.js/blob/master/lib/events.js
// Copyright 2012 DIY Co Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
// Based on https://github.com/diy/intercom.js/blob/master/lib/events.js function removeItem(item, array) {
// Copyright 2012 DIY Co Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
function removeItem(item, array) {
for (var i = array.length - 1; i >= 0; i--) { for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === item) { if (array[i] === item) {
array.splice(i, 1); array.splice(i, 1);
} }
} }
return array; return array;
} }
var EventEmitter = function() {}; var EventEmitter = function() {};
EventEmitter.createInterface = function(space) { EventEmitter.createInterface = function(space) {
var methods = {}; var methods = {};
methods.on = function(name, fn) { methods.on = function(name, fn) {
@ -53,22 +51,21 @@ define(function(require) {
}; };
return methods; return methods;
}; };
var pvt = EventEmitter.createInterface('_handlers'); var pvt = EventEmitter.createInterface('_handlers');
EventEmitter.prototype._on = pvt.on; EventEmitter.prototype._on = pvt.on;
EventEmitter.prototype._off = pvt.off; EventEmitter.prototype._off = pvt.off;
EventEmitter.prototype._trigger = pvt.trigger; EventEmitter.prototype._trigger = pvt.trigger;
var pub = EventEmitter.createInterface('handlers'); var pub = EventEmitter.createInterface('handlers');
EventEmitter.prototype.on = function() { EventEmitter.prototype.on = function() {
pub.on.apply(this, arguments); pub.on.apply(this, arguments);
Array.prototype.unshift.call(arguments, 'on'); Array.prototype.unshift.call(arguments, 'on');
this._trigger.apply(this, arguments); this._trigger.apply(this, arguments);
}; };
EventEmitter.prototype.off = pub.off; EventEmitter.prototype.off = pub.off;
EventEmitter.prototype.trigger = pub.trigger; EventEmitter.prototype.trigger = pub.trigger;
EventEmitter.prototype.removeAllListeners = pub.removeAllListeners; EventEmitter.prototype.removeAllListeners = pub.removeAllListeners;
return EventEmitter; module.exports = EventEmitter;
});

View File

@ -1,13 +1,11 @@
define(function(require) { // Based on https://github.com/diy/intercom.js/blob/master/lib/intercom.js
// Copyright 2012 DIY Co Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
// Based on https://github.com/diy/intercom.js/blob/master/lib/intercom.js var EventEmitter = require('./eventemitter.js');
// Copyright 2012 DIY Co Apache License, Version 2.0 var guid = require('../src/shared.js').guid;
// http://www.apache.org/licenses/LICENSE-2.0
var EventEmitter = require('eventemitter'); function throttle(delay, fn) {
var guid = require('src/shared').guid;
function throttle(delay, fn) {
var last = 0; var last = 0;
return function() { return function() {
var now = Date.now(); var now = Date.now();
@ -16,9 +14,9 @@ define(function(require) {
fn.apply(this, arguments); fn.apply(this, arguments);
} }
}; };
} }
function extend(a, b) { function extend(a, b) {
if (typeof a === 'undefined' || !a) { a = {}; } if (typeof a === 'undefined' || !a) { a = {}; }
if (typeof b === 'object') { if (typeof b === 'object') {
for (var key in b) { for (var key in b) {
@ -28,10 +26,11 @@ define(function(require) {
} }
} }
return a; return a;
} }
var localStorage = (function(window) { var localStorage = (function(window) {
if (typeof window.localStorage === 'undefined') { if (typeof window === 'undefined' ||
typeof window.localStorage === 'undefined') {
return { return {
getItem : function() {}, getItem : function() {},
setItem : function() {}, setItem : function() {},
@ -39,9 +38,9 @@ define(function(require) {
}; };
} }
return window.localStorage; return window.localStorage;
}(this)); }(this));
function Intercom() { function Intercom() {
var self = this; var self = this;
var now = Date.now(); var now = Date.now();
@ -53,14 +52,20 @@ define(function(require) {
var storageHandler = function() { var storageHandler = function() {
self._onStorageEvent.apply(self, arguments); 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) { if (document.attachEvent) {
document.attachEvent('onstorage', storageHandler); document.attachEvent('onstorage', storageHandler);
} else { } else {
window.addEventListener('storage', storageHandler, false); window.addEventListener('storage', storageHandler, false);
} }
} }
Intercom.prototype._transaction = function(fn) { Intercom.prototype._transaction = function(fn) {
var TIMEOUT = 1000; var TIMEOUT = 1000;
var WAIT = 20; var WAIT = 20;
var self = this; var self = this;
@ -80,7 +85,7 @@ define(function(require) {
self._on('storage', lock); self._on('storage', lock);
listening = true; listening = true;
} }
waitTimer = window.setTimeout(lock, WAIT); waitTimer = setTimeout(lock, WAIT);
return; return;
} }
executed = true; executed = true;
@ -95,15 +100,15 @@ define(function(require) {
self._off('storage', lock); self._off('storage', lock);
} }
if (waitTimer) { if (waitTimer) {
window.clearTimeout(waitTimer); clearTimeout(waitTimer);
} }
localStorage.removeItem(INDEX_LOCK); localStorage.removeItem(INDEX_LOCK);
} }
lock(); lock();
}; };
Intercom.prototype._cleanup_emit = throttle(100, function() { Intercom.prototype._cleanup_emit = throttle(100, function() {
var self = this; var self = this;
self._transaction(function() { self._transaction(function() {
@ -127,9 +132,9 @@ define(function(require) {
localStorage.setItem(INDEX_EMIT, JSON.stringify(messages)); localStorage.setItem(INDEX_EMIT, JSON.stringify(messages));
} }
}); });
}); });
Intercom.prototype._cleanup_once = throttle(100, function() { Intercom.prototype._cleanup_once = throttle(100, function() {
var self = this; var self = this;
self._transaction(function() { self._transaction(function() {
@ -154,9 +159,9 @@ define(function(require) {
localStorage.setItem(INDEX_ONCE, JSON.stringify(table)); localStorage.setItem(INDEX_ONCE, JSON.stringify(table));
} }
}); });
}); });
Intercom.prototype._once_expired = function(key, table) { Intercom.prototype._once_expired = function(key, table) {
if (!table) { if (!table) {
return true; return true;
} }
@ -171,9 +176,9 @@ define(function(require) {
var now = Date.now(); var now = Date.now();
var timestamp = table[key].timestamp; var timestamp = table[key].timestamp;
return timestamp < now - ttl; return timestamp < now - ttl;
}; };
Intercom.prototype._localStorageChanged = function(event, field) { Intercom.prototype._localStorageChanged = function(event, field) {
if (event && event.key) { if (event && event.key) {
return event.key === field; return event.key === field;
} }
@ -184,9 +189,9 @@ define(function(require) {
} }
this.previousValues[field] = currentValue; this.previousValues[field] = currentValue;
return true; return true;
}; };
Intercom.prototype._onStorageEvent = function(event) { Intercom.prototype._onStorageEvent = function(event) {
event = event || window.event; event = event || window.event;
var self = this; var self = this;
@ -215,9 +220,9 @@ define(function(require) {
} }
this._trigger('storage', event); this._trigger('storage', event);
}; };
Intercom.prototype._emit = function(name, message, id) { Intercom.prototype._emit = function(name, message, id) {
id = (typeof id === 'string' || typeof id === 'number') ? String(id) : null; id = (typeof id === 'string' || typeof id === 'number') ? String(id) : null;
if (id && id.length) { if (id && id.length) {
if (this.receivedIDs.hasOwnProperty(id)) return; if (this.receivedIDs.hasOwnProperty(id)) return;
@ -240,18 +245,18 @@ define(function(require) {
localStorage.setItem(INDEX_EMIT, data); localStorage.setItem(INDEX_EMIT, data);
self.trigger(name, message); self.trigger(name, message);
window.setTimeout(function() { setTimeout(function() {
self._cleanup_emit(); self._cleanup_emit();
}, 50); }, 50);
}); });
}; };
Intercom.prototype.emit = function(name, message) { Intercom.prototype.emit = function(name, message) {
this._emit.apply(this, arguments); this._emit.apply(this, arguments);
this._trigger('emit', name, message); this._trigger('emit', name, message);
}; };
Intercom.prototype.once = function(key, fn, ttl) { Intercom.prototype.once = function(key, fn, ttl) {
if (!Intercom.supported) { if (!Intercom.supported) {
return; return;
} }
@ -277,30 +282,30 @@ define(function(require) {
localStorage.setItem(INDEX_ONCE, JSON.stringify(data)); localStorage.setItem(INDEX_ONCE, JSON.stringify(data));
fn(); fn();
window.setTimeout(function() { setTimeout(function() {
self._cleanup_once(); self._cleanup_once();
}, 50); }, 50);
}); });
}; };
extend(Intercom.prototype, EventEmitter.prototype); extend(Intercom.prototype, EventEmitter.prototype);
Intercom.supported = (typeof localStorage !== 'undefined'); Intercom.supported = (typeof localStorage !== 'undefined');
var INDEX_EMIT = 'intercom'; var INDEX_EMIT = 'intercom';
var INDEX_ONCE = 'intercom_once'; var INDEX_ONCE = 'intercom_once';
var INDEX_LOCK = 'intercom_lock'; var INDEX_LOCK = 'intercom_lock';
var THRESHOLD_TTL_EMIT = 50000; var THRESHOLD_TTL_EMIT = 50000;
var THRESHOLD_TTL_ONCE = 1000 * 3600; var THRESHOLD_TTL_ONCE = 1000 * 3600;
Intercom.destroy = function() { Intercom.destroy = function() {
localStorage.removeItem(INDEX_LOCK); localStorage.removeItem(INDEX_LOCK);
localStorage.removeItem(INDEX_EMIT); localStorage.removeItem(INDEX_EMIT);
localStorage.removeItem(INDEX_ONCE); localStorage.removeItem(INDEX_ONCE);
}; };
Intercom.getInstance = (function() { Intercom.getInstance = (function() {
var intercom; var intercom;
return function() { return function() {
if (!intercom) { if (!intercom) {
@ -308,7 +313,6 @@ define(function(require) {
} }
return intercom; return intercom;
}; };
})(); })();
return Intercom; module.exports = Intercom;
});

View File

@ -7,41 +7,38 @@
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license> * Available under MIT license <http://lodash.com/license>
*/ */
var ArrayProto = Array.prototype;
var nativeForEach = ArrayProto.forEach;
var nativeIndexOf = ArrayProto.indexOf;
var nativeSome = ArrayProto.some;
define(function(require) { var ObjProto = Object.prototype;
var hasOwnProperty = ObjProto.hasOwnProperty;
var nativeKeys = Object.keys;
var ArrayProto = Array.prototype; var breaker = {};
var nativeForEach = ArrayProto.forEach;
var nativeIndexOf = ArrayProto.indexOf;
var nativeSome = ArrayProto.some;
var ObjProto = Object.prototype; function has(obj, key) {
var hasOwnProperty = ObjProto.hasOwnProperty;
var nativeKeys = Object.keys;
var breaker = {};
function has(obj, key) {
return hasOwnProperty.call(obj, key); return hasOwnProperty.call(obj, key);
} }
var keys = nativeKeys || function(obj) { var keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object'); if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = []; var keys = [];
for (var key in obj) if (has(obj, key)) keys.push(key); for (var key in obj) if (has(obj, key)) keys.push(key);
return keys; return keys;
}; };
function size(obj) { function size(obj) {
if (obj == null) return 0; if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : keys(obj).length; return (obj.length === +obj.length) ? obj.length : keys(obj).length;
} }
function identity(value) { function identity(value) {
return value; return value;
} }
function each(obj, iterator, context) { function each(obj, iterator, context) {
var i, length; var i, length;
if (obj == null) return; if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) { if (nativeForEach && obj.forEach === nativeForEach) {
@ -56,9 +53,9 @@ define(function(require) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
} }
} }
}; };
function any(obj, iterator, context) { function any(obj, iterator, context) {
iterator || (iterator = identity); iterator || (iterator = identity);
var result = false; var result = false;
if (obj == null) return result; if (obj == null) return result;
@ -67,36 +64,34 @@ define(function(require) {
if (result || (result = iterator.call(context, value, index, list))) return breaker; if (result || (result = iterator.call(context, value, index, list))) return breaker;
}); });
return !!result; return !!result;
}; };
function contains(obj, target) { function contains(obj, target) {
if (obj == null) return false; if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) { return any(obj, function(value) {
return value === target; return value === target;
}); });
}; };
function Wrapped(value) { function Wrapped(value) {
this.value = value; this.value = value;
} }
Wrapped.prototype.has = function(key) { Wrapped.prototype.has = function(key) {
return has(this.value, key); return has(this.value, key);
}; };
Wrapped.prototype.contains = function(target) { Wrapped.prototype.contains = function(target) {
return contains(this.value, target); return contains(this.value, target);
}; };
Wrapped.prototype.size = function() { Wrapped.prototype.size = function() {
return size(this.value); return size(this.value);
}; };
function nodash(value) { function nodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor // 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__')) return (value && typeof value == 'object' && !Array.isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value ? value
: new Wrapped(value); : new Wrapped(value);
} }
return nodash; module.exports = nodash;
});

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +0,0 @@
/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';function m(a){throw a;}var q=void 0,u,aa=this;function v(a,b){var c=a.split("."),d=aa;!(c[0]in d)&&d.execScript&&d.execScript("var "+c[0]);for(var f;c.length&&(f=c.shift());)!c.length&&b!==q?d[f]=b:d=d[f]?d[f]:d[f]={}};var w="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;new (w?Uint8Array:Array)(256);var x;for(x=0;256>x;++x)for(var y=x,ba=7,y=y>>>1;y;y>>>=1)--ba;var z=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,
2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,
2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,
2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,
3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,
936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],B=w?new Uint32Array(z):z;function C(a){var b=a.length,c=0,d=Number.POSITIVE_INFINITY,f,h,k,e,g,l,p,s,r,A;for(s=0;s<b;++s)a[s]>c&&(c=a[s]),a[s]<d&&(d=a[s]);f=1<<c;h=new (w?Uint32Array:Array)(f);k=1;e=0;for(g=2;k<=c;){for(s=0;s<b;++s)if(a[s]===k){l=0;p=e;for(r=0;r<k;++r)l=l<<1|p&1,p>>=1;A=k<<16|s;for(r=l;r<f;r+=g)h[r]=A;++e}++k;e<<=1;g<<=1}return[h,c,d]};var D=[],E;for(E=0;288>E;E++)switch(!0){case 143>=E:D.push([E+48,8]);break;case 255>=E:D.push([E-144+400,9]);break;case 279>=E:D.push([E-256+0,7]);break;case 287>=E:D.push([E-280+192,8]);break;default:m("invalid literal: "+E)}
var ca=function(){function a(a){switch(!0){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,
a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:m("invalid length: "+a)}}var b=[],c,d;for(c=3;258>=c;c++)d=a(c),b[c]=d[2]<<24|d[1]<<
16|d[0];return b}();w&&new Uint32Array(ca);function F(a,b){this.l=[];this.m=32768;this.d=this.f=this.c=this.t=0;this.input=w?new Uint8Array(a):a;this.u=!1;this.n=G;this.L=!1;if(b||!(b={}))b.index&&(this.c=b.index),b.bufferSize&&(this.m=b.bufferSize),b.bufferType&&(this.n=b.bufferType),b.resize&&(this.L=b.resize);switch(this.n){case H:this.a=32768;this.b=new (w?Uint8Array:Array)(32768+this.m+258);break;case G:this.a=0;this.b=new (w?Uint8Array:Array)(this.m);this.e=this.X;this.B=this.S;this.q=this.W;break;default:m(Error("invalid inflate mode"))}}
var H=0,G=1;
F.prototype.r=function(){for(;!this.u;){var a=I(this,3);a&1&&(this.u=!0);a>>>=1;switch(a){case 0:var b=this.input,c=this.c,d=this.b,f=this.a,h=b.length,k=q,e=q,g=d.length,l=q;this.d=this.f=0;c+1>=h&&m(Error("invalid uncompressed block header: LEN"));k=b[c++]|b[c++]<<8;c+1>=h&&m(Error("invalid uncompressed block header: NLEN"));e=b[c++]|b[c++]<<8;k===~e&&m(Error("invalid uncompressed block header: length verify"));c+k>b.length&&m(Error("input buffer is broken"));switch(this.n){case H:for(;f+k>d.length;){l=
g-f;k-=l;if(w)d.set(b.subarray(c,c+l),f),f+=l,c+=l;else for(;l--;)d[f++]=b[c++];this.a=f;d=this.e();f=this.a}break;case G:for(;f+k>d.length;)d=this.e({H:2});break;default:m(Error("invalid inflate mode"))}if(w)d.set(b.subarray(c,c+k),f),f+=k,c+=k;else for(;k--;)d[f++]=b[c++];this.c=c;this.a=f;this.b=d;break;case 1:this.q(da,ea);break;case 2:fa(this);break;default:m(Error("unknown BTYPE: "+a))}}return this.B()};
var J=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],K=w?new Uint16Array(J):J,L=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],M=w?new Uint16Array(L):L,ga=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],O=w?new Uint8Array(ga):ga,ha=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ia=w?new Uint16Array(ha):ha,ja=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,
12,12,13,13],P=w?new Uint8Array(ja):ja,Q=new (w?Uint8Array:Array)(288),R,la;R=0;for(la=Q.length;R<la;++R)Q[R]=143>=R?8:255>=R?9:279>=R?7:8;var da=C(Q),S=new (w?Uint8Array:Array)(30),T,ma;T=0;for(ma=S.length;T<ma;++T)S[T]=5;var ea=C(S);function I(a,b){for(var c=a.f,d=a.d,f=a.input,h=a.c,k=f.length,e;d<b;)h>=k&&m(Error("input buffer is broken")),c|=f[h++]<<d,d+=8;e=c&(1<<b)-1;a.f=c>>>b;a.d=d-b;a.c=h;return e}
function U(a,b){for(var c=a.f,d=a.d,f=a.input,h=a.c,k=f.length,e=b[0],g=b[1],l,p;d<g&&!(h>=k);)c|=f[h++]<<d,d+=8;l=e[c&(1<<g)-1];p=l>>>16;a.f=c>>p;a.d=d-p;a.c=h;return l&65535}
function fa(a){function b(a,b,c){var d,e=this.K,f,g;for(g=0;g<a;)switch(d=U(this,b),d){case 16:for(f=3+I(this,2);f--;)c[g++]=e;break;case 17:for(f=3+I(this,3);f--;)c[g++]=0;e=0;break;case 18:for(f=11+I(this,7);f--;)c[g++]=0;e=0;break;default:e=c[g++]=d}this.K=e;return c}var c=I(a,5)+257,d=I(a,5)+1,f=I(a,4)+4,h=new (w?Uint8Array:Array)(K.length),k,e,g,l;for(l=0;l<f;++l)h[K[l]]=I(a,3);if(!w){l=f;for(f=h.length;l<f;++l)h[K[l]]=0}k=C(h);e=new (w?Uint8Array:Array)(c);g=new (w?Uint8Array:Array)(d);a.K=
0;a.q(C(b.call(a,c,k,e)),C(b.call(a,d,k,g)))}u=F.prototype;u.q=function(a,b){var c=this.b,d=this.a;this.C=a;for(var f=c.length-258,h,k,e,g;256!==(h=U(this,a));)if(256>h)d>=f&&(this.a=d,c=this.e(),d=this.a),c[d++]=h;else{k=h-257;g=M[k];0<O[k]&&(g+=I(this,O[k]));h=U(this,b);e=ia[h];0<P[h]&&(e+=I(this,P[h]));d>=f&&(this.a=d,c=this.e(),d=this.a);for(;g--;)c[d]=c[d++-e]}for(;8<=this.d;)this.d-=8,this.c--;this.a=d};
u.W=function(a,b){var c=this.b,d=this.a;this.C=a;for(var f=c.length,h,k,e,g;256!==(h=U(this,a));)if(256>h)d>=f&&(c=this.e(),f=c.length),c[d++]=h;else{k=h-257;g=M[k];0<O[k]&&(g+=I(this,O[k]));h=U(this,b);e=ia[h];0<P[h]&&(e+=I(this,P[h]));d+g>f&&(c=this.e(),f=c.length);for(;g--;)c[d]=c[d++-e]}for(;8<=this.d;)this.d-=8,this.c--;this.a=d};
u.e=function(){var a=new (w?Uint8Array:Array)(this.a-32768),b=this.a-32768,c,d,f=this.b;if(w)a.set(f.subarray(32768,a.length));else{c=0;for(d=a.length;c<d;++c)a[c]=f[c+32768]}this.l.push(a);this.t+=a.length;if(w)f.set(f.subarray(b,b+32768));else for(c=0;32768>c;++c)f[c]=f[b+c];this.a=32768;return f};
u.X=function(a){var b,c=this.input.length/this.c+1|0,d,f,h,k=this.input,e=this.b;a&&("number"===typeof a.H&&(c=a.H),"number"===typeof a.Q&&(c+=a.Q));2>c?(d=(k.length-this.c)/this.C[2],h=258*(d/2)|0,f=h<e.length?e.length+h:e.length<<1):f=e.length*c;w?(b=new Uint8Array(f),b.set(e)):b=e;return this.b=b};
u.B=function(){var a=0,b=this.b,c=this.l,d,f=new (w?Uint8Array:Array)(this.t+(this.a-32768)),h,k,e,g;if(0===c.length)return w?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);h=0;for(k=c.length;h<k;++h){d=c[h];e=0;for(g=d.length;e<g;++e)f[a++]=d[e]}h=32768;for(k=this.a;h<k;++h)f[a++]=b[h];this.l=[];return this.buffer=f};
u.S=function(){var a,b=this.a;w?this.L?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b);return this.buffer=a};function V(a){a=a||{};this.files=[];this.v=a.comment}V.prototype.M=function(a){this.j=a};V.prototype.s=function(a){var b=a[2]&65535|2;return b*(b^1)>>8&255};V.prototype.k=function(a,b){a[0]=(B[(a[0]^b)&255]^a[0]>>>8)>>>0;a[1]=(6681*(20173*(a[1]+(a[0]&255))>>>0)>>>0)+1>>>0;a[2]=(B[(a[2]^a[1]>>>24)&255]^a[2]>>>8)>>>0};V.prototype.U=function(a){var b=[305419896,591751049,878082192],c,d;w&&(b=new Uint32Array(b));c=0;for(d=a.length;c<d;++c)this.k(b,a[c]&255);return b};function W(a,b){b=b||{};this.input=w&&a instanceof Array?new Uint8Array(a):a;this.c=0;this.ca=b.verify||!1;this.j=b.password}var na={P:0,N:8},X=[80,75,1,2],Y=[80,75,3,4],Z=[80,75,5,6];function oa(a,b){this.input=a;this.offset=b}
oa.prototype.parse=function(){var a=this.input,b=this.offset;(a[b++]!==X[0]||a[b++]!==X[1]||a[b++]!==X[2]||a[b++]!==X[3])&&m(Error("invalid file header signature"));this.version=a[b++];this.ja=a[b++];this.$=a[b++]|a[b++]<<8;this.I=a[b++]|a[b++]<<8;this.A=a[b++]|a[b++]<<8;this.time=a[b++]|a[b++]<<8;this.V=a[b++]|a[b++]<<8;this.p=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.z=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.J=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.h=a[b++]|a[b++]<<
8;this.g=a[b++]|a[b++]<<8;this.F=a[b++]|a[b++]<<8;this.fa=a[b++]|a[b++]<<8;this.ha=a[b++]|a[b++]<<8;this.ga=a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24;this.aa=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.filename=String.fromCharCode.apply(null,w?a.subarray(b,b+=this.h):a.slice(b,b+=this.h));this.Y=w?a.subarray(b,b+=this.g):a.slice(b,b+=this.g);this.v=w?a.subarray(b,b+this.F):a.slice(b,b+this.F);this.length=b-this.offset};function pa(a,b){this.input=a;this.offset=b}var qa={O:1,da:8,ea:2048};
pa.prototype.parse=function(){var a=this.input,b=this.offset;(a[b++]!==Y[0]||a[b++]!==Y[1]||a[b++]!==Y[2]||a[b++]!==Y[3])&&m(Error("invalid local file header signature"));this.$=a[b++]|a[b++]<<8;this.I=a[b++]|a[b++]<<8;this.A=a[b++]|a[b++]<<8;this.time=a[b++]|a[b++]<<8;this.V=a[b++]|a[b++]<<8;this.p=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.z=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.J=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.h=a[b++]|a[b++]<<8;this.g=a[b++]|a[b++]<<8;this.filename=
String.fromCharCode.apply(null,w?a.subarray(b,b+=this.h):a.slice(b,b+=this.h));this.Y=w?a.subarray(b,b+=this.g):a.slice(b,b+=this.g);this.length=b-this.offset};
function $(a){var b=[],c={},d,f,h,k;if(!a.i){if(a.o===q){var e=a.input,g;if(!a.D)a:{var l=a.input,p;for(p=l.length-12;0<p;--p)if(l[p]===Z[0]&&l[p+1]===Z[1]&&l[p+2]===Z[2]&&l[p+3]===Z[3]){a.D=p;break a}m(Error("End of Central Directory Record not found"))}g=a.D;(e[g++]!==Z[0]||e[g++]!==Z[1]||e[g++]!==Z[2]||e[g++]!==Z[3])&&m(Error("invalid signature"));a.ia=e[g++]|e[g++]<<8;a.ka=e[g++]|e[g++]<<8;a.la=e[g++]|e[g++]<<8;a.ba=e[g++]|e[g++]<<8;a.R=(e[g++]|e[g++]<<8|e[g++]<<16|e[g++]<<24)>>>0;a.o=(e[g++]|
e[g++]<<8|e[g++]<<16|e[g++]<<24)>>>0;a.w=e[g++]|e[g++]<<8;a.v=w?e.subarray(g,g+a.w):e.slice(g,g+a.w)}d=a.o;h=0;for(k=a.ba;h<k;++h)f=new oa(a.input,d),f.parse(),d+=f.length,b[h]=f,c[f.filename]=h;a.R<d-a.o&&m(Error("invalid file header size"));a.i=b;a.G=c}}u=W.prototype;u.Z=function(){var a=[],b,c,d;this.i||$(this);d=this.i;b=0;for(c=d.length;b<c;++b)a[b]=d[b].filename;return a};
u.r=function(a,b){var c;this.G||$(this);c=this.G[a];c===q&&m(Error(a+" not found"));var d;d=b||{};var f=this.input,h=this.i,k,e,g,l,p,s,r,A;h||$(this);h[c]===q&&m(Error("wrong index"));e=h[c].aa;k=new pa(this.input,e);k.parse();e+=k.length;g=k.z;if(0!==(k.I&qa.O)){!d.password&&!this.j&&m(Error("please set password"));s=this.T(d.password||this.j);r=e;for(A=e+12;r<A;++r)ra(this,s,f[r]);e+=12;g-=12;r=e;for(A=e+g;r<A;++r)f[r]=ra(this,s,f[r])}switch(k.A){case na.P:l=w?this.input.subarray(e,e+g):this.input.slice(e,
e+g);break;case na.N:l=(new F(this.input,{index:e,bufferSize:k.J})).r();break;default:m(Error("unknown compression type"))}if(this.ca){var t=q,n,N="number"===typeof t?t:t=0,ka=l.length;n=-1;for(N=ka&7;N--;++t)n=n>>>8^B[(n^l[t])&255];for(N=ka>>3;N--;t+=8)n=n>>>8^B[(n^l[t])&255],n=n>>>8^B[(n^l[t+1])&255],n=n>>>8^B[(n^l[t+2])&255],n=n>>>8^B[(n^l[t+3])&255],n=n>>>8^B[(n^l[t+4])&255],n=n>>>8^B[(n^l[t+5])&255],n=n>>>8^B[(n^l[t+6])&255],n=n>>>8^B[(n^l[t+7])&255];p=(n^4294967295)>>>0;k.p!==p&&m(Error("wrong crc: file=0x"+
k.p.toString(16)+", data=0x"+p.toString(16)))}return l};u.M=function(a){this.j=a};function ra(a,b,c){c^=a.s(b);a.k(b,c);return c}u.k=V.prototype.k;u.T=V.prototype.U;u.s=V.prototype.s;v("Zlib.Unzip",W);v("Zlib.Unzip.prototype.decompress",W.prototype.r);v("Zlib.Unzip.prototype.getFilenames",W.prototype.Z);v("Zlib.Unzip.prototype.setPassword",W.prototype.M);}).call(this);

View File

@ -1,3 +1,5 @@
var ZlibNamespace = {};
/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';var n=void 0,y=!0,aa=this;function G(e,b){var a=e.split("."),d=aa;!(a[0]in d)&&d.execScript&&d.execScript("var "+a[0]);for(var c;a.length&&(c=a.shift());)!a.length&&b!==n?d[c]=b:d=d[c]?d[c]:d[c]={}};var H="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function ba(e,b){this.index="number"===typeof b?b:0;this.f=0;this.buffer=e instanceof(H?Uint8Array:Array)?e:new (H?Uint8Array:Array)(32768);if(2*this.buffer.length<=this.index)throw Error("invalid index");this.buffer.length<=this.index&&ca(this)}function ca(e){var b=e.buffer,a,d=b.length,c=new (H?Uint8Array:Array)(d<<1);if(H)c.set(b);else for(a=0;a<d;++a)c[a]=b[a];return e.buffer=c} /** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';var n=void 0,y=!0,aa=this;function G(e,b){var a=e.split("."),d=aa;!(a[0]in d)&&d.execScript&&d.execScript("var "+a[0]);for(var c;a.length&&(c=a.shift());)!a.length&&b!==n?d[c]=b:d=d[c]?d[c]:d[c]={}};var H="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function ba(e,b){this.index="number"===typeof b?b:0;this.f=0;this.buffer=e instanceof(H?Uint8Array:Array)?e:new (H?Uint8Array:Array)(32768);if(2*this.buffer.length<=this.index)throw Error("invalid index");this.buffer.length<=this.index&&ca(this)}function ca(e){var b=e.buffer,a,d=b.length,c=new (H?Uint8Array:Array)(d<<1);if(H)c.set(b);else for(a=0;a<d;++a)c[a]=b[a];return e.buffer=c}
ba.prototype.b=function(e,b,a){var d=this.buffer,c=this.index,f=this.f,l=d[c],p;a&&1<b&&(e=8<b?(L[e&255]<<24|L[e>>>8&255]<<16|L[e>>>16&255]<<8|L[e>>>24&255])>>32-b:L[e]>>8-b);if(8>b+f)l=l<<b|e,f+=b;else for(p=0;p<b;++p)l=l<<1|e>>b-p-1&1,8===++f&&(f=0,d[c++]=L[l],l=0,c===d.length&&(d=ca(this)));d[c]=l;this.buffer=d;this.f=f;this.index=c};ba.prototype.finish=function(){var e=this.buffer,b=this.index,a;0<this.f&&(e[b]<<=8-this.f,e[b]=L[e[b]],b++);H?a=e.subarray(0,b):(e.length=b,a=e);return a}; ba.prototype.b=function(e,b,a){var d=this.buffer,c=this.index,f=this.f,l=d[c],p;a&&1<b&&(e=8<b?(L[e&255]<<24|L[e>>>8&255]<<16|L[e>>>16&255]<<8|L[e>>>24&255])>>32-b:L[e]>>8-b);if(8>b+f)l=l<<b|e,f+=b;else for(p=0;p<b;++p)l=l<<1|e>>b-p-1&1,8===++f&&(f=0,d[c++]=L[l],l=0,c===d.length&&(d=ca(this)));d[c]=l;this.buffer=d;this.f=f;this.index=c};ba.prototype.finish=function(){var e=this.buffer,b=this.index,a;0<this.f&&(e[b]<<=8-this.f,e[b]=L[e[b]],b++);H?a=e.subarray(0,b):(e.length=b,a=e);return a};
var da=new (H?Uint8Array:Array)(256),ha;for(ha=0;256>ha;++ha){for(var U=ha,ja=U,ka=7,U=U>>>1;U;U>>>=1)ja<<=1,ja|=U&1,--ka;da[ha]=(ja<<ka&255)>>>0}var L=da;function la(e){var b=n,a,d="number"===typeof b?b:b=0,c=e.length;a=-1;for(d=c&7;d--;++b)a=a>>>8^V[(a^e[b])&255];for(d=c>>3;d--;b+=8)a=a>>>8^V[(a^e[b])&255],a=a>>>8^V[(a^e[b+1])&255],a=a>>>8^V[(a^e[b+2])&255],a=a>>>8^V[(a^e[b+3])&255],a=a>>>8^V[(a^e[b+4])&255],a=a>>>8^V[(a^e[b+5])&255],a=a>>>8^V[(a^e[b+6])&255],a=a>>>8^V[(a^e[b+7])&255];return(a^4294967295)>>>0} var da=new (H?Uint8Array:Array)(256),ha;for(ha=0;256>ha;++ha){for(var U=ha,ja=U,ka=7,U=U>>>1;U;U>>>=1)ja<<=1,ja|=U&1,--ka;da[ha]=(ja<<ka&255)>>>0}var L=da;function la(e){var b=n,a,d="number"===typeof b?b:b=0,c=e.length;a=-1;for(d=c&7;d--;++b)a=a>>>8^V[(a^e[b])&255];for(d=c>>3;d--;b+=8)a=a>>>8^V[(a^e[b])&255],a=a>>>8^V[(a^e[b+1])&255],a=a>>>8^V[(a^e[b+2])&255],a=a>>>8^V[(a^e[b+3])&255],a=a>>>8^V[(a^e[b+4])&255],a=a>>>8^V[(a^e[b+5])&255],a=a>>>8^V[(a^e[b+6])&255],a=a>>>8^V[(a^e[b+7])&255];return(a^4294967295)>>>0}
@ -34,4 +36,38 @@ W=n,X=n;H&&(O=new Uint32Array(O));W=0;for(X=ea.length;W<X;++W)Pa(O,ea[W]&255);N=
1980&127)<<1|u.getMonth()+1>>3;m=b.h;a[d++]=a[c++]=m&255;a[d++]=a[c++]=m>>8&255;a[d++]=a[c++]=m>>16&255;a[d++]=a[c++]=m>>24&255;h=b.buffer.length;a[d++]=a[c++]=h&255;a[d++]=a[c++]=h>>8&255;a[d++]=a[c++]=h>>16&255;a[d++]=a[c++]=h>>24&255;s=b.size;a[d++]=a[c++]=s&255;a[d++]=a[c++]=s>>8&255;a[d++]=a[c++]=s>>16&255;a[d++]=a[c++]=s>>24&255;a[d++]=a[c++]=t&255;a[d++]=a[c++]=t>>8&255;a[d++]=a[c++]=0;a[d++]=a[c++]=0;a[c++]=r&255;a[c++]=r>>8&255;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]= 1980&127)<<1|u.getMonth()+1>>3;m=b.h;a[d++]=a[c++]=m&255;a[d++]=a[c++]=m>>8&255;a[d++]=a[c++]=m>>16&255;a[d++]=a[c++]=m>>24&255;h=b.buffer.length;a[d++]=a[c++]=h&255;a[d++]=a[c++]=h>>8&255;a[d++]=a[c++]=h>>16&255;a[d++]=a[c++]=h>>24&255;s=b.size;a[d++]=a[c++]=s&255;a[d++]=a[c++]=s>>8&255;a[d++]=a[c++]=s>>16&255;a[d++]=a[c++]=s>>24&255;a[d++]=a[c++]=t&255;a[d++]=a[c++]=t>>8&255;a[d++]=a[c++]=0;a[d++]=a[c++]=0;a[c++]=r&255;a[c++]=r>>8&255;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=0;a[c++]=
0;a[c++]=0;a[c++]=k&255;a[c++]=k>>8&255;a[c++]=k>>16&255;a[c++]=k>>24&255;if(Q=b.a.filename)if(H)a.set(Q,d),a.set(Q,c),d+=t,c+=t;else for(g=0;g<t;++g)a[d++]=a[c++]=Q[g];if(z=b.a.extraField)if(H)a.set(z,d),a.set(z,c),d+=0,c+=0;else for(g=0;g<r;++g)a[d++]=a[c++]=z[g];if(A=b.a.comment)if(H)a.set(A,c),c+=r;else for(g=0;g<r;++g)a[c++]=A[g];if(H)a.set(b.buffer,d),d+=b.buffer.length;else{g=0;for(J=b.buffer.length;g<J;++g)a[d++]=b.buffer[g]}}a[f++]=Oa[0];a[f++]=Oa[1];a[f++]=Oa[2];a[f++]=Oa[3];a[f++]=0;a[f++]= 0;a[c++]=0;a[c++]=k&255;a[c++]=k>>8&255;a[c++]=k>>16&255;a[c++]=k>>24&255;if(Q=b.a.filename)if(H)a.set(Q,d),a.set(Q,c),d+=t,c+=t;else for(g=0;g<t;++g)a[d++]=a[c++]=Q[g];if(z=b.a.extraField)if(H)a.set(z,d),a.set(z,c),d+=0,c+=0;else for(g=0;g<r;++g)a[d++]=a[c++]=z[g];if(A=b.a.comment)if(H)a.set(A,c),c+=r;else for(g=0;g<r;++g)a[c++]=A[g];if(H)a.set(b.buffer,d),d+=b.buffer.length;else{g=0;for(J=b.buffer.length;g<J;++g)a[d++]=b.buffer[g]}}a[f++]=Oa[0];a[f++]=Oa[1];a[f++]=Oa[2];a[f++]=Oa[3];a[f++]=0;a[f++]=
0;a[f++]=0;a[f++]=0;a[f++]=C&255;a[f++]=C>>8&255;a[f++]=C&255;a[f++]=C>>8&255;a[f++]=p&255;a[f++]=p>>8&255;a[f++]=p>>16&255;a[f++]=p>>24&255;a[f++]=l&255;a[f++]=l>>8&255;a[f++]=l>>16&255;a[f++]=l>>24&255;r=this.d?this.d.length:0;a[f++]=r&255;a[f++]=r>>8&255;if(this.d)if(H)a.set(this.d,f);else{g=0;for(J=r;g<J;++g)a[f++]=this.d[g]}return a};function Qa(e,b){var a,d=e[2]&65535|2;a=d*(d^1)>>8&255;Pa(e,b);return a^b} 0;a[f++]=0;a[f++]=0;a[f++]=C&255;a[f++]=C>>8&255;a[f++]=C&255;a[f++]=C>>8&255;a[f++]=p&255;a[f++]=p>>8&255;a[f++]=p>>16&255;a[f++]=p>>24&255;a[f++]=l&255;a[f++]=l>>8&255;a[f++]=l>>16&255;a[f++]=l>>24&255;r=this.d?this.d.length:0;a[f++]=r&255;a[f++]=r>>8&255;if(this.d)if(H)a.set(this.d,f);else{g=0;for(J=r;g<J;++g)a[f++]=this.d[g]}return a};function Qa(e,b){var a,d=e[2]&65535|2;a=d*(d^1)>>8&255;Pa(e,b);return a^b}
function Pa(e,b){e[0]=(V[(e[0]^b)&255]^e[0]>>>8)>>>0;e[1]=(6681*(20173*(e[1]+(e[0]&255))>>>0)>>>0)+1>>>0;e[2]=(V[(e[2]^e[1]>>>24)&255]^e[2]>>>8)>>>0};function Ra(e,b){var a,d,c,f;if(Object.keys)a=Object.keys(b);else for(d in a=[],c=0,b)a[c++]=d;c=0;for(f=a.length;c<f;++c)d=a[c],G(e+"."+d,b[d])};G("Zlib.Zip",$);G("Zlib.Zip.prototype.addFile",$.prototype.m);G("Zlib.Zip.prototype.compress",$.prototype.g);G("Zlib.Zip.prototype.setPassword",$.prototype.q);Ra("Zlib.Zip.CompressionMethod",{STORE:0,DEFLATE:8});Ra("Zlib.Zip.OperatingSystem",{MSDOS:0,UNIX:3,MACINTOSH:7});}).call(this); function Pa(e,b){e[0]=(V[(e[0]^b)&255]^e[0]>>>8)>>>0;e[1]=(6681*(20173*(e[1]+(e[0]&255))>>>0)>>>0)+1>>>0;e[2]=(V[(e[2]^e[1]>>>24)&255]^e[2]>>>8)>>>0};function Ra(e,b){var a,d,c,f;if(Object.keys)a=Object.keys(b);else for(d in a=[],c=0,b)a[c++]=d;c=0;for(f=a.length;c<f;++c)d=a[c],G(e+"."+d,b[d])};G("Zlib.Zip",$);G("Zlib.Zip.prototype.addFile",$.prototype.m);G("Zlib.Zip.prototype.compress",$.prototype.g);G("Zlib.Zip.prototype.setPassword",$.prototype.q);Ra("Zlib.Zip.CompressionMethod",{STORE:0,DEFLATE:8});Ra("Zlib.Zip.OperatingSystem",{MSDOS:0,UNIX:3,MACINTOSH:7});}).call(ZlibNamespace);
/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';function m(a){throw a;}var q=void 0,u,aa=this;function v(a,b){var c=a.split("."),d=aa;!(c[0]in d)&&d.execScript&&d.execScript("var "+c[0]);for(var f;c.length&&(f=c.shift());)!c.length&&b!==q?d[f]=b:d=d[f]?d[f]:d[f]={}};var w="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;new (w?Uint8Array:Array)(256);var x;for(x=0;256>x;++x)for(var y=x,ba=7,y=y>>>1;y;y>>>=1)--ba;var z=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,
2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,
2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,
2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,
3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,
936918E3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],B=w?new Uint32Array(z):z;function C(a){var b=a.length,c=0,d=Number.POSITIVE_INFINITY,f,h,k,e,g,l,p,s,r,A;for(s=0;s<b;++s)a[s]>c&&(c=a[s]),a[s]<d&&(d=a[s]);f=1<<c;h=new (w?Uint32Array:Array)(f);k=1;e=0;for(g=2;k<=c;){for(s=0;s<b;++s)if(a[s]===k){l=0;p=e;for(r=0;r<k;++r)l=l<<1|p&1,p>>=1;A=k<<16|s;for(r=l;r<f;r+=g)h[r]=A;++e}++k;e<<=1;g<<=1}return[h,c,d]};var D=[],E;for(E=0;288>E;E++)switch(!0){case 143>=E:D.push([E+48,8]);break;case 255>=E:D.push([E-144+400,9]);break;case 279>=E:D.push([E-256+0,7]);break;case 287>=E:D.push([E-280+192,8]);break;default:m("invalid literal: "+E)}
var ca=function(){function a(a){switch(!0){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,
a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:m("invalid length: "+a)}}var b=[],c,d;for(c=3;258>=c;c++)d=a(c),b[c]=d[2]<<24|d[1]<<
16|d[0];return b}();w&&new Uint32Array(ca);function F(a,b){this.l=[];this.m=32768;this.d=this.f=this.c=this.t=0;this.input=w?new Uint8Array(a):a;this.u=!1;this.n=G;this.L=!1;if(b||!(b={}))b.index&&(this.c=b.index),b.bufferSize&&(this.m=b.bufferSize),b.bufferType&&(this.n=b.bufferType),b.resize&&(this.L=b.resize);switch(this.n){case H:this.a=32768;this.b=new (w?Uint8Array:Array)(32768+this.m+258);break;case G:this.a=0;this.b=new (w?Uint8Array:Array)(this.m);this.e=this.X;this.B=this.S;this.q=this.W;break;default:m(Error("invalid inflate mode"))}}
var H=0,G=1;
F.prototype.r=function(){for(;!this.u;){var a=I(this,3);a&1&&(this.u=!0);a>>>=1;switch(a){case 0:var b=this.input,c=this.c,d=this.b,f=this.a,h=b.length,k=q,e=q,g=d.length,l=q;this.d=this.f=0;c+1>=h&&m(Error("invalid uncompressed block header: LEN"));k=b[c++]|b[c++]<<8;c+1>=h&&m(Error("invalid uncompressed block header: NLEN"));e=b[c++]|b[c++]<<8;k===~e&&m(Error("invalid uncompressed block header: length verify"));c+k>b.length&&m(Error("input buffer is broken"));switch(this.n){case H:for(;f+k>d.length;){l=
g-f;k-=l;if(w)d.set(b.subarray(c,c+l),f),f+=l,c+=l;else for(;l--;)d[f++]=b[c++];this.a=f;d=this.e();f=this.a}break;case G:for(;f+k>d.length;)d=this.e({H:2});break;default:m(Error("invalid inflate mode"))}if(w)d.set(b.subarray(c,c+k),f),f+=k,c+=k;else for(;k--;)d[f++]=b[c++];this.c=c;this.a=f;this.b=d;break;case 1:this.q(da,ea);break;case 2:fa(this);break;default:m(Error("unknown BTYPE: "+a))}}return this.B()};
var J=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],K=w?new Uint16Array(J):J,L=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],M=w?new Uint16Array(L):L,ga=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],O=w?new Uint8Array(ga):ga,ha=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ia=w?new Uint16Array(ha):ha,ja=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,
12,12,13,13],P=w?new Uint8Array(ja):ja,Q=new (w?Uint8Array:Array)(288),R,la;R=0;for(la=Q.length;R<la;++R)Q[R]=143>=R?8:255>=R?9:279>=R?7:8;var da=C(Q),S=new (w?Uint8Array:Array)(30),T,ma;T=0;for(ma=S.length;T<ma;++T)S[T]=5;var ea=C(S);function I(a,b){for(var c=a.f,d=a.d,f=a.input,h=a.c,k=f.length,e;d<b;)h>=k&&m(Error("input buffer is broken")),c|=f[h++]<<d,d+=8;e=c&(1<<b)-1;a.f=c>>>b;a.d=d-b;a.c=h;return e}
function U(a,b){for(var c=a.f,d=a.d,f=a.input,h=a.c,k=f.length,e=b[0],g=b[1],l,p;d<g&&!(h>=k);)c|=f[h++]<<d,d+=8;l=e[c&(1<<g)-1];p=l>>>16;a.f=c>>p;a.d=d-p;a.c=h;return l&65535}
function fa(a){function b(a,b,c){var d,e=this.K,f,g;for(g=0;g<a;)switch(d=U(this,b),d){case 16:for(f=3+I(this,2);f--;)c[g++]=e;break;case 17:for(f=3+I(this,3);f--;)c[g++]=0;e=0;break;case 18:for(f=11+I(this,7);f--;)c[g++]=0;e=0;break;default:e=c[g++]=d}this.K=e;return c}var c=I(a,5)+257,d=I(a,5)+1,f=I(a,4)+4,h=new (w?Uint8Array:Array)(K.length),k,e,g,l;for(l=0;l<f;++l)h[K[l]]=I(a,3);if(!w){l=f;for(f=h.length;l<f;++l)h[K[l]]=0}k=C(h);e=new (w?Uint8Array:Array)(c);g=new (w?Uint8Array:Array)(d);a.K=
0;a.q(C(b.call(a,c,k,e)),C(b.call(a,d,k,g)))}u=F.prototype;u.q=function(a,b){var c=this.b,d=this.a;this.C=a;for(var f=c.length-258,h,k,e,g;256!==(h=U(this,a));)if(256>h)d>=f&&(this.a=d,c=this.e(),d=this.a),c[d++]=h;else{k=h-257;g=M[k];0<O[k]&&(g+=I(this,O[k]));h=U(this,b);e=ia[h];0<P[h]&&(e+=I(this,P[h]));d>=f&&(this.a=d,c=this.e(),d=this.a);for(;g--;)c[d]=c[d++-e]}for(;8<=this.d;)this.d-=8,this.c--;this.a=d};
u.W=function(a,b){var c=this.b,d=this.a;this.C=a;for(var f=c.length,h,k,e,g;256!==(h=U(this,a));)if(256>h)d>=f&&(c=this.e(),f=c.length),c[d++]=h;else{k=h-257;g=M[k];0<O[k]&&(g+=I(this,O[k]));h=U(this,b);e=ia[h];0<P[h]&&(e+=I(this,P[h]));d+g>f&&(c=this.e(),f=c.length);for(;g--;)c[d]=c[d++-e]}for(;8<=this.d;)this.d-=8,this.c--;this.a=d};
u.e=function(){var a=new (w?Uint8Array:Array)(this.a-32768),b=this.a-32768,c,d,f=this.b;if(w)a.set(f.subarray(32768,a.length));else{c=0;for(d=a.length;c<d;++c)a[c]=f[c+32768]}this.l.push(a);this.t+=a.length;if(w)f.set(f.subarray(b,b+32768));else for(c=0;32768>c;++c)f[c]=f[b+c];this.a=32768;return f};
u.X=function(a){var b,c=this.input.length/this.c+1|0,d,f,h,k=this.input,e=this.b;a&&("number"===typeof a.H&&(c=a.H),"number"===typeof a.Q&&(c+=a.Q));2>c?(d=(k.length-this.c)/this.C[2],h=258*(d/2)|0,f=h<e.length?e.length+h:e.length<<1):f=e.length*c;w?(b=new Uint8Array(f),b.set(e)):b=e;return this.b=b};
u.B=function(){var a=0,b=this.b,c=this.l,d,f=new (w?Uint8Array:Array)(this.t+(this.a-32768)),h,k,e,g;if(0===c.length)return w?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);h=0;for(k=c.length;h<k;++h){d=c[h];e=0;for(g=d.length;e<g;++e)f[a++]=d[e]}h=32768;for(k=this.a;h<k;++h)f[a++]=b[h];this.l=[];return this.buffer=f};
u.S=function(){var a,b=this.a;w?this.L?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b);return this.buffer=a};function V(a){a=a||{};this.files=[];this.v=a.comment}V.prototype.M=function(a){this.j=a};V.prototype.s=function(a){var b=a[2]&65535|2;return b*(b^1)>>8&255};V.prototype.k=function(a,b){a[0]=(B[(a[0]^b)&255]^a[0]>>>8)>>>0;a[1]=(6681*(20173*(a[1]+(a[0]&255))>>>0)>>>0)+1>>>0;a[2]=(B[(a[2]^a[1]>>>24)&255]^a[2]>>>8)>>>0};V.prototype.U=function(a){var b=[305419896,591751049,878082192],c,d;w&&(b=new Uint32Array(b));c=0;for(d=a.length;c<d;++c)this.k(b,a[c]&255);return b};function W(a,b){b=b||{};this.input=w&&a instanceof Array?new Uint8Array(a):a;this.c=0;this.ca=b.verify||!1;this.j=b.password}var na={P:0,N:8},X=[80,75,1,2],Y=[80,75,3,4],Z=[80,75,5,6];function oa(a,b){this.input=a;this.offset=b}
oa.prototype.parse=function(){var a=this.input,b=this.offset;(a[b++]!==X[0]||a[b++]!==X[1]||a[b++]!==X[2]||a[b++]!==X[3])&&m(Error("invalid file header signature"));this.version=a[b++];this.ja=a[b++];this.$=a[b++]|a[b++]<<8;this.I=a[b++]|a[b++]<<8;this.A=a[b++]|a[b++]<<8;this.time=a[b++]|a[b++]<<8;this.V=a[b++]|a[b++]<<8;this.p=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.z=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.J=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.h=a[b++]|a[b++]<<
8;this.g=a[b++]|a[b++]<<8;this.F=a[b++]|a[b++]<<8;this.fa=a[b++]|a[b++]<<8;this.ha=a[b++]|a[b++]<<8;this.ga=a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24;this.aa=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.filename=String.fromCharCode.apply(null,w?a.subarray(b,b+=this.h):a.slice(b,b+=this.h));this.Y=w?a.subarray(b,b+=this.g):a.slice(b,b+=this.g);this.v=w?a.subarray(b,b+this.F):a.slice(b,b+this.F);this.length=b-this.offset};function pa(a,b){this.input=a;this.offset=b}var qa={O:1,da:8,ea:2048};
pa.prototype.parse=function(){var a=this.input,b=this.offset;(a[b++]!==Y[0]||a[b++]!==Y[1]||a[b++]!==Y[2]||a[b++]!==Y[3])&&m(Error("invalid local file header signature"));this.$=a[b++]|a[b++]<<8;this.I=a[b++]|a[b++]<<8;this.A=a[b++]|a[b++]<<8;this.time=a[b++]|a[b++]<<8;this.V=a[b++]|a[b++]<<8;this.p=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.z=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.J=(a[b++]|a[b++]<<8|a[b++]<<16|a[b++]<<24)>>>0;this.h=a[b++]|a[b++]<<8;this.g=a[b++]|a[b++]<<8;this.filename=
String.fromCharCode.apply(null,w?a.subarray(b,b+=this.h):a.slice(b,b+=this.h));this.Y=w?a.subarray(b,b+=this.g):a.slice(b,b+=this.g);this.length=b-this.offset};
function $(a){var b=[],c={},d,f,h,k;if(!a.i){if(a.o===q){var e=a.input,g;if(!a.D)a:{var l=a.input,p;for(p=l.length-12;0<p;--p)if(l[p]===Z[0]&&l[p+1]===Z[1]&&l[p+2]===Z[2]&&l[p+3]===Z[3]){a.D=p;break a}m(Error("End of Central Directory Record not found"))}g=a.D;(e[g++]!==Z[0]||e[g++]!==Z[1]||e[g++]!==Z[2]||e[g++]!==Z[3])&&m(Error("invalid signature"));a.ia=e[g++]|e[g++]<<8;a.ka=e[g++]|e[g++]<<8;a.la=e[g++]|e[g++]<<8;a.ba=e[g++]|e[g++]<<8;a.R=(e[g++]|e[g++]<<8|e[g++]<<16|e[g++]<<24)>>>0;a.o=(e[g++]|
e[g++]<<8|e[g++]<<16|e[g++]<<24)>>>0;a.w=e[g++]|e[g++]<<8;a.v=w?e.subarray(g,g+a.w):e.slice(g,g+a.w)}d=a.o;h=0;for(k=a.ba;h<k;++h)f=new oa(a.input,d),f.parse(),d+=f.length,b[h]=f,c[f.filename]=h;a.R<d-a.o&&m(Error("invalid file header size"));a.i=b;a.G=c}}u=W.prototype;u.Z=function(){var a=[],b,c,d;this.i||$(this);d=this.i;b=0;for(c=d.length;b<c;++b)a[b]=d[b].filename;return a};
u.r=function(a,b){var c;this.G||$(this);c=this.G[a];c===q&&m(Error(a+" not found"));var d;d=b||{};var f=this.input,h=this.i,k,e,g,l,p,s,r,A;h||$(this);h[c]===q&&m(Error("wrong index"));e=h[c].aa;k=new pa(this.input,e);k.parse();e+=k.length;g=k.z;if(0!==(k.I&qa.O)){!d.password&&!this.j&&m(Error("please set password"));s=this.T(d.password||this.j);r=e;for(A=e+12;r<A;++r)ra(this,s,f[r]);e+=12;g-=12;r=e;for(A=e+g;r<A;++r)f[r]=ra(this,s,f[r])}switch(k.A){case na.P:l=w?this.input.subarray(e,e+g):this.input.slice(e,
e+g);break;case na.N:l=(new F(this.input,{index:e,bufferSize:k.J})).r();break;default:m(Error("unknown compression type"))}if(this.ca){var t=q,n,N="number"===typeof t?t:t=0,ka=l.length;n=-1;for(N=ka&7;N--;++t)n=n>>>8^B[(n^l[t])&255];for(N=ka>>3;N--;t+=8)n=n>>>8^B[(n^l[t])&255],n=n>>>8^B[(n^l[t+1])&255],n=n>>>8^B[(n^l[t+2])&255],n=n>>>8^B[(n^l[t+3])&255],n=n>>>8^B[(n^l[t+4])&255],n=n>>>8^B[(n^l[t+5])&255],n=n>>>8^B[(n^l[t+6])&255],n=n>>>8^B[(n^l[t+7])&255];p=(n^4294967295)>>>0;k.p!==p&&m(Error("wrong crc: file=0x"+
k.p.toString(16)+", data=0x"+p.toString(16)))}return l};u.M=function(a){this.j=a};function ra(a,b,c){c^=a.s(b);a.k(b,c);return c}u.k=V.prototype.k;u.T=V.prototype.U;u.s=V.prototype.s;v("Zlib.Unzip",W);v("Zlib.Unzip.prototype.decompress",W.prototype.r);v("Zlib.Unzip.prototype.getFilenames",W.prototype.Z);v("Zlib.Unzip.prototype.setPassword",W.prototype.M);}).call(ZlibNamespace);
module.exports = ZlibNamespace.Zlib;

View File

@ -25,24 +25,28 @@
"url": "https://github.com/js-platform/filer.git" "url": "https://github.com/js-platform/filer.git"
}, },
"dependencies": { "dependencies": {
"bower": "~1.0.0" "bower": "~1.0.0",
"request": "^2.36.0"
}, },
"devDependencies": { "devDependencies": {
"chai": "~1.9.1",
"grunt": "~0.4.0", "grunt": "~0.4.0",
"grunt-browserify": "^2.1.0",
"grunt-bump": "0.0.13", "grunt-bump": "0.0.13",
"grunt-contrib-clean": "~0.4.0", "grunt-contrib-clean": "~0.4.0",
"grunt-contrib-compress": "~0.4.1", "grunt-contrib-compress": "~0.4.1",
"grunt-contrib-concat": "~0.1.3", "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-jshint": "~0.7.1",
"grunt-contrib-requirejs": "~0.4.0",
"grunt-contrib-uglify": "~0.1.2", "grunt-contrib-uglify": "~0.1.2",
"grunt-contrib-watch": "~0.3.1", "grunt-contrib-watch": "~0.3.1",
"grunt-git": "0.2.10", "grunt-git": "0.2.10",
"grunt-mocha": "0.4.10",
"grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck", "grunt-npm": "git://github.com/sedge/grunt-npm.git#branchcheck",
"grunt-prompt": "^1.1.0", "grunt-prompt": "^1.1.0",
"grunt-shell": "~0.7.0",
"habitat": "^1.1.0", "habitat": "^1.1.0",
"mocha": "~1.18.2",
"semver": "^2.3.0" "semver": "^2.3.0"
} },
"main": "./src/index.js"
} }

View File

@ -1,8 +0,0 @@
define(function(require) {
return {
Compression: require('src/adapters/zlib'),
Encryption: require('src/adapters/crypto')
};
});

View File

@ -1,124 +0,0 @@
define(function(require) {
// AES encryption, see http://code.google.com/p/crypto-js/#AES
require("crypto-js/rollups/aes");
// Move back and forth from Uint8Arrays and CryptoJS WordArray
// See http://code.google.com/p/crypto-js/#The_Cipher_Input and
// https://groups.google.com/forum/#!topic/crypto-js/TOb92tcJlU0
var WordArray = CryptoJS.lib.WordArray;
function fromWordArray(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var u8 = new Uint8Array(sigBytes);
var b;
for (var i = 0; i < sigBytes; i++) {
b = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
u8[i] = b;
}
return u8;
}
function toWordArray(u8arr) {
var len = u8arr.length;
var words = [];
for (var i = 0; i < len; i++) {
words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
}
return WordArray.create(words, len);
}
// UTF8 Text De/Encoders
require('encoding');
function encode(str) {
return (new TextEncoder('utf-8')).encode(str);
}
function decode(u8arr) {
return (new TextDecoder('utf-8')).decode(u8arr);
}
function CryptoContext(context, encrypt, decrypt) {
this.context = context;
this.encrypt = encrypt;
this.decrypt = decrypt;
}
CryptoContext.prototype.clear = function(callback) {
this.context.clear(callback);
};
CryptoContext.prototype.get = function(key, callback) {
var decrypt = this.decrypt;
this.context.get(key, function(err, value) {
if(err) {
callback(err);
return;
}
if(value) {
value = decrypt(value);
}
callback(null, value);
});
};
CryptoContext.prototype.put = function(key, value, callback) {
var encryptedValue = this.encrypt(value);
this.context.put(key, encryptedValue, callback);
};
CryptoContext.prototype.delete = function(key, callback) {
this.context.delete(key, callback);
};
// It is up to the app using this wrapper how the passphrase is acquired, probably by
// prompting the user to enter it when the file system is being opened.
function CryptoAdapter(passphrase, provider) {
this.provider = provider;
// Cache cipher algorithm we'll use in encrypt/decrypt
var cipher = CryptoJS.AES;
// To encrypt:
// 1) accept a buffer (Uint8Array) containing binary data
// 2) convert the buffer to a CipherJS WordArray
// 3) encrypt the WordArray using the chosen cipher algorithm + passphrase
// 4) convert the resulting ciphertext to a UTF8 encoded Uint8Array and return
this.encrypt = function(buffer) {
var wordArray = toWordArray(buffer);
var encrypted = cipher.encrypt(wordArray, passphrase);
var utf8EncodedBuf = encode(encrypted);
return utf8EncodedBuf;
};
// To decrypt:
// 1) accept a buffer (Uint8Array) containing a UTF8 encoded Uint8Array
// 2) convert the buffer to string (i.e., the ciphertext we got from encrypting)
// 3) decrypt the ciphertext string
// 4) convert the decrypted cipherParam object to a UTF8 string
// 5) encode the UTF8 string to a Uint8Array buffer and return
this.decrypt = function(buffer) {
var encryptedStr = decode(buffer);
var decrypted = cipher.decrypt(encryptedStr, passphrase);
var decryptedUtf8 = decrypted.toString(CryptoJS.enc.Utf8);
var utf8EncodedBuf = encode(decryptedUtf8);
return utf8EncodedBuf;
};
}
CryptoAdapter.isSupported = function() {
return true;
};
CryptoAdapter.prototype.open = function(callback) {
this.provider.open(callback);
};
CryptoAdapter.prototype.getReadOnlyContext = function() {
return new CryptoContext(this.provider.getReadOnlyContext(),
this.encrypt,
this.decrypt);
};
CryptoAdapter.prototype.getReadWriteContext = function() {
return new CryptoContext(this.provider.getReadWriteContext(),
this.encrypt,
this.decrypt);
};
return CryptoAdapter;
});

View File

@ -1,63 +0,0 @@
define(function(require) {
// Zlib compression, see
// https://github.com/imaya/zlib.js/blob/master/bin/zlib.min.js
require("zlib");
var Inflate = Zlib.Inflate;
function inflate(compressed) {
return (new Inflate(compressed)).decompress();
}
var Deflate = Zlib.Deflate;
function deflate(buffer) {
return (new Deflate(buffer)).compress();
}
function ZlibContext(context) {
this.context = context;
}
ZlibContext.prototype.clear = function(callback) {
this.context.clear(callback);
};
ZlibContext.prototype.get = function(key, callback) {
this.context.get(key, function(err, result) {
if(err) {
callback(err);
return;
}
// Deal with result being null
if(result) {
result = inflate(result);
}
callback(null, result);
});
};
ZlibContext.prototype.put = function(key, value, callback) {
value = deflate(value);
this.context.put(key, value, callback);
};
ZlibContext.prototype.delete = function(key, callback) {
this.context.delete(key, callback);
};
function ZlibAdapter(provider, inflate, deflate) {
this.provider = provider;
}
ZlibAdapter.isSupported = function() {
return true;
};
ZlibAdapter.prototype.open = function(callback) {
this.provider.open(callback);
};
ZlibAdapter.prototype.getReadOnlyContext = function() {
return new ZlibContext(this.provider.getReadOnlyContext());
};
ZlibAdapter.prototype.getReadWriteContext = function() {
return new ZlibContext(this.provider.getReadWriteContext());
};
return ZlibAdapter;
});

View File

@ -1,15 +1,13 @@
define(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';
var O_READ = 'READ'; module.exports = {
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_SYSTEM_NAME: 'local',
FILE_STORE_NAME: 'files', FILE_STORE_NAME: 'files',
@ -78,6 +76,4 @@ define(function(require) {
TMP: '/tmp', TMP: '/tmp',
PATH: '' PATH: ''
} }
}; };
});

View File

@ -1,8 +1,6 @@
define(['src/constants'], function(Constants) { var MODE_FILE = require('./constants.js').MODE_FILE;
return function DirectoryEntry(id, type) { module.exports = function DirectoryEntry(id, type) {
this.id = id; this.id = id;
this.type = type || Constants.MODE_FILE; this.type = type || MODE_FILE;
}; };
});

View File

@ -1,6 +1,5 @@
define(function(require) { var errors = {};
var errors = {}; [
[
/** /**
* node.js errors * node.js errors
*/ */
@ -72,7 +71,7 @@ define(function(require) {
'1000:ENOTMOUNTED:not mounted', '1000:ENOTMOUNTED:not mounted',
'1001:EFILESYSTEMERROR:missing super node, use \'FORMAT\' flag to format filesystem.', '1001:EFILESYSTEMERROR:missing super node, use \'FORMAT\' flag to format filesystem.',
'1002:ENOATTR:attribute does not exist' '1002:ENOATTR:attribute does not exist'
].forEach(function(e) { ].forEach(function(e) {
e = e.split(':'); e = e.split(':');
var errno = e[0], var errno = e[0],
err = e[1], err = e[1],
@ -88,7 +87,6 @@ define(function(require) {
// We expose the error as both Errors.EINVAL and Errors[18] // We expose the error as both Errors.EINVAL and Errors[18]
errors[err] = errors[errno] = ctor; errors[err] = errors[errno] = ctor;
});
return errors;
}); });
module.exports = errors;

View File

@ -1,47 +1,46 @@
define(function(require) { var _ = require('../../lib/nodash.js');
// TextEncoder and TextDecoder will either already be present, or use this shim. var TextDecoder = require('../../lib/encoding.js').TextDecoder;
// Because of the way the spec is defined, we need to get them off the global. var TextEncoder = require('../../lib/encoding.js').TextEncoder;
require('encoding');
var _ = require('nodash'); var Path = require('../path.js');
var normalize = Path.normalize;
var dirname = Path.dirname;
var basename = Path.basename;
var isAbsolutePath = Path.isAbsolute;
var isNullPath = Path.isNull;
var normalize = require('src/path').normalize; var Constants = require('../constants.js');
var dirname = require('src/path').dirname; var MODE_FILE = Constants.MODE_FILE;
var basename = require('src/path').basename; var MODE_DIRECTORY = Constants.MODE_DIRECTORY;
var isAbsolutePath = require('src/path').isAbsolute; var MODE_SYMBOLIC_LINK = Constants.MODE_SYMBOLIC_LINK;
var isNullPath = require('src/path').isNull; var MODE_META = Constants.MODE_META;
var MODE_FILE = require('src/constants').MODE_FILE; var ROOT_DIRECTORY_NAME = Constants.ROOT_DIRECTORY_NAME;
var MODE_DIRECTORY = require('src/constants').MODE_DIRECTORY; var SUPER_NODE_ID = Constants.SUPER_NODE_ID;
var MODE_SYMBOLIC_LINK = require('src/constants').MODE_SYMBOLIC_LINK; var SYMLOOP_MAX = Constants.SYMLOOP_MAX;
var MODE_META = require('src/constants').MODE_META;
var ROOT_DIRECTORY_NAME = require('src/constants').ROOT_DIRECTORY_NAME; var O_READ = Constants.O_READ;
var SUPER_NODE_ID = require('src/constants').SUPER_NODE_ID; var O_WRITE = Constants.O_WRITE;
var SYMLOOP_MAX = require('src/constants').SYMLOOP_MAX; var O_CREATE = Constants.O_CREATE;
var O_EXCLUSIVE = Constants.O_EXCLUSIVE;
var O_TRUNCATE = Constants.O_TRUNCATE;
var O_APPEND = Constants.O_APPEND;
var O_FLAGS = Constants.O_FLAGS;
var O_READ = require('src/constants').O_READ; var XATTR_CREATE = Constants.XATTR_CREATE;
var O_WRITE = require('src/constants').O_WRITE; var XATTR_REPLACE = Constants.XATTR_REPLACE;
var O_CREATE = require('src/constants').O_CREATE; var FS_NOMTIME = Constants.FS_NOMTIME;
var O_EXCLUSIVE = require('src/constants').O_EXCLUSIVE; var FS_NOCTIME = Constants.FS_NOCTIME;
var O_TRUNCATE = require('src/constants').O_TRUNCATE;
var O_APPEND = require('src/constants').O_APPEND;
var O_FLAGS = require('src/constants').O_FLAGS;
var XATTR_CREATE = require('src/constants').XATTR_CREATE; var Errors = require('../errors.js');
var XATTR_REPLACE = require('src/constants').XATTR_REPLACE; var DirectoryEntry = require('../directory-entry.js');
var FS_NOMTIME = require('src/constants').FS_NOMTIME; var OpenFileDescription = require('../open-file-description.js');
var FS_NOCTIME = require('src/constants').FS_NOCTIME; var SuperNode = require('../super-node.js');
var Node = require('../node.js');
var Stats = require('../stats.js');
var Errors = require('src/errors'); /**
var DirectoryEntry = require('src/directory-entry');
var OpenFileDescription = require('src/open-file-description');
var SuperNode = require('src/super-node');
var Node = require('src/node');
var Stats = require('src/stats');
/**
* Many functions below use this callback pattern. If it's not * Many functions below use this callback pattern. If it's not
* re-defined, we use this to generate a callback. NOTE: this * re-defined, we use this to generate a callback. NOTE: this
* can be use for callbacks of both forms without problem (i.e., * can be use for callbacks of both forms without problem (i.e.,
@ -49,7 +48,7 @@ define(function(require) {
* - callback(error) * - callback(error)
* - callback(error, result) * - callback(error, result)
*/ */
function standard_check_result_cb(callback) { function standard_check_result_cb(callback) {
return function(error, result) { return function(error, result) {
if(error) { if(error) {
callback(error); callback(error);
@ -57,13 +56,13 @@ define(function(require) {
callback(null, result); callback(null, result);
} }
}; };
} }
/* /**
* Update node times. Only passed times are modified (undefined times are ignored) * Update node times. Only passed times are modified (undefined times are ignored)
* and filesystem flags are examined in order to override update logic. * and filesystem flags are examined in order to override update logic.
*/ */
function update_node_times(context, path, node, times, callback) { function update_node_times(context, path, node, times, callback) {
// Honour mount flags for how we update times // Honour mount flags for how we update times
var flags = context.flags; var flags = context.flags;
if(_(flags).contains(FS_NOCTIME)) { if(_(flags).contains(FS_NOCTIME)) {
@ -104,14 +103,14 @@ define(function(require) {
} else { } else {
complete(); complete();
} }
} }
/* /**
* make_node() * make_node()
*/ */
// in: file or directory path // in: file or directory path
// out: new node representing file/directory // out: new node representing file/directory
function make_node(context, path, mode, callback) { function make_node(context, path, mode, callback) {
if(mode !== MODE_DIRECTORY && mode !== MODE_FILE) { if(mode !== MODE_DIRECTORY && mode !== MODE_FILE) {
return callback(new Errors.EINVAL('mode must be a directory or file')); return callback(new Errors.EINVAL('mode must be a directory or file'));
} }
@ -181,15 +180,14 @@ define(function(require) {
// Find the parent node // Find the parent node
find_node(context, parentPath, create_node_in_parent); find_node(context, parentPath, create_node_in_parent);
} }
/* /**
* find_node * find_node
*/ */
// in: file or directory path
// in: file or directory path // out: node structure, or error
// out: node structure, or error function find_node(context, path, callback) {
function find_node(context, path, callback) {
path = normalize(path); path = normalize(path);
if(!path) { if(!path) {
return callback(new Errors.ENOENT('path is an empty string')); return callback(new Errors.ENOENT('path is an empty string'));
@ -278,14 +276,13 @@ define(function(require) {
} else { } else {
find_node(context, parentPath, read_parent_directory_data); find_node(context, parentPath, read_parent_directory_data);
} }
} }
/* /**
* set extended attribute (refactor) * set extended attribute (refactor)
*/ */
function set_extended_attribute (context, path_or_fd, name, value, flag, callback) {
function set_extended_attribute (context, path_or_fd, name, value, flag, callback) {
var path; var path;
function set_xattr (error, node) { function set_xattr (error, node) {
@ -325,14 +322,13 @@ define(function(require) {
else { else {
callback(new Errors.EINVAL('path or file descriptor of wrong type')); callback(new Errors.EINVAL('path or file descriptor of wrong type'));
} }
} }
/* /**
* make_root_directory * make_root_directory
*/ */
// Note: this should only be invoked when formatting a new file system
// Note: this should only be invoked when formatting a new file system function make_root_directory(context, callback) {
function make_root_directory(context, callback) {
var superNode; var superNode;
var directoryNode; var directoryNode;
var directoryData; var directoryData;
@ -368,13 +364,12 @@ define(function(require) {
} }
context.get(SUPER_NODE_ID, write_super_node); context.get(SUPER_NODE_ID, write_super_node);
} }
/* /**
* make_directory * make_directory
*/ */
function make_directory(context, path, callback) {
function make_directory(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -442,13 +437,12 @@ define(function(require) {
} }
find_node(context, path, check_if_directory_exists); find_node(context, path, check_if_directory_exists);
} }
/* /**
* remove_directory * remove_directory
*/ */
function remove_directory(context, path, callback) {
function remove_directory(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -536,9 +530,9 @@ define(function(require) {
} }
find_node(context, parentPath, read_parent_directory_data); find_node(context, parentPath, read_parent_directory_data);
} }
function open_file(context, path, flags, callback) { function open_file(context, path, flags, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -677,9 +671,9 @@ define(function(require) {
callback(null, fileNode); callback(null, fileNode);
} }
} }
} }
function replace_data(context, ofd, buffer, offset, length, callback) { function replace_data(context, ofd, buffer, offset, length, callback) {
var fileNode; var fileNode;
function return_nbytes(error) { function return_nbytes(error) {
@ -725,9 +719,9 @@ define(function(require) {
} }
context.get(ofd.id, write_file_data); context.get(ofd.id, write_file_data);
} }
function write_data(context, ofd, buffer, offset, length, position, callback) { function write_data(context, ofd, buffer, offset, length, position, callback) {
var fileNode; var fileNode;
var fileData; var fileData;
@ -790,9 +784,9 @@ define(function(require) {
} }
context.get(ofd.id, read_file_data); context.get(ofd.id, read_file_data);
} }
function read_data(context, ofd, buffer, offset, length, position, callback) { function read_data(context, ofd, buffer, offset, length, position, callback) {
var fileNode; var fileNode;
var fileData; var fileData;
@ -822,19 +816,19 @@ define(function(require) {
} }
context.get(ofd.id, read_file_data); context.get(ofd.id, read_file_data);
} }
function stat_file(context, path, callback) { function stat_file(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
find_node(context, path, standard_check_result_cb(callback)); find_node(context, path, standard_check_result_cb(callback));
} }
function fstat_file(context, ofd, callback) { function fstat_file(context, ofd, callback) {
context.get(ofd.id, standard_check_result_cb(callback)); context.get(ofd.id, standard_check_result_cb(callback));
} }
function lstat_file(context, path, callback) { function lstat_file(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -869,9 +863,9 @@ define(function(require) {
} }
} }
} }
} }
function link_node(context, oldpath, newpath, callback) { function link_node(context, oldpath, newpath, callback) {
oldpath = normalize(oldpath); oldpath = normalize(oldpath);
var oldname = basename(oldpath); var oldname = basename(oldpath);
var oldParentPath = dirname(oldpath); var oldParentPath = dirname(oldpath);
@ -958,9 +952,9 @@ define(function(require) {
} }
find_node(context, oldParentPath, read_old_directory_data); find_node(context, oldParentPath, read_old_directory_data);
} }
function unlink_node(context, path, callback) { function unlink_node(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -1028,9 +1022,9 @@ define(function(require) {
} }
find_node(context, parentPath, read_directory_data); find_node(context, parentPath, read_directory_data);
} }
function read_directory(context, path, callback) { function read_directory(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
@ -1057,9 +1051,9 @@ define(function(require) {
} }
find_node(context, path, read_directory_data); find_node(context, path, read_directory_data);
} }
function make_symbolic_link(context, srcpath, dstpath, callback) { function make_symbolic_link(context, srcpath, dstpath, callback) {
dstpath = normalize(dstpath); dstpath = normalize(dstpath);
var name = basename(dstpath); var name = basename(dstpath);
var parentPath = dirname(dstpath); var parentPath = dirname(dstpath);
@ -1121,9 +1115,9 @@ define(function(require) {
context.put(directoryNode.data, directoryData, update_time); context.put(directoryNode.data, directoryData, update_time);
} }
} }
} }
function read_link(context, path, callback) { function read_link(context, path, callback) {
path = normalize(path); path = normalize(path);
var name = basename(path); var name = basename(path);
var parentPath = dirname(path); var parentPath = dirname(path);
@ -1166,9 +1160,9 @@ define(function(require) {
} }
} }
} }
} }
function truncate_file(context, path, length, callback) { function truncate_file(context, path, length, callback) {
path = normalize(path); path = normalize(path);
var fileNode; var fileNode;
@ -1220,9 +1214,9 @@ define(function(require) {
} else { } else {
find_node(context, path, read_file_data); find_node(context, path, read_file_data);
} }
} }
function ftruncate_file(context, ofd, length, callback) { function ftruncate_file(context, ofd, length, callback) {
var fileNode; var fileNode;
function read_file_data (error, node) { function read_file_data (error, node) {
@ -1256,6 +1250,7 @@ define(function(require) {
update_node_times(context, ofd.path, fileNode, { mtime: now, ctime: now }, callback); update_node_times(context, ofd.path, fileNode, { mtime: now, ctime: now }, callback);
} }
} }
function update_file_node (error) { function update_file_node (error) {
if(error) { if(error) {
callback(error); callback(error);
@ -1271,9 +1266,9 @@ define(function(require) {
} else { } else {
context.get(ofd.id, read_file_data); context.get(ofd.id, read_file_data);
} }
} }
function utimes_file(context, path, atime, mtime, callback) { function utimes_file(context, path, atime, mtime, callback) {
path = normalize(path); path = normalize(path);
function update_times(error, node) { function update_times(error, node) {
@ -1293,9 +1288,9 @@ define(function(require) {
else { else {
find_node(context, path, update_times); find_node(context, path, update_times);
} }
} }
function futimes_file(context, ofd, atime, mtime, callback) { function futimes_file(context, ofd, atime, mtime, callback) {
function update_times (error, node) { function update_times (error, node) {
if (error) { if (error) {
@ -1314,9 +1309,9 @@ define(function(require) {
else { else {
context.get(ofd.id, update_times); context.get(ofd.id, update_times);
} }
} }
function setxattr_file(context, path, name, value, flag, callback) { function setxattr_file(context, path, name, value, flag, callback) {
path = normalize(path); path = normalize(path);
if (typeof name != 'string') { if (typeof name != 'string') {
@ -1332,9 +1327,9 @@ define(function(require) {
else { else {
set_extended_attribute(context, path, name, value, flag, callback); set_extended_attribute(context, path, name, value, flag, callback);
} }
} }
function fsetxattr_file (context, ofd, name, value, flag, callback) { function fsetxattr_file (context, ofd, name, value, flag, callback) {
if (typeof name != 'string') { if (typeof name != 'string') {
callback(new Errors.EINVAL('attribute name must be a string')); callback(new Errors.EINVAL('attribute name must be a string'));
} }
@ -1348,9 +1343,9 @@ define(function(require) {
else { else {
set_extended_attribute(context, ofd, name, value, flag, callback); set_extended_attribute(context, ofd, name, value, flag, callback);
} }
} }
function getxattr_file (context, path, name, callback) { function getxattr_file (context, path, name, callback) {
path = normalize(path); path = normalize(path);
function get_xattr(error, node) { function get_xattr(error, node) {
@ -1376,9 +1371,9 @@ define(function(require) {
else { else {
find_node(context, path, get_xattr); find_node(context, path, get_xattr);
} }
} }
function fgetxattr_file (context, ofd, name, callback) { function fgetxattr_file (context, ofd, name, callback) {
function get_xattr (error, node) { function get_xattr (error, node) {
var xattr = (node ? node.xattrs[name] : null); var xattr = (node ? node.xattrs[name] : null);
@ -1403,9 +1398,9 @@ define(function(require) {
else { else {
context.get(ofd.id, get_xattr); context.get(ofd.id, get_xattr);
} }
} }
function removexattr_file (context, path, name, callback) { function removexattr_file (context, path, name, callback) {
path = normalize(path); path = normalize(path);
function remove_xattr (error, node) { function remove_xattr (error, node) {
@ -1440,9 +1435,9 @@ define(function(require) {
else { else {
find_node(context, path, remove_xattr); find_node(context, path, remove_xattr);
} }
} }
function fremovexattr_file (context, ofd, name, callback) { function fremovexattr_file (context, ofd, name, callback) {
function remove_xattr (error, node) { function remove_xattr (error, node) {
function update_time(error) { function update_time(error) {
@ -1474,16 +1469,16 @@ define(function(require) {
else { else {
context.get(ofd.id, remove_xattr); context.get(ofd.id, remove_xattr);
} }
} }
function validate_flags(flags) { function validate_flags(flags) {
if(!_(O_FLAGS).has(flags)) { if(!_(O_FLAGS).has(flags)) {
return null; return null;
} }
return O_FLAGS[flags]; return O_FLAGS[flags];
} }
function validate_file_options(options, enc, fileMode){ function validate_file_options(options, enc, fileMode){
if(!options) { if(!options) {
options = { encoding: enc, flag: fileMode }; options = { encoding: enc, flag: fileMode };
} else if(typeof options === "function") { } else if(typeof options === "function") {
@ -1492,9 +1487,9 @@ define(function(require) {
options = { encoding: options, flag: fileMode }; options = { encoding: options, flag: fileMode };
} }
return options; return options;
} }
function pathCheck(path, callback) { function pathCheck(path, callback) {
var err; var err;
if(isNullPath(path)) { if(isNullPath(path)) {
err = new Error('Path must be a string without null bytes.'); err = new Error('Path must be a string without null bytes.');
@ -1507,10 +1502,10 @@ define(function(require) {
return false; return false;
} }
return true; return true;
} }
function open(fs, context, path, flags, mode, callback) { function open(fs, context, path, flags, mode, callback) {
// NOTE: we support the same signature as node with a `mode` arg, // NOTE: we support the same signature as node with a `mode` arg,
// but ignore it. // but ignore it.
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
@ -1538,35 +1533,35 @@ define(function(require) {
} }
open_file(context, path, flags, check_result); open_file(context, path, flags, check_result);
} }
function close(fs, context, fd, callback) { function close(fs, context, fd, callback) {
if(!_(fs.openFiles).has(fd)) { if(!_(fs.openFiles).has(fd)) {
callback(new Errors.EBADF()); callback(new Errors.EBADF());
} else { } else {
fs.releaseDescriptor(fd); fs.releaseDescriptor(fd);
callback(null); callback(null);
} }
} }
function mknod(fs, context, path, mode, callback) { function mknod(fs, context, path, mode, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
make_node(context, path, mode, callback); make_node(context, path, mode, callback);
} }
function mkdir(fs, context, path, mode, callback) { function mkdir(fs, context, path, mode, callback) {
// NOTE: we support passing a mode arg, but we ignore it internally for now. // NOTE: we support passing a mode arg, but we ignore it internally for now.
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
make_directory(context, path, standard_check_result_cb(callback)); make_directory(context, path, standard_check_result_cb(callback));
} }
function rmdir(fs, context, path, callback) { function rmdir(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
remove_directory(context, path, standard_check_result_cb(callback)); remove_directory(context, path, standard_check_result_cb(callback));
} }
function stat(fs, context, path, callback) { function stat(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
function check_result(error, result) { function check_result(error, result) {
@ -1579,9 +1574,9 @@ define(function(require) {
} }
stat_file(context, path, check_result); stat_file(context, path, check_result);
} }
function fstat(fs, context, fd, callback) { function fstat(fs, context, fd, callback) {
function check_result(error, result) { function check_result(error, result) {
if(error) { if(error) {
callback(error); callback(error);
@ -1597,20 +1592,20 @@ define(function(require) {
} else { } else {
fstat_file(context, ofd, check_result); fstat_file(context, ofd, check_result);
} }
} }
function link(fs, context, oldpath, newpath, callback) { function link(fs, context, oldpath, newpath, callback) {
if(!pathCheck(oldpath, callback)) return; if(!pathCheck(oldpath, callback)) return;
if(!pathCheck(newpath, callback)) return; if(!pathCheck(newpath, callback)) return;
link_node(context, oldpath, newpath, standard_check_result_cb(callback)); link_node(context, oldpath, newpath, standard_check_result_cb(callback));
} }
function unlink(fs, context, path, callback) { function unlink(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
unlink_node(context, path, standard_check_result_cb(callback)); unlink_node(context, path, standard_check_result_cb(callback));
} }
function read(fs, context, fd, buffer, offset, length, position, callback) { function read(fs, context, fd, buffer, offset, length, position, callback) {
// Follow how node.js does this // Follow how node.js does this
function wrapped_cb(err, bytesRead) { function wrapped_cb(err, bytesRead) {
// Retain a reference to buffer so that it can't be GC'ed too soon. // Retain a reference to buffer so that it can't be GC'ed too soon.
@ -1629,9 +1624,9 @@ define(function(require) {
} else { } else {
read_data(context, ofd, buffer, offset, length, position, standard_check_result_cb(wrapped_cb)); read_data(context, ofd, buffer, offset, length, position, standard_check_result_cb(wrapped_cb));
} }
} }
function readFile(fs, context, path, options, callback) { function readFile(fs, context, path, options, callback) {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
options = validate_file_options(options, null, 'r'); options = validate_file_options(options, null, 'r');
@ -1674,9 +1669,9 @@ define(function(require) {
}); });
}); });
}); });
} }
function write(fs, context, fd, buffer, offset, length, position, callback) { function write(fs, context, fd, buffer, offset, length, position, callback) {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
offset = (undefined === offset) ? 0 : offset; offset = (undefined === offset) ? 0 : offset;
length = (undefined === length) ? buffer.length - offset : length; length = (undefined === length) ? buffer.length - offset : length;
@ -1691,9 +1686,9 @@ define(function(require) {
} else { } else {
write_data(context, ofd, buffer, offset, length, position, standard_check_result_cb(callback)); write_data(context, ofd, buffer, offset, length, position, standard_check_result_cb(callback));
} }
} }
function writeFile(fs, context, path, data, options, callback) { function writeFile(fs, context, path, data, options, callback) {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
options = validate_file_options(options, 'utf8', 'w'); options = validate_file_options(options, 'utf8', 'w');
@ -1727,9 +1722,9 @@ define(function(require) {
callback(null); callback(null);
}); });
}); });
} }
function appendFile(fs, context, path, data, options, callback) { function appendFile(fs, context, path, data, options, callback) {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
options = validate_file_options(options, 'utf8', 'a'); options = validate_file_options(options, 'utf8', 'a');
@ -1763,21 +1758,21 @@ define(function(require) {
callback(null); callback(null);
}); });
}); });
} }
function exists(fs, context, path, callback) { function exists(fs, context, path, callback) {
function cb(err, stats) { function cb(err, stats) {
callback(err ? false : true); callback(err ? false : true);
} }
stat(fs, context, path, cb); stat(fs, context, path, cb);
} }
function getxattr(fs, context, path, name, callback) { function getxattr(fs, context, path, name, callback) {
if (!pathCheck(path, callback)) return; if (!pathCheck(path, callback)) return;
getxattr_file(context, path, name, standard_check_result_cb(callback)); getxattr_file(context, path, name, standard_check_result_cb(callback));
} }
function fgetxattr(fs, context, fd, name, callback) { function fgetxattr(fs, context, fd, name, callback) {
var ofd = fs.openFiles[fd]; var ofd = fs.openFiles[fd];
if (!ofd) { if (!ofd) {
callback(new Errors.EBADF()); callback(new Errors.EBADF());
@ -1785,9 +1780,9 @@ define(function(require) {
else { else {
fgetxattr_file(context, ofd, name, standard_check_result_cb(callback)); fgetxattr_file(context, ofd, name, standard_check_result_cb(callback));
} }
} }
function setxattr(fs, context, path, name, value, flag, callback) { function setxattr(fs, context, path, name, value, flag, callback) {
if(typeof flag === 'function') { if(typeof flag === 'function') {
callback = flag; callback = flag;
flag = null; flag = null;
@ -1795,9 +1790,9 @@ define(function(require) {
if (!pathCheck(path, callback)) return; if (!pathCheck(path, callback)) return;
setxattr_file(context, path, name, value, flag, standard_check_result_cb(callback)); setxattr_file(context, path, name, value, flag, standard_check_result_cb(callback));
} }
function fsetxattr(fs, context, fd, name, value, flag, callback) { function fsetxattr(fs, context, fd, name, value, flag, callback) {
if(typeof flag === 'function') { if(typeof flag === 'function') {
callback = flag; callback = flag;
flag = null; flag = null;
@ -1813,14 +1808,14 @@ define(function(require) {
else { else {
fsetxattr_file(context, ofd, name, value, flag, standard_check_result_cb(callback)); fsetxattr_file(context, ofd, name, value, flag, standard_check_result_cb(callback));
} }
} }
function removexattr(fs, context, path, name, callback) { function removexattr(fs, context, path, name, callback) {
if (!pathCheck(path, callback)) return; if (!pathCheck(path, callback)) return;
removexattr_file(context, path, name, standard_check_result_cb(callback)); removexattr_file(context, path, name, standard_check_result_cb(callback));
} }
function fremovexattr(fs, context, fd, name, callback) { function fremovexattr(fs, context, fd, name, callback) {
var ofd = fs.openFiles[fd]; var ofd = fs.openFiles[fd];
if (!ofd) { if (!ofd) {
callback(new Errors.EBADF()); callback(new Errors.EBADF());
@ -1831,9 +1826,9 @@ define(function(require) {
else { else {
fremovexattr_file(context, ofd, name, standard_check_result_cb(callback)); fremovexattr_file(context, ofd, name, standard_check_result_cb(callback));
} }
} }
function lseek(fs, context, fd, offset, whence, callback) { function lseek(fs, context, fd, offset, whence, callback) {
function update_descriptor_position(error, stats) { function update_descriptor_position(error, stats) {
if(error) { if(error) {
callback(error); callback(error);
@ -1871,14 +1866,14 @@ define(function(require) {
} else { } else {
callback(new Errors.EINVAL('whence argument is not a proper value')); callback(new Errors.EINVAL('whence argument is not a proper value'));
} }
} }
function readdir(fs, context, path, callback) { function readdir(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
read_directory(context, path, standard_check_result_cb(callback)); read_directory(context, path, standard_check_result_cb(callback));
} }
function utimes(fs, context, path, atime, mtime, callback) { function utimes(fs, context, path, atime, mtime, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
var currentTime = Date.now(); var currentTime = Date.now();
@ -1886,9 +1881,9 @@ define(function(require) {
mtime = (mtime) ? mtime : currentTime; mtime = (mtime) ? mtime : currentTime;
utimes_file(context, path, atime, mtime, standard_check_result_cb(callback)); utimes_file(context, path, atime, mtime, standard_check_result_cb(callback));
} }
function futimes(fs, context, fd, atime, mtime, callback) { function futimes(fs, context, fd, atime, mtime, callback) {
var currentTime = Date.now(); var currentTime = Date.now();
atime = (atime) ? atime : currentTime; atime = (atime) ? atime : currentTime;
mtime = (mtime) ? mtime : currentTime; mtime = (mtime) ? mtime : currentTime;
@ -1901,9 +1896,9 @@ define(function(require) {
} else { } else {
futimes_file(context, ofd, atime, mtime, standard_check_result_cb(callback)); futimes_file(context, ofd, atime, mtime, standard_check_result_cb(callback));
} }
} }
function rename(fs, context, oldpath, newpath, callback) { function rename(fs, context, oldpath, newpath, callback) {
if(!pathCheck(oldpath, callback)) return; if(!pathCheck(oldpath, callback)) return;
if(!pathCheck(newpath, callback)) return; if(!pathCheck(newpath, callback)) return;
@ -1916,22 +1911,22 @@ define(function(require) {
} }
link_node(context, oldpath, newpath, unlink_old_node); link_node(context, oldpath, newpath, unlink_old_node);
} }
function symlink(fs, context, srcpath, dstpath, type, callback) { function symlink(fs, context, srcpath, dstpath, type, callback) {
// NOTE: we support passing the `type` arg, but ignore it. // NOTE: we support passing the `type` arg, but ignore it.
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
if(!pathCheck(srcpath, callback)) return; if(!pathCheck(srcpath, callback)) return;
if(!pathCheck(dstpath, callback)) return; if(!pathCheck(dstpath, callback)) return;
make_symbolic_link(context, srcpath, dstpath, standard_check_result_cb(callback)); make_symbolic_link(context, srcpath, dstpath, standard_check_result_cb(callback));
} }
function readlink(fs, context, path, callback) { function readlink(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
read_link(context, path, standard_check_result_cb(callback)); read_link(context, path, standard_check_result_cb(callback));
} }
function lstat(fs, context, path, callback) { function lstat(fs, context, path, callback) {
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
function check_result(error, result) { function check_result(error, result) {
@ -1944,18 +1939,18 @@ define(function(require) {
} }
lstat_file(context, path, check_result); lstat_file(context, path, check_result);
} }
function truncate(fs, context, path, length, callback) { function truncate(fs, context, path, length, callback) {
// NOTE: length is optional // NOTE: length is optional
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
length = length || 0; length = length || 0;
if(!pathCheck(path, callback)) return; if(!pathCheck(path, callback)) return;
truncate_file(context, path, length, standard_check_result_cb(callback)); truncate_file(context, path, length, standard_check_result_cb(callback));
} }
function ftruncate(fs, context, fd, length, callback) { function ftruncate(fs, context, fd, length, callback) {
// NOTE: length is optional // NOTE: length is optional
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
length = length || 0; length = length || 0;
@ -1968,9 +1963,9 @@ define(function(require) {
} else { } else {
ftruncate_file(context, ofd, length, standard_check_result_cb(callback)); ftruncate_file(context, ofd, length, standard_check_result_cb(callback));
} }
} }
return { module.exports = {
makeRootDirectory: make_root_directory, makeRootDirectory: make_root_directory,
open: open, open: open,
close: close, close: close,
@ -2003,6 +1998,4 @@ define(function(require) {
lstat: lstat, lstat: lstat,
truncate: truncate, truncate: truncate,
ftruncate: ftruncate ftruncate: ftruncate
}; };
});

View File

@ -1,34 +1,32 @@
define(function(require) { var _ = require('../../lib/nodash.js');
var _ = require('nodash'); var isNullPath = require('../path.js').isNull;
var nop = require('../shared.js').nop;
var isNullPath = require('src/path').isNull; var Constants = require('../constants.js');
var nop = require('src/shared').nop; var FILE_SYSTEM_NAME = Constants.FILE_SYSTEM_NAME;
var FS_FORMAT = Constants.FS_FORMAT;
var FS_READY = Constants.FS_READY;
var FS_PENDING = Constants.FS_PENDING;
var FS_ERROR = Constants.FS_ERROR;
var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; var providers = require('../providers/index.js');
var FS_FORMAT = require('src/constants').FS_FORMAT;
var FS_READY = require('src/constants').FS_READY;
var FS_PENDING = require('src/constants').FS_PENDING;
var FS_ERROR = require('src/constants').FS_ERROR;
var providers = require('src/providers/providers'); var Shell = require('../shell/shell.js');
var adapters = require('src/adapters/adapters'); var Intercom = require('../../lib/intercom.js');
var FSWatcher = require('../fs-watcher.js');
var Errors = require('../errors.js');
var Shell = require('src/shell/shell'); var STDIN = Constants.STDIN;
var Intercom = require('intercom'); var STDOUT = Constants.STDOUT;
var FSWatcher = require('src/fs-watcher'); var STDERR = Constants.STDERR;
var Errors = require('src/errors'); var FIRST_DESCRIPTOR = Constants.FIRST_DESCRIPTOR;
var STDIN = require('src/constants').STDIN;
var STDOUT = require('src/constants').STDOUT;
var STDERR = require('src/constants').STDERR;
var FIRST_DESCRIPTOR = require('src/constants').FIRST_DESCRIPTOR;
// The core fs operations live on impl // The core fs operations live on impl
var impl = require('src/filesystem/implementation'); var impl = require('./implementation.js');
// node.js supports a calling pattern that leaves off a callback. // node.js supports a calling pattern that leaves off a callback.
function maybeCallback(callback) { function maybeCallback(callback) {
if(typeof callback === "function") { if(typeof callback === "function") {
return callback; return callback;
} }
@ -37,9 +35,9 @@ define(function(require) {
throw err; throw err;
} }
}; };
} }
/** /**
* FileSystem * FileSystem
* *
* A FileSystem takes an `options` object, which can specify a number of, * A FileSystem takes an `options` object, which can specify a number of,
@ -64,7 +62,7 @@ define(function(require) {
* users should check the file system's `readyState` and `error` * users should check the file system's `readyState` and `error`
* properties to make sure it is usable. * properties to make sure it is usable.
*/ */
function FileSystem(options, callback) { function FileSystem(options, callback) {
options = options || {}; options = options || {};
callback = callback || nop; callback = callback || nop;
@ -211,18 +209,15 @@ define(function(require) {
impl.makeRootDirectory(context, complete); impl.makeRootDirectory(context, complete);
}); });
}); });
} }
// Expose storage providers on FileSystem constructor // Expose storage providers on FileSystem constructor
FileSystem.providers = providers; FileSystem.providers = providers;
// Expose adatpers on FileSystem constructor /**
FileSystem.adapters = adapters;
/**
* Public API for FileSystem * Public API for FileSystem
*/ */
[ [
'open', 'open',
'close', 'close',
'mknod', 'mknod',
@ -254,7 +249,7 @@ define(function(require) {
'fgetxattr', 'fgetxattr',
'removexattr', 'removexattr',
'fremovexattr' 'fremovexattr'
].forEach(function(methodName) { ].forEach(function(methodName) {
FileSystem.prototype[methodName] = function() { FileSystem.prototype[methodName] = function() {
var fs = this; var fs = this;
var args = Array.prototype.slice.call(arguments, 0); var args = Array.prototype.slice.call(arguments, 0);
@ -291,12 +286,10 @@ define(function(require) {
callback(error); callback(error);
} }
}; };
});
FileSystem.prototype.Shell = function(options) {
return new Shell(this, options);
};
return FileSystem;
}); });
FileSystem.prototype.Shell = function(options) {
return new Shell(this, options);
};
module.exports = FileSystem;

View File

@ -1,14 +1,12 @@
define(function(require) { var EventEmitter = require('../lib/eventemitter.js');
var isNullPath = require('./path.js').isNull;
var Intercom = require('../lib/intercom.js');
var EventEmitter = require('eventemitter'); /**
var isNullPath = require('src/path').isNull;
var Intercom = require('intercom');
/**
* FSWatcher based on node.js' FSWatcher * FSWatcher based on node.js' FSWatcher
* see https://github.com/joyent/node/blob/master/lib/fs.js * see https://github.com/joyent/node/blob/master/lib/fs.js
*/ */
function FSWatcher() { function FSWatcher() {
EventEmitter.call(this); EventEmitter.call(this);
var self = this; var self = this;
var recursive = false; var recursive = false;
@ -46,9 +44,8 @@ define(function(require) {
intercom.off('change', onchange); intercom.off('change', onchange);
self.removeAllListeners('change'); self.removeAllListeners('change');
}; };
} }
FSWatcher.prototype = new EventEmitter(); FSWatcher.prototype = new EventEmitter();
FSWatcher.prototype.constructor = FSWatcher; FSWatcher.prototype.constructor = FSWatcher;
return FSWatcher; module.exports = FSWatcher;
});

View File

@ -1,7 +1,5 @@
define(function(require) { module.exports = {
return { FileSystem: require('./filesystem/interface.js'),
FileSystem: require('src/filesystem/interface'), Path: require('./path.js'),
Path: require('src/path'), Errors: require('./errors.js')
Errors: require('src/errors') };
};
});

59
src/network.js Normal file
View File

@ -0,0 +1,59 @@
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) {
require('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;
if (error) {
return callback(error, 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(null, data);
});
}
module.exports.download = (function() {
if (typeof XMLHttpRequest === 'undefined') {
return nodeDownload;
} else {
return browserDownload;
}
}());

View File

@ -1,10 +1,11 @@
define(['src/constants', 'src/shared'], function(Constants, Shared) { var MODE_FILE = require('./constants.js').MODE_FILE;
var guid = require('./shared.js').guid;
return function Node(id, mode, size, atime, ctime, mtime, flags, xattrs, nlinks, version) { module.exports = function Node(id, mode, size, atime, ctime, mtime, flags, xattrs, nlinks, version) {
var now = Date.now(); var now = Date.now();
this.id = id || Shared.guid(); this.id = id || guid();
this.mode = mode || Constants.MODE_FILE; // node type (file, directory, etc) this.mode = mode || MODE_FILE; // node type (file, directory, etc)
this.size = size || 0; // size (bytes for files, entries for directories) this.size = size || 0; // size (bytes for files, entries for directories)
this.atime = atime || now; // access time (will mirror ctime after creation) this.atime = atime || now; // access time (will mirror ctime after creation)
this.ctime = ctime || now; // creation/change time this.ctime = ctime || now; // creation/change time
@ -15,7 +16,5 @@ define(['src/constants', 'src/shared'], function(Constants, Shared) {
this.version = version || 0; // node version this.version = version || 0; // node version
this.blksize = undefined; // block size this.blksize = undefined; // block size
this.nblocks = 1; // blocks count this.nblocks = 1; // blocks count
this.data = Shared.guid(); // id for data object this.data = guid(); // id for data object
}; };
});

View File

@ -1,10 +1,6 @@
define(function(require) { module.exports = function OpenFileDescription(path, id, flags, position) {
return function OpenFileDescription(path, id, flags, position) {
this.path = path; this.path = path;
this.id = id; this.id = id;
this.flags = flags; this.flags = flags;
this.position = position; this.position = position;
}; };
});

View File

@ -20,13 +20,12 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js // Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js
define(function() {
// resolves . and .. elements in a path array with directory names there // resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array // must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish // (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths) // relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) { function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0 // if the path tries to go above the root, `up` ends up > 0
var up = 0; var up = 0;
for (var i = parts.length - 1; i >= 0; i--) { for (var i = parts.length - 1; i >= 0; i--) {
@ -50,19 +49,19 @@ define(function() {
} }
return parts; return parts;
} }
// Split a filename into [root, dir, basename, ext], unix version // Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing. // 'root' is just a slash, or nothing.
var splitPathRe = var splitPathRe =
/^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/; /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;
var splitPath = function(filename) { var splitPath = function(filename) {
var result = splitPathRe.exec(filename); var result = splitPathRe.exec(filename);
return [result[1] || '', result[2] || '', result[3] || '', result[4] || '']; return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
}; };
// path.resolve([from ...], to) // path.resolve([from ...], to)
function resolve() { function resolve() {
var resolvedPath = '', var resolvedPath = '',
resolvedAbsolute = false; resolvedAbsolute = false;
@ -88,10 +87,10 @@ define(function() {
}), !resolvedAbsolute).join('/'); }), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
} }
// path.normalize(path) // path.normalize(path)
function normalize(path) { function normalize(path) {
var isAbsolute = path.charAt(0) === '/', var isAbsolute = path.charAt(0) === '/',
trailingSlash = path.substr(-1) === '/'; trailingSlash = path.substr(-1) === '/';
@ -110,17 +109,17 @@ define(function() {
*/ */
return (isAbsolute ? '/' : '') + path; return (isAbsolute ? '/' : '') + path;
} }
function join() { function join() {
var paths = Array.prototype.slice.call(arguments, 0); var paths = Array.prototype.slice.call(arguments, 0);
return normalize(paths.filter(function(p, index) { return normalize(paths.filter(function(p, index) {
return p && typeof p === 'string'; return p && typeof p === 'string';
}).join('/')); }).join('/'));
} }
// path.relative(from, to) // path.relative(from, to)
function relative(from, to) { function relative(from, to) {
from = exports.resolve(from).substr(1); from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1); to = exports.resolve(to).substr(1);
@ -159,9 +158,9 @@ define(function() {
outputParts = outputParts.concat(toParts.slice(samePartsLength)); outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/'); return outputParts.join('/');
} }
function dirname(path) { function dirname(path) {
var result = splitPath(path), var result = splitPath(path),
root = result[0], root = result[0],
dir = result[1]; dir = result[1];
@ -177,9 +176,9 @@ define(function() {
} }
return root + dir; return root + dir;
} }
function basename(path, ext) { function basename(path, ext) {
var f = splitPath(path)[2]; var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows? // TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) { if (ext && f.substr(-1 * ext.length) === ext) {
@ -187,30 +186,30 @@ define(function() {
} }
// XXXidbfs: node.js just does `return f` // XXXidbfs: node.js just does `return f`
return f === "" ? "/" : f; return f === "" ? "/" : f;
} }
function extname(path) { function extname(path) {
return splitPath(path)[3]; return splitPath(path)[3];
} }
function isAbsolute(path) { function isAbsolute(path) {
if(path.charAt(0) === '/') { if(path.charAt(0) === '/') {
return true; return true;
} }
return false; return false;
} }
function isNull(path) { function isNull(path) {
if (('' + path).indexOf('\u0000') !== -1) { if (('' + path).indexOf('\u0000') !== -1) {
return true; return true;
} }
return false; return false;
} }
// XXXidbfs: we don't support path.exists() or path.existsSync(), which // XXXidbfs: we don't support path.exists() or path.existsSync(), which
// are deprecated, and need a FileSystem instance to work. Use fs.stat(). // are deprecated, and need a FileSystem instance to work. Use fs.stat().
return { module.exports = {
normalize: normalize, normalize: normalize,
resolve: resolve, resolve: resolve,
join: join, join: join,
@ -222,6 +221,4 @@ define(function() {
extname: extname, extname: extname,
isAbsolute: isAbsolute, isAbsolute: isAbsolute,
isNull: isNull isNull: isNull
}; };
});

35
src/providers/index.js Normal file
View File

@ -0,0 +1,35 @@
var IndexedDB = require('./indexeddb.js');
var WebSQL = require('./websql.js');
var Memory = require('./memory.js');
module.exports = {
IndexedDB: IndexedDB,
WebSQL: WebSQL,
Memory: Memory,
/**
* Convenience Provider references
*/
// The default provider to use when none is specified
Default: IndexedDB,
// The Fallback provider does automatic fallback checks
Fallback: (function() {
if(IndexedDB.isSupported()) {
return IndexedDB;
}
if(WebSQL.isSupported()) {
return WebSQL;
}
function NotSupported() {
throw "[Filer Error] Your browser doesn't support IndexedDB or WebSQL.";
}
NotSupported.isSupported = function() {
return false;
};
return NotSupported;
}())
};

View File

@ -1,15 +1,14 @@
define(function(require) { (function(global) {
var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; var FILE_STORE_NAME = require('../constants.js').FILE_STORE_NAME;
var IDB_RW = require('../constants.js').IDB_RW;
var IDB_RO = require('../constants.js').IDB_RO;
var Errors = require('../errors.js');
var indexedDB = window.indexedDB || var indexedDB = global.indexedDB ||
window.mozIndexedDB || global.mozIndexedDB ||
window.webkitIndexedDB || global.webkitIndexedDB ||
window.msIndexedDB; global.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) { function IndexedDBContext(db, mode) {
var transaction = db.transaction(FILE_STORE_NAME, mode); var transaction = db.transaction(FILE_STORE_NAME, mode);
@ -126,5 +125,6 @@ define(function(require) {
return new IndexedDBContext(this.db, IDB_RW); return new IndexedDBContext(this.db, IDB_RW);
}; };
return IndexedDB; module.exports = IndexedDB;
});
}(this));

View File

@ -1,11 +1,10 @@
define(function(require) { var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; var asyncCallback = require('../../lib/async.js').nextTick;
var asyncCallback = require('async').nextTick;
/** /**
* Make shared in-memory DBs possible when using the same name. * Make shared in-memory DBs possible when using the same name.
*/ */
var createDB = (function() { var createDB = (function() {
var pool = {}; var pool = {};
return function getOrCreate(name) { return function getOrCreate(name) {
var firstAccess = !pool.hasOwnProperty(name); var firstAccess = !pool.hasOwnProperty(name);
@ -17,13 +16,13 @@ define(function(require) {
db: pool[name] db: pool[name]
}; };
}; };
}()); }());
function MemoryContext(db, readOnly) { function MemoryContext(db, readOnly) {
this.readOnly = readOnly; this.readOnly = readOnly;
this.objectStore = db; this.objectStore = db;
} }
MemoryContext.prototype.clear = function(callback) { MemoryContext.prototype.clear = function(callback) {
if(this.readOnly) { if(this.readOnly) {
asyncCallback(function() { asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context"); callback("[MemoryContext] Error: write operation on read only context");
@ -35,14 +34,14 @@ define(function(require) {
delete objectStore[key]; delete objectStore[key];
}); });
asyncCallback(callback); asyncCallback(callback);
}; };
MemoryContext.prototype.get = function(key, callback) { MemoryContext.prototype.get = function(key, callback) {
var that = this; var that = this;
asyncCallback(function() { asyncCallback(function() {
callback(null, that.objectStore[key]); callback(null, that.objectStore[key]);
}); });
}; };
MemoryContext.prototype.put = function(key, value, callback) { MemoryContext.prototype.put = function(key, value, callback) {
if(this.readOnly) { if(this.readOnly) {
asyncCallback(function() { asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context"); callback("[MemoryContext] Error: write operation on read only context");
@ -51,8 +50,8 @@ define(function(require) {
} }
this.objectStore[key] = value; this.objectStore[key] = value;
asyncCallback(callback); asyncCallback(callback);
}; };
MemoryContext.prototype.delete = function(key, callback) { MemoryContext.prototype.delete = function(key, callback) {
if(this.readOnly) { if(this.readOnly) {
asyncCallback(function() { asyncCallback(function() {
callback("[MemoryContext] Error: write operation on read only context"); callback("[MemoryContext] Error: write operation on read only context");
@ -61,29 +60,28 @@ define(function(require) {
} }
delete this.objectStore[key]; delete this.objectStore[key];
asyncCallback(callback); asyncCallback(callback);
}; };
function Memory(name) { function Memory(name) {
this.name = name || FILE_SYSTEM_NAME; this.name = name || FILE_SYSTEM_NAME;
} }
Memory.isSupported = function() { Memory.isSupported = function() {
return true; return true;
}; };
Memory.prototype.open = function(callback) { Memory.prototype.open = function(callback) {
var result = createDB(this.name); var result = createDB(this.name);
this.db = result.db; this.db = result.db;
asyncCallback(function() { asyncCallback(function() {
callback(null, result.firstAccess); callback(null, result.firstAccess);
}); });
}; };
Memory.prototype.getReadOnlyContext = function() { Memory.prototype.getReadOnlyContext = function() {
return new MemoryContext(this.db, true); return new MemoryContext(this.db, true);
}; };
Memory.prototype.getReadWriteContext = function() { Memory.prototype.getReadWriteContext = function() {
return new MemoryContext(this.db, false); return new MemoryContext(this.db, false);
}; };
return Memory; module.exports = Memory;
});

View File

@ -1,38 +0,0 @@
define(function(require) {
var IndexedDB = require('src/providers/indexeddb');
var WebSQL = require('src/providers/websql');
var Memory = require('src/providers/memory');
return {
IndexedDB: IndexedDB,
WebSQL: WebSQL,
Memory: Memory,
/**
* Convenience Provider references
*/
// The default provider to use when none is specified
Default: IndexedDB,
// The Fallback provider does automatic fallback checks
Fallback: (function() {
if(IndexedDB.isSupported()) {
return IndexedDB;
}
if(WebSQL.isSupported()) {
return WebSQL;
}
function NotSupported() {
throw "[Filer Error] Your browser doesn't support IndexedDB or WebSQL.";
}
NotSupported.isSupported = function() {
return false;
};
return NotSupported;
}())
};
});

View File

@ -1,11 +1,11 @@
define(function(require) { (function(global) {
var FILE_SYSTEM_NAME = require('src/constants').FILE_SYSTEM_NAME; var FILE_SYSTEM_NAME = require('../constants.js').FILE_SYSTEM_NAME;
var FILE_STORE_NAME = require('src/constants').FILE_STORE_NAME; var FILE_STORE_NAME = require('../constants.js').FILE_STORE_NAME;
var WSQL_VERSION = require('src/constants').WSQL_VERSION; var WSQL_VERSION = require('../constants.js').WSQL_VERSION;
var WSQL_SIZE = require('src/constants').WSQL_SIZE; var WSQL_SIZE = require('../constants.js').WSQL_SIZE;
var WSQL_DESC = require('src/constants').WSQL_DESC; var WSQL_DESC = require('../constants.js').WSQL_DESC;
var u8toArray = require('src/shared').u8toArray; var u8toArray = require('../shared.js').u8toArray;
var Errors = require('src/errors'); var Errors = require('../errors.js');
function WebSQLContext(db, isReadOnly) { function WebSQLContext(db, isReadOnly) {
var that = this; var that = this;
@ -98,7 +98,7 @@ define(function(require) {
this.db = null; this.db = null;
} }
WebSQL.isSupported = function() { WebSQL.isSupported = function() {
return !!window.openDatabase; return !!global.openDatabase;
}; };
WebSQL.prototype.open = function(callback) { WebSQL.prototype.open = function(callback) {
@ -110,7 +110,7 @@ define(function(require) {
return; return;
} }
var db = window.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE); var db = global.openDatabase(that.name, WSQL_VERSION, WSQL_DESC, WSQL_SIZE);
if(!db) { if(!db) {
callback("[WebSQL] Unable to open database."); callback("[WebSQL] Unable to open database.");
return; return;
@ -156,5 +156,6 @@ define(function(require) {
return new WebSQLContext(this.db, false); return new WebSQLContext(this.db, false);
}; };
return WebSQL; module.exports = WebSQL;
});
}(this));

View File

@ -1,37 +1,26 @@
define(function(require) { function guid() {
require("crypto-js/rollups/sha256"); var Crypto = CryptoJS;
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16); return v.toString(16);
}).toUpperCase(); }).toUpperCase();
} }
function hash(string) { function nop() {}
return Crypto.SHA256(string).toString(Crypto.enc.hex);
}
function nop() {} /**
/**
* Convert a Uint8Array to a regular array * Convert a Uint8Array to a regular array
*/ */
function u8toArray(u8) { function u8toArray(u8) {
var array = []; var array = [];
var len = u8.length; var len = u8.length;
for(var i = 0; i < len; i++) { for(var i = 0; i < len; i++) {
array[i] = u8[i]; array[i] = u8[i];
} }
return array; return array;
} }
return { module.exports = {
guid: guid, guid: guid,
hash: hash,
u8toArray: u8toArray, u8toArray: u8toArray,
nop: nop nop: nop
}; };
});

View File

@ -1,8 +1,6 @@
define(function(require) { var defaults = require('../constants.js').ENVIRONMENT;
var defaults = require('src/constants').ENVIRONMENT; module.exports = function Environment(env) {
function Environment(env) {
env = env || {}; env = env || {};
env.TMP = env.TMP || defaults.TMP; env.TMP = env.TMP || defaults.TMP;
env.PATH = env.PATH || defaults.PATH; env.PATH = env.PATH || defaults.PATH;
@ -14,7 +12,4 @@ define(function(require) {
this.set = function(name, value) { this.set = function(name, value) {
env[name] = value; env[name] = value;
}; };
} };
return Environment;
});

View File

@ -1,15 +1,12 @@
/* jshint evil:true */ var Path = require('../path.js');
define(function(require) { var Errors = require('../errors.js');
var Environment = require('./environment.js');
var async = require('../../lib/async.js');
var Network = require('../network.js');
var Zlib = require('../../lib/zip-utils.js');
var TextEncoder = require('../../lib/encoding.js').TextEncoder;
var Path = require('src/path'); function Shell(fs, options) {
var Errors = require('src/errors');
var Environment = require('src/shell/environment');
var async = require('async');
require('zip');
require('unzip');
function Shell(fs, options) {
options = options || {}; options = options || {};
var env = new Environment(options.env); var env = new Environment(options.env);
@ -61,9 +58,9 @@ define(function(require) {
this.pwd = function() { this.pwd = function() {
return cwd; return cwd;
}; };
} }
/** /**
* Execute the .js command located at `path`. Such commands * Execute the .js command located at `path`. Such commands
* should assume the existence of 3 arguments, which will be * should assume the existence of 3 arguments, which will be
* defined at runtime: * defined at runtime:
@ -79,7 +76,8 @@ define(function(require) {
* // .js code here * // .js code here
* } * }
*/ */
Shell.prototype.exec = function(path, args, callback) { Shell.prototype.exec = function(path, args, callback) {
/* jshint evil:true */
var fs = this.fs; var fs = this.fs;
if(typeof args === 'function') { if(typeof args === 'function') {
callback = args; callback = args;
@ -101,16 +99,16 @@ define(function(require) {
callback(e); callback(e);
} }
}); });
}; };
/** /**
* Create a file if it does not exist, or update access and * Create a file if it does not exist, or update access and
* modified times if it does. Valid options include: * modified times if it does. Valid options include:
* *
* * updateOnly - whether to create the file if missing (defaults to false) * * updateOnly - whether to create the file if missing (defaults to false)
* * date - use the provided Date value instead of current date/time * * date - use the provided Date value instead of current date/time
*/ */
Shell.prototype.touch = function(path, options, callback) { Shell.prototype.touch = function(path, options, callback) {
var fs = this.fs; var fs = this.fs;
if(typeof options === 'function') { if(typeof options === 'function') {
callback = options; callback = options;
@ -143,15 +141,15 @@ define(function(require) {
updateTimes(path); updateTimes(path);
} }
}); });
}; };
/** /**
* Concatenate multiple files into a single String, with each * Concatenate multiple files into a single String, with each
* file separated by a newline. The `files` argument should * file separated by a newline. The `files` argument should
* be a String (path to single file) or an Array of Strings * be a String (path to single file) or an Array of Strings
* (multiple file paths). * (multiple file paths).
*/ */
Shell.prototype.cat = function(files, callback) { Shell.prototype.cat = function(files, callback) {
var fs = this.fs; var fs = this.fs;
var all = ''; var all = '';
callback = callback || function(){}; callback = callback || function(){};
@ -182,9 +180,9 @@ define(function(require) {
callback(null, all.replace(/\n$/, '')); callback(null, all.replace(/\n$/, ''));
} }
}); });
}; };
/** /**
* Get the listing of a directory, returning an array of * Get the listing of a directory, returning an array of
* file entries in the following form: * file entries in the following form:
* *
@ -201,7 +199,7 @@ define(function(require) {
* to follow directories as they are encountered, use * to follow directories as they are encountered, use
* the `recursive=true` option. * the `recursive=true` option.
*/ */
Shell.prototype.ls = function(dir, options, callback) { Shell.prototype.ls = function(dir, options, callback) {
var fs = this.fs; var fs = this.fs;
if(typeof options === 'function') { if(typeof options === 'function') {
callback = options; callback = options;
@ -264,16 +262,16 @@ define(function(require) {
} }
list(dir, callback); list(dir, callback);
}; };
/** /**
* Removes the file or directory at `path`. If `path` is a file * Removes the file or directory at `path`. If `path` is a file
* it will be removed. If `path` is a directory, it will be * it will be removed. If `path` is a directory, it will be
* removed if it is empty, otherwise the callback will receive * removed if it is empty, otherwise the callback will receive
* an error. In order to remove non-empty directories, use the * an error. In order to remove non-empty directories, use the
* `recursive=true` option. * `recursive=true` option.
*/ */
Shell.prototype.rm = function(path, options, callback) { Shell.prototype.rm = function(path, options, callback) {
var fs = this.fs; var fs = this.fs;
if(typeof options === 'function') { if(typeof options === 'function') {
callback = options; callback = options;
@ -337,14 +335,14 @@ define(function(require) {
} }
remove(path, callback); remove(path, callback);
}; };
/** /**
* Gets the path to the temporary directory, creating it if not * Gets the path to the temporary directory, creating it if not
* present. The directory used is the one specified in * present. The directory used is the one specified in
* env.TMP. The callback receives (error, tempDirName). * env.TMP. The callback receives (error, tempDirName).
*/ */
Shell.prototype.tempDir = function(callback) { Shell.prototype.tempDir = function(callback) {
var fs = this.fs; var fs = this.fs;
var tmp = this.env.get('TMP'); var tmp = this.env.get('TMP');
callback = callback || function(){}; callback = callback || function(){};
@ -354,16 +352,16 @@ define(function(require) {
fs.mkdir(tmp, function(err) { fs.mkdir(tmp, function(err) {
callback(null, tmp); callback(null, tmp);
}); });
}; };
/** /**
* Recursively creates the directory at `path`. If the parent * Recursively creates the directory at `path`. If the parent
* of `path` does not exist, it will be created. * of `path` does not exist, it will be created.
* Based off EnsureDir by Sam X. Xu * Based off EnsureDir by Sam X. Xu
* https://www.npmjs.org/package/ensureDir * https://www.npmjs.org/package/ensureDir
* MIT License * MIT License
*/ */
Shell.prototype.mkdirp = function(path, callback) { Shell.prototype.mkdirp = function(path, callback) {
var fs = this.fs; var fs = this.fs;
callback = callback || function(){}; callback = callback || function(){};
@ -417,20 +415,19 @@ define(function(require) {
}); });
} }
} }
}); });
} }
_mkdirp(path, callback); _mkdirp(path, callback);
}; };
/** /**
* Downloads the file at `url` and saves it to the filesystem. * Downloads the file at `url` and saves it to the filesystem.
* The file is saved to a file named with the current date/time * The file is saved to a file named with the current date/time
* unless the `options.filename` is present, in which case that * unless the `options.filename` is present, in which case that
* filename is used instead. The callback receives (error, path). * filename is used instead. The callback receives (error, path).
*/ */
Shell.prototype.wget = function(url, options, callback) { Shell.prototype.wget = function(url, options, callback) {
var fs = this.fs; var fs = this.fs;
if(typeof options === 'function') { if(typeof options === 'function') {
callback = options; callback = options;
@ -444,23 +441,23 @@ define(function(require) {
return; return;
} }
// Grab whatever is after the last / (assuming there is one) and // Grab whatever is after the last / (assuming there is one). Like the real
// remove any non-filename type chars(i.e., : and /). Like the real // wget, we leave query string or hash portions in tact. This assumes a
// wget, we leave query string or hash portions in tact. // properly encoded URL.
var path = options.filename || url.replace(/[:/]/g, '').split('/').pop(); // i.e. instead of "/foo?bar/" we would expect "/foo?bar%2F"
var path = options.filename || url.split('/').pop();
path = Path.resolve(fs.cwd, path); path = Path.resolve(fs.cwd, path);
function onerror() { function onerror() {
callback(new Error('unable to get resource')); callback(new Error('unable to get resource'));
} }
var request = new XMLHttpRequest(); Network.download(url, function(err, data) {
request.onload = function() { if (err || !data) {
if(request.status !== 200) {
return onerror(); return onerror();
} }
var data = new Uint8Array(request.response);
fs.writeFile(path, data, function(err) { fs.writeFile(path, data, function(err) {
if(err) { if(err) {
callback(err); callback(err);
@ -468,18 +465,10 @@ define(function(require) {
callback(null, path); callback(null, path);
} }
}); });
}; });
request.onerror = onerror; };
request.open("GET", url, true);
if("withCredentials" in request) {
request.withCredentials = true;
}
request.responseType = "arraybuffer"; Shell.prototype.unzip = function(zipfile, options, callback) {
request.send();
};
Shell.prototype.unzip = function(zipfile, options, callback) {
var fs = this.fs; var fs = this.fs;
var sh = this; var sh = this;
if(typeof options === 'function') { if(typeof options === 'function') {
@ -523,9 +512,9 @@ define(function(require) {
async.eachSeries(filenames, decompress, callback); async.eachSeries(filenames, decompress, callback);
}); });
}; };
Shell.prototype.zip = function(zipfile, paths, options, callback) { Shell.prototype.zip = function(zipfile, paths, options, callback) {
var fs = this.fs; var fs = this.fs;
var sh = this; var sh = this;
if(typeof options === 'function') { if(typeof options === 'function') {
@ -610,8 +599,6 @@ define(function(require) {
fs.writeFile(zipfile, compressed, callback); fs.writeFile(zipfile, compressed, callback);
}); });
}); });
}; };
return Shell; module.exports = Shell;
});

View File

@ -1,6 +1,6 @@
define(['src/constants'], function(Constants) { var Constants = require('./constants.js');
function Stats(fileNode, devName) { function Stats(fileNode, devName) {
this.node = fileNode.id; this.node = fileNode.id;
this.dev = devName; this.dev = devName;
this.size = fileNode.size; this.size = fileNode.size;
@ -9,29 +9,27 @@ define(['src/constants'], function(Constants) {
this.mtime = fileNode.mtime; this.mtime = fileNode.mtime;
this.ctime = fileNode.ctime; this.ctime = fileNode.ctime;
this.type = fileNode.mode; this.type = fileNode.mode;
} }
Stats.prototype.isFile = function() { Stats.prototype.isFile = function() {
return this.type === Constants.MODE_FILE; return this.type === Constants.MODE_FILE;
}; };
Stats.prototype.isDirectory = function() { Stats.prototype.isDirectory = function() {
return this.type === Constants.MODE_DIRECTORY; return this.type === Constants.MODE_DIRECTORY;
}; };
Stats.prototype.isSymbolicLink = function() { Stats.prototype.isSymbolicLink = function() {
return this.type === Constants.MODE_SYMBOLIC_LINK; return this.type === Constants.MODE_SYMBOLIC_LINK;
}; };
// These will always be false in Filer. // These will always be false in Filer.
Stats.prototype.isSocket = Stats.prototype.isSocket =
Stats.prototype.isFIFO = Stats.prototype.isFIFO =
Stats.prototype.isCharacterDevice = Stats.prototype.isCharacterDevice =
Stats.prototype.isBlockDevice = Stats.prototype.isBlockDevice =
function() { function() {
return false; return false;
}; };
return Stats; module.exports = Stats;
});

View File

@ -1,6 +1,7 @@
define(['src/constants', 'src/shared'], function(Constants, Shared) { var Constants = require('./constants.js');
var guid = require('./shared.js').guid;
return function SuperNode(atime, ctime, mtime) { module.exports = function SuperNode(atime, ctime, mtime) {
var now = Date.now(); var now = Date.now();
this.id = Constants.SUPER_NODE_ID; this.id = Constants.SUPER_NODE_ID;
@ -8,7 +9,5 @@ define(['src/constants', 'src/shared'], function(Constants, Shared) {
this.atime = atime || now; this.atime = atime || now;
this.ctime = ctime || now; this.ctime = ctime || now;
this.mtime = mtime || now; this.mtime = mtime || now;
this.rnode = Shared.guid(); // root node id (randomly generated) this.rnode = guid(); // root node id (randomly generated)
}; };
});

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('trailing slashes in path names, issue 105', function() { describe('trailing slashes in path names, issue 105', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -31,5 +33,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.writeFile truncation - issue 106', function() { describe('fs.writeFile truncation - issue 106', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -27,5 +29,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -6,26 +6,14 @@
<script src="../bower_components/chai/chai.js"></script> <script src="../bower_components/chai/chai.js"></script>
<script src="../bower_components/mocha/mocha.js"></script> <script src="../bower_components/mocha/mocha.js"></script>
<script> <script>
// Polyfill for function.bind, which PhantomJS seems to need, see mocha.setup('bdd').timeout(5000).slow(250);;
// https://gist.github.com/Daniel-Hug/5682738/raw/147ec7d72123fbef4d7471dcc88c2bc3d52de8d9/function-bind.js
Function.prototype.bind = (function () {}).bind || function (b) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
function c() {} window.onload = function() {
var a = [].slice, mocha.checkLeaks();
f = a.call(arguments, 1), mocha.run();
e = this,
d = function () {
return e.apply(this instanceof c ? this : b || window, f.concat(a.call(arguments)));
};
c.prototype = this.prototype;
d.prototype = new c();
return d;
}; };
</script> </script>
<script src="../lib/require.js" data-main="require-config"></script> <script src="../dist/filer-test.js"></script>
</head> </head>
<body> <body>
<div id="mocha"></div> <div id="mocha"></div>

69
tests/index.js Normal file
View File

@ -0,0 +1,69 @@
/**
* 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");

View File

@ -1,14 +1,17 @@
define(["Filer"], function(Filer) { (function(global) {
var Filer = require("../..");
var indexedDB = window.indexedDB || var indexedDB = global.indexedDB ||
window.mozIndexedDB || global.mozIndexedDB ||
window.webkitIndexedDB || global.webkitIndexedDB ||
window.msIndexedDB; global.msIndexedDB;
var needsCleanup = []; var needsCleanup = [];
window.addEventListener('beforeunload', function() { if(global.addEventListener) {
global.addEventListener('beforeunload', function() {
needsCleanup.forEach(function(f) { f(); }); needsCleanup.forEach(function(f) { f(); });
}); });
}
function IndexedDBTestProvider(name) { function IndexedDBTestProvider(name) {
var _done = false; var _done = false;
@ -48,6 +51,6 @@ define(["Filer"], function(Filer) {
this.cleanup = cleanup; this.cleanup = cleanup;
} }
return IndexedDBTestProvider; module.exports = IndexedDBTestProvider;
}); }(this));

View File

@ -1,6 +1,6 @@
define(["Filer"], function(Filer) { var Filer = require('../..');
function MemoryTestProvider(name) { function MemoryTestProvider(name) {
var that = this; var that = this;
function cleanup(callback) { function cleanup(callback) {
@ -17,8 +17,6 @@ define(["Filer"], function(Filer) {
this.init = init; this.init = init;
this.cleanup = cleanup; this.cleanup = cleanup;
} }
return MemoryTestProvider; module.exports = MemoryTestProvider;
});

View File

@ -1,5 +1,9 @@
define(["Filer", "tests/lib/indexeddb", "tests/lib/websql", "tests/lib/memory"], (function(global) {
function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
var Filer = require('../..');
var IndexedDBTestProvider = require('./indexeddb.js');
var WebSQLTestProvider = require('./websql.js');
var MemoryTestProvider = require('./memory.js');
var _provider; var _provider;
var _fs; var _fs;
@ -12,13 +16,6 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
} }
function findBestProvider() { function findBestProvider() {
// 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) {
return MemoryTestProvider;
}
var providers = Filer.FileSystem.providers; var providers = Filer.FileSystem.providers;
if(providers.IndexedDB.isSupported()) { if(providers.IndexedDB.isSupported()) {
return IndexedDBTestProvider; return IndexedDBTestProvider;
@ -30,12 +27,12 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
} }
function setup(callback) { function setup(callback) {
// We support specifying the provider via the query string // In browser we support specifying the provider via the query string
// (e.g., ?filer-provider=IndexedDB). If not specified, we use // (e.g., ?filer-provider=IndexedDB). If not specified, we use
// the Memory provider by default. See test/require-config.js // the Memory provider by default. See test/require-config.js
// for definition of window.filerArgs. // for definition of window.filerArgs.
var providerType = window.filerArgs && window.filerArgs.provider ? var providerType = global.filerArgs && global.filerArgs.provider ?
window.filerArgs.provider : 'Memory'; global.filerArgs.provider : 'Memory';
var name = uniqueName(); var name = uniqueName();
@ -55,8 +52,8 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
} }
// Allow passing FS flags on query string // Allow passing FS flags on query string
var flags = window.filerArgs && window.filerArgs.flags ? var flags = global.filerArgs && global.filerArgs.flags ?
window.filerArgs.flags : 'FORMAT'; global.filerArgs.flags : 'FORMAT';
// Create a file system and wait for it to get setup // Create a file system and wait for it to get setup
_provider.init(); _provider.init();
@ -119,7 +116,7 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
return true; return true;
} }
return { module.exports = {
uniqueName: uniqueName, uniqueName: uniqueName,
setup: setup, setup: setup,
fs: fs, fs: fs,
@ -134,4 +131,4 @@ function(Filer, IndexedDBTestProvider, WebSQLTestProvider, MemoryTestProvider) {
typedArrayEqual: typedArrayEqual typedArrayEqual: typedArrayEqual
}; };
}); }(this));

View File

@ -1,9 +1,13 @@
define(["Filer"], function(Filer) { (function(global) {
var Filer = require('../..');
var needsCleanup = []; var needsCleanup = [];
if(global.addEventListener) {
window.addEventListener('beforeunload', function() { window.addEventListener('beforeunload', function() {
needsCleanup.forEach(function(f) { f(); }); needsCleanup.forEach(function(f) { f(); });
}); });
}
function WebSQLTestProvider(name) { function WebSQLTestProvider(name) {
var _done = false; var _done = false;
@ -38,6 +42,6 @@ define(["Filer"], function(Filer) {
this.cleanup = cleanup; this.cleanup = cleanup;
} }
return WebSQLTestProvider; module.exports = WebSQLTestProvider;
}); }(this));

View File

@ -1,90 +0,0 @@
/**
* Add spec files to the list in test-manifest.js
*/
// Dynamically figure out which source to use (dist/ or src/) based on
// query string:
//
// ?filer-dist/filer.js --> use dist/filer.js
// ?filer-dist/filer.min.js --> use dist/filer.min.js
// ?<default> --> (default) use src/filer.js with require
var filerArgs = window.filerArgs = {};
var config = (function() {
var query = window.location.search.substring(1);
query.split('&').forEach(function(pair) {
pair = pair.split('=');
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
if(key.indexOf('filer-') === 0) {
filerArgs[ key.replace(/^filer-/, '') ] = value;
}
});
// Support dist/filer.js
if(filerArgs['filer-dist/filer.js']) {
return {
paths: {
"tests": "../tests",
"spec": "../tests/spec",
"bugs": "../tests/bugs",
"util": "../tests/lib/test-utils",
"Filer": "../dist/filer"
},
baseUrl: "../lib",
optimize: "none"
};
}
// Support dist/filer.min.js
if(filerArgs['filer-dist/filer.min.js']) {
return {
paths: {
"tests": "../tests",
"spec": "../tests/spec",
"bugs": "../tests/bugs",
"util": "../tests/lib/test-utils",
"Filer": "../dist/filer.min"
},
baseUrl: "../lib",
optimize: "none"
};
}
// Support src/ filer via require
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"]
}
}
};
}());
require.config(config);
// Intentional globals
assert = chai.assert;
expect = chai.expect;
// We need to setup describe() support before loading tests.
// Use a test timeout of 5s and a slow-test warning of 250ms
mocha.setup("bdd").timeout(5000).slow(250);
require(["tests/test-manifest"], function() {
window.onload = function() {
mocha.checkLeaks();
mocha.run();
};
});

View File

@ -1,175 +0,0 @@
define(["Filer", "util"], function(Filer, util) {
// We reuse the same set of tests for all adapters.
// buildTestsFor() creates a set of tests bound to an
// adapter, and uses the provider set on the query string
// (defaults to best available/supported provider, see test-utils.js).
function buildTestsFor(adapterName, buildAdapter) {
function encode(str) {
// TextEncoder is either native, or shimmed by Filer
return (new TextEncoder("utf-8")).encode(str);
}
// Make some string + binary buffer versions of things we'll need
var valueStr = "value", valueBuffer = encode(valueStr);
var value1Str = "value1", value1Buffer = encode(value1Str);
var value2Str = "value2", value2Buffer = encode(value2Str);
function createProvider() {
return buildAdapter(util.provider().provider);
}
describe("Filer.FileSystem.adapters." + adapterName, function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it("is supported -- if it isn't, none of these tests can run.", function() {
// Allow for combined adapters (e.g., 'Encryption+Compression') joined by '+'
adapterName.split('+').forEach(function(name) {
expect(Filer.FileSystem.adapters[name].isSupported()).to.be.true;
});
});
it("has open, getReadOnlyContext, and getReadWriteContext instance methods", function() {
var provider = createProvider();
expect(provider.open).to.be.a('function');
expect(provider.getReadOnlyContext).to.be.a('function');
expect(provider.getReadWriteContext).to.be.a('function');
});
});
describe("open a provider with an " + adapterName + " adapter", function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it("should open a new database", function(done) {
var provider = createProvider();
provider.open(function(error, firstAccess) {
expect(error).not.to.exist;
// NOTE: we test firstAccess logic in the individual provider tests
// (see tests/spec/providers/*) but can't easily/actually test it here,
// since the provider-agnostic code in test-utils pre-creates a
// FileSystem object, thus eating the first access info.
// See https://github.com/js-platform/filer/issues/127
done();
});
});
});
describe("Read/Write operations on a provider with an " + adapterName + " adapter", function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it("should allow put() and get()", function(done) {
var provider = createProvider();
provider.open(function(error, firstAccess) {
if(error) throw error;
var context = provider.getReadWriteContext();
context.put("key", valueBuffer, function(error, result) {
if(error) throw error;
context.get("key", function(error, result) {
expect(error).not.to.exist;
expect(util.typedArrayEqual(result, valueBuffer)).to.be.true;
done();
});
});
});
});
it("should allow delete()", function(done) {
var provider = createProvider();
provider.open(function(error, firstAccess) {
if(error) throw error;
var context = provider.getReadWriteContext();
context.put("key", valueBuffer, function(error, result) {
if(error) throw error;
context.delete("key", function(error, result) {
if(error) throw error;
context.get("key", function(error, result) {
expect(error).not.to.exist;
expect(result).not.to.exist;
done();
});
});
});
});
});
it("should allow clear()", function(done) {
var provider = createProvider();
provider.open(function(error, firstAccess) {
if(error) throw error;
var context = provider.getReadWriteContext();
context.put("key1", value1Buffer, function(error, result) {
if(error) throw error;
context.put("key2", value2Buffer, function(error, result) {
if(error) throw error;
context.clear(function(err) {
if(error) throw error;
context.get("key1", function(error, result) {
if(error) throw error;
expect(result).not.to.exist;
context.get("key2", function(error, result) {
expect(error).not.to.exist;
expect(result).not.to.exist;
done();
});
});
});
});
});
});
});
/**
* With issue 123 (see https://github.com/js-platform/filer/issues/128) we had to
* start using readwrite contexts everywhere with IndexedDB. As such, we can't
* easily test this here, without knowing which provider we have. We test this
* in the actual providers, so this isn't really needed. Skipping for now.
*/
it.skip("should fail when trying to write on ReadOnlyContext", function(done) {
var provider = createProvider();
provider.open(function(error, firstAccess) {
if(error) throw error;
var context = provider.getReadOnlyContext();
context.put("key1", value1Buffer, function(error, result) {
expect(error).to.exist;
expect(result).not.to.exist;
done();
});
});
});
});
}
// Encryption
buildTestsFor('Encryption', function buildAdapter(provider) {
var passphrase = '' + Date.now();
return new Filer.FileSystem.adapters.Encryption(passphrase, provider);
});
// Compression
buildTestsFor('Compression', function buildAdapter(provider) {
return new Filer.FileSystem.adapters.Compression(provider);
});
// Encryption + Compression together
buildTestsFor('Encryption+Compression', function buildAdapter(provider) {
var passphrase = '' + Date.now();
var compression = new Filer.FileSystem.adapters.Compression(provider);
var encryptionWithCompression = new Filer.FileSystem.adapters.Encryption(passphrase, compression);
return encryptionWithCompression;
});
});

View File

@ -1,15 +0,0 @@
define(["Filer"], function(Filer) {
describe("Filer.FileSystem.adapters", function() {
it("is defined", function() {
expect(Filer.FileSystem.adapters).to.exist;
});
it("has a default Encryption constructor", function() {
expect(Filer.FileSystem.adapters.Encryption).to.be.a('function');
});
it("has a default Compression constructor", function() {
expect(Filer.FileSystem.adapters.Compression).to.be.a('function');
});
});
});

View File

@ -1,6 +1,7 @@
define(["Filer"], function(Filer) { var Filer = require('../..');
var expect = require('chai').expect;
describe("Filer.Errors", function() { describe("Filer.Errors", function() {
it("has expected errors", function() { it("has expected errors", function() {
expect(Filer.Errors).to.exist; expect(Filer.Errors).to.exist;
@ -132,5 +133,4 @@ define(["Filer"], function(Filer) {
expect(Filer.Errors[1001]).to.equal(Filer.Errors.EFILESYSTEMERROR); expect(Filer.Errors[1001]).to.equal(Filer.Errors.EFILESYSTEMERROR);
expect(Filer.Errors[1002]).to.equal(Filer.Errors.ENOATTR); expect(Filer.Errors[1002]).to.equal(Filer.Errors.ENOATTR);
}); });
});
}); });

View File

@ -1,6 +1,7 @@
define(["Filer"], function(Filer) { var Filer = require('../..');
var expect = require('chai').expect;
describe("Filer", function() { describe("Filer", function() {
it("is defined", function() { it("is defined", function() {
expect(typeof Filer).not.to.equal(undefined); expect(typeof Filer).not.to.equal(undefined);
}); });
@ -8,6 +9,4 @@ define(["Filer"], function(Filer) {
it("has FileSystem constructor", function() { it("has FileSystem constructor", function() {
expect(typeof Filer.FileSystem).to.equal('function'); expect(typeof Filer.FileSystem).to.equal('function');
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.appendFile', function() { describe('fs.appendFile', function() {
beforeEach(function(done) { beforeEach(function(done) {
util.setup(function() { util.setup(function() {
var fs = util.fs(); var fs = util.fs();
@ -125,5 +127,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.close', function() { describe('fs.close', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -25,6 +27,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.exists', function() { describe('fs.exists', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -55,5 +57,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.link', function() { describe('fs.link', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -67,6 +69,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.lseek', function() { describe('fs.lseek', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -159,6 +161,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.lstat', function() { describe('fs.lstat', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -46,6 +48,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.mkdir', function() { describe('fs.mkdir', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -44,6 +46,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,5 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
describe('fs.mknod', function() { var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.mknod', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -75,6 +78,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,9 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
var constants = require('../../src/constants.js');
describe('fs.open', function() { describe('fs.open', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -31,7 +34,6 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
it('should return an error when flagged for write and the path is a directory', function(done) { it('should return an error when flagged for write and the path is a directory', function(done) {
var fs = util.fs(); var fs = util.fs();
@ -81,7 +83,7 @@ define(["Filer", "util"], function(Filer, util) {
it('should return the argument value of the file descriptor index matching the value set by the first useable file descriptor constant', function(done) { it('should return the argument value of the file descriptor index matching the value set by the first useable file descriptor constant', function(done) {
var fs = util.fs(); var fs = util.fs();
var firstFD = require('src/constants').FIRST_DESCRIPTOR; var firstFD = constants.FIRST_DESCRIPTOR;
var fd1; var fd1;
fs.open('/file1', 'w+', function(error, fd) { fs.open('/file1', 'w+', function(error, fd) {
@ -104,6 +106,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.read', function() { describe('fs.read', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -57,6 +59,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.readdir', function() { describe('fs.readdir', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -53,6 +55,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.readlink', function() { describe('fs.readlink', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -42,6 +44,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.rename', function() { describe('fs.rename', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -45,6 +47,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.rmdir', function() { describe('fs.rmdir', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -96,6 +98,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe("fs", function() { describe("fs", function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -19,6 +21,4 @@ define(["Filer", "util"], function(Filer, util) {
done(); done();
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.stat', function() { describe('fs.stat', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -90,6 +92,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.stats', function() { describe('fs.stats', function() {
describe('#isFile()', function() { describe('#isFile()', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -243,5 +245,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.symlink', function() { describe('fs.symlink', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -42,6 +44,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.truncate', function() { describe('fs.truncate', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -185,5 +187,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.unlink', function() { describe('fs.unlink', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -80,6 +82,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.utimes', function() { describe('fs.utimes', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -168,12 +170,11 @@ define(["Filer", "util"], function(Filer, util) {
// Note: testing estimation as time may differ by a couple of milliseconds // Note: testing estimation as time may differ by a couple of milliseconds
// This number should be increased if tests are on slow systems // This number should be increased if tests are on slow systems
var delta = Date.now() - then; var delta = Date.now() - then;
expect(then - stat.atime).to.be.below(delta); expect(then - stat.atime).to.be.at.most(delta);
expect(then - stat.mtime).to.be.below(delta); expect(then - stat.mtime).to.be.at.most(delta);
done(); done();
}); });
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.watch', function() { describe('fs.watch', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -38,6 +40,4 @@ define(["Filer", "util"], function(Filer, util) {
if(error) throw error; if(error) throw error;
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.write', function() { describe('fs.write', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -57,6 +59,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.writeFile, fs.readFile', function() { describe('fs.writeFile, fs.readFile', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -99,6 +101,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('fs.xattr', function() { describe('fs.xattr', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -389,5 +391,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -0,0 +1,59 @@
var network = require('../../../src/network.js');
var expect = require('chai').expect;
describe('Network module', function() {
var uri;
if (typeof XMLHttpRequest === 'undefined') {
// Node context
uri = {
valid: 'http://localhost:1234/package.json',
invalid: 'booyah!',
notFound: 'http://localhost:1234/this-isnt-real'
}
} else {
// Browser context
uri = {
valid: '../package.json',
invalid: 'asdf://booyah!',
notFound: 'this-isnt-real'
};
}
it('should get an error when a non-existent path is specified', function(done) {
network.download(uri.notFound, function(error, data) {
expect(error).to.exist;
expect(error.code).to.eql(404);
expect(data).to.be.eql(null);
done();
});
});
if (typeof XMLHttpRequest === 'undefined') {
it('in nodejs, should get an error when an invalid URI is specified', function(done) {
network.download(uri.invalid, function(error, data) {
expect(error).to.exist;
expect(error.code).to.eql(null);
expect(error.message).to.exist;
expect(data).to.be.eql(null);
done();
});
});
} else {
it('in a browser, should throw an error when an invalid URI is specified', function(done) {
expect(function(){
network.download(uri.invalid, function() {});
}).to.throwError;
done();
});
}
it('should download a resource from the server', function(done) {
network.download(uri.valid, function(error, data) {
expect(error).not.to.exist;
expect(data).to.exist;
expect(data).to.have.length.above(0);
done();
});
});
});

View File

@ -0,0 +1,13 @@
define(["Filer", "util"], function(Filer, util) {
describe('Nodejs compatability', function() {
beforeEach(util.setup);
afterEach(util.cleanup);
it('module should be requireable', function() {
expect(function() {
var Filer = require('../../dist/filer_node.js');
}).to.not.throwError;
});
});
});

View File

@ -1,7 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../../..');
var util = require('../../../lib/test-utils.js');
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-mkdir.js", function() { var expect = require('chai').expect;
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-mkdir.js", function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -36,6 +37,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,7 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../../..');
var util = require('../../../lib/test-utils.js');
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-null-bytes.js", function() { var expect = require('chai').expect;
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-null-bytes.js", function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -58,5 +59,4 @@ define(["Filer", "util"], function(Filer, util) {
fn(); fn();
}); });
}); });
});
}); });

View File

@ -1,13 +1,13 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../../..');
var util = require('../../../lib/test-utils.js');
var expect = require('chai').expect;
/** /**
* NOTE: unlike node.js, which either doesn't give filenames (e.g., in case of * NOTE: unlike node.js, which either doesn't give filenames (e.g., in case of
* fd vs. path) for events, or gives only a portion thereof (e.g., basname), * fd vs. path) for events, or gives only a portion thereof (e.g., basname),
* we give full, abs paths always. * we give full, abs paths always.
*/ */
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-watch-recursive.js", function() {
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-watch-recursive.js", function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -33,6 +33,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,16 +1,16 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../../..');
var util = require('../../../lib/test-utils.js');
var expect = require('chai').expect;
/** /**
* NOTE: unlike node.js, which either doesn't give filenames (e.g., in case of * NOTE: unlike node.js, which either doesn't give filenames (e.g., in case of
* fd vs. path) for events, or gives only a portion thereof (e.g., basname), * fd vs. path) for events, or gives only a portion thereof (e.g., basname),
* we give full, abs paths always. * we give full, abs paths always.
*/ */
var filenameOne = '/watch.txt';
var filenameTwo = '/hasOwnProperty';
var filenameOne = '/watch.txt'; describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-watch.js", function() {
var filenameTwo = '/hasOwnProperty';
describe("node.js tests: https://github.com/joyent/node/blob/master/test/simple/test-fs-watch.js", function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -70,5 +70,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;
describe('path resolution', function() { describe('path resolution', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -221,6 +223,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,15 +1,10 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
if(!Filer.FileSystem.providers.IndexedDB.isSupported()) { if(!Filer.FileSystem.providers.IndexedDB.isSupported()) {
console.log("Skipping Filer.FileSystem.providers.IndexedDB tests, since IndexedDB isn't supported."); console.log("Skipping Filer.FileSystem.providers.IndexedDB tests, since IndexedDB isn't supported.");
return; } else {
}
if(navigator.userAgent.indexOf('PhantomJS') > -1) {
console.log("Skipping Filer.FileSystem.providers.IndexedDB tests, since PhantomJS doesn't support it.");
return;
}
describe("Filer.FileSystem.providers.IndexedDB", function() { describe("Filer.FileSystem.providers.IndexedDB", function() {
it("is supported -- if it isn't, none of these tests can run.", function() { it("is supported -- if it isn't, none of these tests can run.", function() {
expect(Filer.FileSystem.providers.IndexedDB.isSupported()).to.be.true; expect(Filer.FileSystem.providers.IndexedDB.isSupported()).to.be.true;
@ -150,4 +145,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); }

View File

@ -1,6 +1,7 @@
define(["Filer"], function(Filer) { var Filer = require('../../..');
var expect = require('chai').expect;
describe("Filer.FileSystem.providers.Memory", function() { describe("Filer.FileSystem.providers.Memory", function() {
it("is supported -- if it isn't, none of these tests can run.", function() { it("is supported -- if it isn't, none of these tests can run.", function() {
expect(Filer.FileSystem.providers.Memory.isSupported()).to.be.true; expect(Filer.FileSystem.providers.Memory.isSupported()).to.be.true;
}); });
@ -43,7 +44,6 @@ define(["Filer"], function(Filer) {
}); });
}); });
}); });
});
describe("open an Memory provider", function() { describe("open an Memory provider", function() {
it("should open a new Memory database", function(done) { it("should open a new Memory database", function(done) {
@ -142,6 +142,4 @@ define(["Filer"], function(Filer) {
}); });
}); });
}); });
});
}); });

View File

@ -1,5 +1,7 @@
define(["Filer"], function(Filer) { var Filer = require('../../..');
describe("Filer.FileSystem.providers", function() { var expect = require('chai').expect;
describe("Filer.FileSystem.providers", function() {
it("is defined", function() { it("is defined", function() {
expect(Filer.FileSystem.providers).to.exist; expect(Filer.FileSystem.providers).to.exist;
}); });
@ -23,5 +25,4 @@ define(["Filer"], function(Filer) {
it("has Fallback constructor", function() { it("has Fallback constructor", function() {
expect(Filer.FileSystem.providers.Fallback).to.be.a('function'); expect(Filer.FileSystem.providers.Fallback).to.be.a('function');
}); });
});
}); });

View File

@ -1,15 +1,10 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
if(!Filer.FileSystem.providers.WebSQL.isSupported()) { if(!Filer.FileSystem.providers.WebSQL.isSupported()) {
console.log("Skipping Filer.FileSystem.providers.WebSQL tests, since WebSQL isn't supported."); console.log("Skipping Filer.FileSystem.providers.WebSQL tests, since WebSQL isn't supported.");
return; } else {
}
if(navigator.userAgent.indexOf('PhantomJS') > -1) {
console.log("Skipping Filer.FileSystem.providers.WebSQL tests, since PhantomJS doesn't support it.");
return;
}
describe("Filer.FileSystem.providers.WebSQL", function() { describe("Filer.FileSystem.providers.WebSQL", function() {
it("is supported -- if it isn't, none of these tests can run.", function() { it("is supported -- if it isn't, none of these tests can run.", function() {
expect(Filer.FileSystem.providers.WebSQL.isSupported()).to.be.true; expect(Filer.FileSystem.providers.WebSQL.isSupported()).to.be.true;
@ -145,4 +140,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); }

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.cat', function() { describe('FileSystemShell.cat', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -79,6 +81,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.cd', function() { describe('FileSystemShell.cd', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -118,6 +120,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.env', function() { describe('FileSystemShell.env', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -108,6 +110,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.exec', function() { describe('FileSystemShell.exec', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -28,6 +30,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.ls', function() { describe('FileSystemShell.ls', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -182,6 +184,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.mkdirp', function() { describe('FileSystemShell.mkdirp', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -93,5 +95,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.rm', function() { describe('FileSystemShell.rm', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -133,6 +135,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,13 +1,15 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
function getTimes(fs, path, callback) { function getTimes(fs, path, callback) {
fs.stat(path, function(error, stats) { fs.stat(path, function(error, stats) {
if(error) throw error; if(error) throw error;
callback({mtime: stats.mtime, atime: stats.atime}); callback({mtime: stats.mtime, atime: stats.atime});
}); });
} }
describe('FileSystemShell.touch', function() { describe('FileSystemShell.touch', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -98,6 +100,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
});
}); });

View File

@ -1,6 +1,8 @@
define(["Filer", "util"], function(Filer, util) { var Filer = require('../../..');
var util = require('../../lib/test-utils.js');
var expect = require('chai').expect;
describe('FileSystemShell.wget', function() { describe('FileSystemShell.wget', function() {
beforeEach(util.setup); beforeEach(util.setup);
afterEach(util.cleanup); afterEach(util.cleanup);
@ -34,7 +36,7 @@ define(["Filer", "util"], function(Filer, util) {
it('should download the contents of a file from a url to default filename', function(done) { it('should download the contents of a file from a url to default filename', function(done) {
var fs = util.fs(); var fs = util.fs();
var shell = fs.Shell(); var shell = fs.Shell();
var url = "test-file.txt"; var url = typeof XMLHttpRequest === "undefined" ? "http://localhost:1234/tests/test-file.txt" : "/tests/test-file.txt";
var contents = "This is a test file used in some of the tests.\n"; var contents = "This is a test file used in some of the tests.\n";
shell.wget(url, function(err, path) { shell.wget(url, function(err, path) {
@ -54,7 +56,7 @@ define(["Filer", "util"], function(Filer, util) {
it('should download the contents of a file from a url to specified filename', function(done) { it('should download the contents of a file from a url to specified filename', function(done) {
var fs = util.fs(); var fs = util.fs();
var shell = fs.Shell(); var shell = fs.Shell();
var url = "test-file.txt"; var url = typeof XMLHttpRequest === "undefined" ? "http://localhost:1234/tests/test-file.txt" : "/tests/test-file.txt";
var contents = "This is a test file used in some of the tests.\n"; var contents = "This is a test file used in some of the tests.\n";
shell.wget(url, { filename: 'test-file.txt' }, function(err, path) { shell.wget(url, { filename: 'test-file.txt' }, function(err, path) {
@ -74,7 +76,7 @@ define(["Filer", "util"], function(Filer, util) {
it('should download the contents of a file from a url with query string', function(done) { it('should download the contents of a file from a url with query string', function(done) {
var fs = util.fs(); var fs = util.fs();
var shell = fs.Shell(); var shell = fs.Shell();
var url = "test-file.txt?foo"; var url = typeof XMLHttpRequest === "undefined" ? "http://localhost:1234/tests/test-file.txt?foo" : "/tests/test-file.txt?foo";
var contents = "This is a test file used in some of the tests.\n"; var contents = "This is a test file used in some of the tests.\n";
shell.wget(url, function(err, path) { shell.wget(url, function(err, path) {
@ -90,27 +92,4 @@ define(["Filer", "util"], function(Filer, util) {
}); });
}); });
}); });
it('should download the contents of a file from a url to specified filename, stripping : and /', function(done) {
var fs = util.fs();
var shell = fs.Shell();
var url = "test-file.txt?foo=:/";
var contents = "This is a test file used in some of the tests.\n";
shell.wget(url, function(err, path) {
if(err) throw err;
expect(path).to.equal('/test-file.txt?foo=');
fs.readFile(path, 'utf8', function(err, data) {
if(err) throw err;
expect(data).to.equal(contents);
done();
});
});
});
});
}); });

Some files were not shown because too many files have changed in this diff Show More