<commit_before>/*
 * dependencies.js: Common utility functions for building complete dependency trees.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var path = require('path'),
    semver = require('semver'),
    utile = require('utile'),
    wtfos = require('wtfos'),
    async = utile.async,
    validate = require('./validate');

//
// ### function dependencies (options, callback)
// #### @options {Object} {Options for calculating dependencies}
// ####   @options.systems {Array|Object} List of systems to create dependency tree for.
// ####   @options.client  {Client}       API Client for fetching systems.
// ####   @options.os      {string}       Target OS to calculate dependencies for.
// #### @callback {function} Continuation to respond to when complete.
//
// Creates a dependency tree for the specified `systems`.
//
var dependencies = module.exports = function (options, callback) {
  var systems = options.systems,
      client  = options.client,
      os      = options.os,
      tree    = {};

  //
  // Helper function which builds the subtree for
  // `name` and inserts it into the parent `tree`.
  //
  function updateTree(parts, next) {
    var name    = parts[0],
        version = parts[1];

    client.get(name, function (err, system) {
      if (err) {
        return next(err)
      }

      var versions = Object.keys(system.versions),
          required = version || "*",
          invalid,
          osdeps;

      version = semver.maxSatisfying(
        versions,
        version || system.version
      ) || version;

      if (!system.versions[version]) {
        return next(new Error('Could not resolve dependency: ' + [name, version].join('@')));
      }

      system              = system.versions[version],
      system.version      = version;
      system.required     = required;
      system.runlist      = system.runlist || [];
      system.dependencies = utile.mixin(
        system.dependencies || {},
        osDependencies(system, os)
      );

      if ((!system.runlist || !system.runlist.length) && system.dependencies) {
        system.runlist = Object.keys(system.dependencies);
      }

      invalid = validate(system, os);
      if (invalid) {
        return next(invalid);
      }

      tree[name] = system;

      if ((!system.dependencies || !Object.keys(system.dependencies).length)
          && (!system.os || !system.os[os])) {
        return next();
      }

      async.parallel({
        dependencies: async.apply(dependencies, {
          systems: system.dependencies,
          client: client,
          os: os
        }),
        remoteDependencies: function remoteDeps(next) {
          if (!system.remoteDependencies) {
            return next();
          }

          dependencies({
            systems: system.remoteDependencies,
            client: client
          }, next);
        }
      }, function (err, subtrees) {
        if (err) {
          return next(err);
        }

        ['dependencies', 'remoteDependencies'].forEach(function (key) {
          if (subtrees[key]) {
            tree[name][key] = subtrees[key];
          }
        });

        next();
      });
    });
  }

  async.forEach(dependencies.systemNames(systems), updateTree, function (err) {
    return err
      ? callback(err)
      : callback(null, tree);
  });
};

//
// ### function maxSatisfying (callback)
// #### @options {Object} Options for calculating maximum satisfying set.
// ####   @options.system {Object|string} System to calculate against
// ####   @options.client {Client} API client to fetch systems from.
// #### @callback {function} Continuation to respond to
// Returns an object containing the latest versions which
// satisfy the dependency needs the system installed
// with the given name
//
// Algorithm:
//   1. Get the current OS with wtfos
//   2. Build the dependency tree for the system and
//      the current OS
//   3. Reduce the dependency tree to the aggregate semver
//      satisfying string, the "required satisfying set".
//   4. Get latest for all installed systems
//   5. Reduce latest against the satisfying set.
//
dependencies.maxSatisfying = function (options, callback) {
  var system = options.system,
      client = options.client;

  async.waterfall([
    //
    // 1. Get the current OS with wtfos
    //
    async.apply(wtfos),
    //
    // 3. Build the dependency tree for those systems and
    //    the current OS
    // 4. Reduce the dependency tree to the aggregate semver
    //    satisfying string, the "satisfying set".
    //
    function satisfyingSet(os, next) {
      var parent = system.name || system;

      //
      // Recursively adds all dependencies in the
      // system dependency subtree to the satisfying set.
      //
      function addSatisfying(dep, set) {
        var name = dep.name;

        set[name] =  set[name] ? (set[name] + ' ') : '';
        set[name] += dep.required;

        if (dep.dependencies && Object.keys(dep.dependencies).length) {
          set = addSatisfying(dep.dependencies, set);
        }

        return set;
      }

      os = (os.distribution && os.distribution.toLowerCase()) || null;
      dependencies(parent, os, function (err, dep) {
        if (err) {
          return next(err);
        }

        next(null, Object.keys(dep[parent].dependencies).reduce(function (set, name) {
          return addSatisfying(dep[parent].dependencies[name], set);
        }, {}));
      });
    },
    //
    // 5. Get latest for all installed systems
    //
    function getLatest(set, done) {
      async.reduce(
        Object.keys(set),
        {},
        function getSystem(latest, name, next) {
          client.get(name, function (err, system) {
            if (err) {
              return next(err);
            }

            latest[name] = system;
            next(null, latest);
          });
        },
        function (err, latest) {
          return !err
            ? done(null, latest, set)
            : done(err);
        }
      );
    }
  ], function satisfy(err, latest, required) {
    if (err) {
      return callback(err);
    }

    callback(null, Object.keys(required)
      .reduce(function (sat, name) {
        sat[name] = semver.maxSatisfying(
          Object.keys(latest[name].versions),
          required[name]
        );
        return sat;
      }, {}));
  });
};

//
// ### function systemNames(names)
// #### @names {string|Array|Object}
//
// Helper function with returns a normalized Array of
// Arrays representing the `<name, version>` pair
// for the specified `names`.
//
dependencies.systemNames = function (names) {
  if (typeof names === 'string') {
    return [names.split('@')];
  }
  else if (Array.isArray(names)) {
    return names.map(function (system) {
      return system.name || system.split('@');
    });
  }

  return Object.keys(names).map(function (name) {
    return [name, names[name] || '*'];
  });
};

//
// ### function osDependencies (system, os)
//
// Helper function which returns a dependency set for the given
// `system` and `os`.
//
function osDependencies(system, os) {
  if (!os || typeof system.os !== 'object') {
    return {};
  }

  //
  // If `system.dependencies` and `system.runlist`
  // are not defined assume that the object is a single dependency
  //
  if (!system.os[os].dependencies && !system.os[os].runlist) {
    return system.os[os];
  }

  return system.os[os].dependencies || {};
}<commit_msg>[fix] Update use of `systemJson.dependencies()` to new method signature.<commit_after>/*
 * dependencies.js: Common utility functions for building complete dependency trees.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var path = require('path'),
    semver = require('semver'),
    utile = require('utile'),
    wtfos = require('wtfos'),
    async = utile.async,
    validate = require('./validate');

//
// ### function dependencies (options, callback)
// #### @options {Object} {Options for calculating dependencies}
// ####   @options.systems {Array|Object} List of systems to create dependency tree for.
// ####   @options.client  {Client}       API Client for fetching systems.
// ####   @options.os      {string}       Target OS to calculate dependencies for.
// #### @callback {function} Continuation to respond to when complete.
//
// Creates a dependency tree for the specified `systems`.
//
var dependencies = module.exports = function (options, callback) {
  var systems = options.systems,
      client  = options.client,
      os      = options.os,
      tree    = {};

  //
  // Helper function which builds the subtree for
  // `name` and inserts it into the parent `tree`.
  //
  function updateTree(parts, next) {
    var name    = parts[0],
        version = parts[1];

    client.get(name, function (err, system) {
      if (err) {
        return next(err)
      }

      var versions = Object.keys(system.versions),
          required = version || "*",
          invalid,
          osdeps;

      version = semver.maxSatisfying(
        versions,
        version || system.version
      ) || version;

      if (!system.versions[version]) {
        return next(new Error('Could not resolve dependency: ' + [name, version].join('@')));
      }

      system              = system.versions[version],
      system.version      = version;
      system.required     = required;
      system.runlist      = system.runlist || [];
      system.dependencies = utile.mixin(
        system.dependencies || {},
        osDependencies(system, os)
      );

      if ((!system.runlist || !system.runlist.length) && system.dependencies) {
        system.runlist = Object.keys(system.dependencies);
      }

      invalid = validate(system, os);
      if (invalid) {
        return next(invalid);
      }

      tree[name] = system;

      if ((!system.dependencies || !Object.keys(system.dependencies).length)
          && (!system.os || !system.os[os])) {
        return next();
      }

      async.parallel({
        dependencies: async.apply(dependencies, {
          systems: system.dependencies,
          client: client,
          os: os
        }),
        remoteDependencies: function remoteDeps(next) {
          if (!system.remoteDependencies) {
            return next();
          }

          dependencies({
            systems: system.remoteDependencies,
            client: client
          }, next);
        }
      }, function (err, subtrees) {
        if (err) {
          return next(err);
        }

        ['dependencies', 'remoteDependencies'].forEach(function (key) {
          if (subtrees[key]) {
            tree[name][key] = subtrees[key];
          }
        });

        next();
      });
    });
  }

  async.forEach(dependencies.systemNames(systems), updateTree, function (err) {
    return err
      ? callback(err)
      : callback(null, tree);
  });
};

//
// ### function maxSatisfying (callback)
// #### @options {Object} Options for calculating maximum satisfying set.
// ####   @options.system {Object|string} System to calculate against
// ####   @options.client {Client} API client to fetch systems from.
// #### @callback {function} Continuation to respond to
// Returns an object containing the latest versions which
// satisfy the dependency needs the system installed
// with the given name
//
// Algorithm:
//   1. Get the current OS with wtfos
//   2. Build the dependency tree for the system and
//      the current OS
//   3. Reduce the dependency tree to the aggregate semver
//      satisfying string, the "required satisfying set".
//   4. Get latest for all installed systems
//   5. Reduce latest against the satisfying set.
//
dependencies.maxSatisfying = function (options, callback) {
  var system = options.system,
      client = options.client;

  async.waterfall([
    //
    // 1. Get the current OS with wtfos
    //
    async.apply(wtfos),
    //
    // 3. Build the dependency tree for those systems and
    //    the current OS
    // 4. Reduce the dependency tree to the aggregate semver
    //    satisfying string, the "satisfying set".
    //
    function satisfyingSet(os, next) {
      var parent = system.name || system;

      //
      // Recursively adds all dependencies in the
      // system dependency subtree to the satisfying set.
      //
      function addSatisfying(dep, set) {
        var name = dep.name;

        set[name] =  set[name] ? (set[name] + ' ') : '';
        set[name] += dep.required;

        if (dep.dependencies && Object.keys(dep.dependencies).length) {
          set = addSatisfying(dep.dependencies, set);
        }

        return set;
      }

      os = (os.distribution && os.distribution.toLowerCase()) || null;
      dependencies({
        systems: parent,
        client: client,
        os: os
      }, function (err, dep) {
        if (err) {
          return next(err);
        }

        next(null, Object.keys(dep[parent].dependencies).reduce(function (set, name) {
          return addSatisfying(dep[parent].dependencies[name], set);
        }, {}));
      });
    },
    //
    // 5. Get latest for all installed systems
    //
    function getLatest(set, done) {
      async.reduce(
        Object.keys(set),
        {},
        function getSystem(latest, name, next) {
          client.get(name, function (err, system) {
            if (err) {
              return next(err);
            }

            latest[name] = system;
            next(null, latest);
          });
        },
        function (err, latest) {
          return !err
            ? done(null, latest, set)
            : done(err);
        }
      );
    }
  ], function satisfy(err, latest, required) {
    if (err) {
      return callback(err);
    }

    callback(null, Object.keys(required)
      .reduce(function (sat, name) {
        sat[name] = semver.maxSatisfying(
          Object.keys(latest[name].versions),
          required[name]
        );
        return sat;
      }, {}));
  });
};

//
// ### function systemNames(names)
// #### @names {string|Array|Object}
//
// Helper function with returns a normalized Array of
// Arrays representing the `<name, version>` pair
// for the specified `names`.
//
dependencies.systemNames = function (names) {
  if (typeof names === 'string') {
    return [names.split('@')];
  }
  else if (Array.isArray(names)) {
    return names.map(function (system) {
      return system.name || system.split('@');
    });
  }

  return Object.keys(names).map(function (name) {
    return [name, names[name] || '*'];
  });
};

//
// ### function osDependencies (system, os)
//
// Helper function which returns a dependency set for the given
// `system` and `os`.
//
function osDependencies(system, os) {
  if (!os || typeof system.os !== 'object') {
    return {};
  }

  //
  // If `system.dependencies` and `system.runlist`
  // are not defined assume that the object is a single dependency
  //
  if (!system.os[os].dependencies && !system.os[os].runlist) {
    return system.os[os];
  }

  return system.os[os].dependencies || {};
}<|endoftext|>


<commit_before>/**
 * DirectedEdge Client for Node.js
 * @author Josh Smith
 * @todo Implement call throttling to maintain
    10,000 calls/day and 10 calls/sec
 */

var QueryString = require('querystring'),
    https = require('https'),
		builder = require('xmlbuilder'),
		request = require('request'),
		xml2js = require('xml2js');

function emptyFn () {}

var DirectedEdge = exports.DirectedEdge = function(username,password,database) {
		// Your database name is currently the same as your user name
		if (typeof database === "undefined") database = username;

		var hostname = 'webservices.directededge.com';
		var version = '/api/v1/';
		var auth = username + ':' + password;

		var url = 'https://' + auth + '@' + hostname + version + database + '/';

    this.post = function (path,xml,callback) {
				url += path;

        request.post({url:url, body:xml}, function(e, r, body) {
					if(e) {
					} else {
						console.log(body);
					}
				});
    }

    this.get = function (path,callback) {
				url += path;

				console.log(url);

        request.get({url:url}, function(e, r, body) {
					if(e) {

					} else {
						var parser = new xml2js.Parser();
						parser.parseString(body, function(err, result) {
							var body = JSON.stringify(result);
							callback(e, body, r);
						});
					}
				});
    }
}

/////////////////////////////////////////////////////
/** Database Resources                            **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge
 * Dumps the entire database to XML
 * DO THIS SPARINGLY
 * @see http://developer.directededge.com/article/REST_API#HTTP_GET
 */
DirectedEdge.prototype.getDatabase = function (itemId,callback) {
		var path = itemId;

    var path = QueryString.stringify(path);
		this.get('', callback);
}

/////////////////////////////////////////////////////
/** Item Resources		                            **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge: Item Resources
 * Update a given item with a new link
 * @see http://developer.directededge.com/article/REST_API#Item_resource
 */
DirectedEdge.prototype.updateItemWithLink = function (itemId,linkName,callback) {
		var path = itemId + '/add';

		var doc = builder.create();

    doc.begin('xml')
			.att('version', '1.0').att('encoding', 'utf-8')
			.ele('directedege')
				.att('version', '0.1')
				.ele('item')
					.att('id', itemId)
						.ele('link')
						.txt(linkName);

		xml = doc.toString();

    path = QueryString.stringify(path);
    this.post(path,xml,callback);
}

DirectedEdge.prototype.getItem = function (itemId,callback) {
		var path = encodeURIComponent(itemId);
		this.get(path, callback);
}

/////////////////////////////////////////////////////
/** Related and Recommended Resources             **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge: Related and Recommended Resources
 * Gets similar things to the item
 * @see http://developer.directededge.com/article/REST_API#Related_.2F_recommended_resources
 */
DirectedEdge.prototype.getRelated = function (itemId,params,callback) {
	  if (typeof params == 'function') {
	      callback = params;
	      params = [];
	  }

    var path = encodeURIComponent(itemId);
		var qs = QueryString.stringify(params);
		this.get(path + '/related?' + qs, callback);
}

/**
 * DirectedEdge: Related and Recommended Resources, cont.
 * Gets recommended items for the user
 * @see http://developer.directededge.com/article/REST_API#Related_.2F_recommended_resources
 */
DirectedEdge.prototype.getRecommended = function (userId,params,callback) {
	  if (typeof params == 'function') {
	      callback = params;
	      params = [];
	  }

    var path = encodeURIComponent(userId);
		var qs = QueryString.stringify(params);
		this.get(path + '/recommended?' + qs, callback);
}
<commit_msg>Added in error handling for DirectedEdge.post and DirectedEdge.get Signed-off-by: Josh Smith <joshdotsmith@gmail.com><commit_after>/**
 * DirectedEdge Client for Node.js
 * @author Josh Smith
 * @todo Implement call throttling to maintain
    10,000 calls/day and 10 calls/sec
 */

var QueryString = require('querystring'),
    https = require('https'),
		builder = require('xmlbuilder'),
		request = require('request'),
		xml2js = require('xml2js');

function emptyFn () {}

var DirectedEdge = exports.DirectedEdge = function(username,password,database) {
		// Your database name is currently the same as your user name
		if (typeof database === "undefined") database = username;

		var hostname = 'webservices.directededge.com';
		var version = '/api/v1/';
		var auth = username + ':' + password;

		var url = 'https://' + auth + '@' + hostname + version + database + '/';

    this.post = function (path,xml,callback) {
				url += path;

        request.post({url:url, body:xml}, function(e, r, body) {
					if(e) {
						if (typeof e == 'string')
							e = JSON.parse(e);
						else if (typeof e.data == 'string')
							e.data = JSON.parse(e.data);
					}

					callback(e, body, r);
				});
    }

    this.get = function (path,callback) {
				url += path;

				console.log(url);

        request.get({url:url}, function(e, r, body) {
					if(e) {
						if (typeof e == 'string')
							e = JSON.parse(e);
						else if (typeof e.data == 'string')
							e.data = JSON.parse(e.data);
					} else {
						var parser = new xml2js.Parser();
						parser.parseString(body, function(err, result) {
							var body = JSON.stringify(result);
							callback(e, body, r);
						});
					}
				});
    }
}

/////////////////////////////////////////////////////
/** Database Resources                            **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge
 * Dumps the entire database to XML
 * DO THIS SPARINGLY
 * @see http://developer.directededge.com/article/REST_API#HTTP_GET
 */
DirectedEdge.prototype.getDatabase = function (itemId,callback) {
		var path = itemId;

    var path = QueryString.stringify(path);
		this.get('', callback);
}

/////////////////////////////////////////////////////
/** Item Resources		                            **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge: Item Resources
 * Update a given item with a new link
 * @see http://developer.directededge.com/article/REST_API#Item_resource
 */
DirectedEdge.prototype.updateItemWithLink = function (itemId,linkName,callback) {
		var path = itemId + '/add';

		var doc = builder.create();

    doc.begin('xml')
			.att('version', '1.0').att('encoding', 'utf-8')
			.ele('directedege')
				.att('version', '0.1')
				.ele('item')
					.att('id', itemId)
						.ele('link')
						.txt(linkName);

		xml = doc.toString();

    path = QueryString.stringify(path);
    this.post(path,xml,callback);
}

DirectedEdge.prototype.getItem = function (itemId,callback) {
		var path = encodeURIComponent(itemId);
		this.get(path, callback);
}

/////////////////////////////////////////////////////
/** Related and Recommended Resources             **/
/////////////////////////////////////////////////////

/**
 * DirectedEdge: Related and Recommended Resources
 * Gets similar things to the item
 * @see http://developer.directededge.com/article/REST_API#Related_.2F_recommended_resources
 */
DirectedEdge.prototype.getRelated = function (itemId,params,callback) {
	  if (typeof params == 'function') {
	      callback = params;
	      params = [];
	  }

    var path = encodeURIComponent(itemId);
		var qs = QueryString.stringify(params);
		this.get(path + '/related?' + qs, callback);
}

/**
 * DirectedEdge: Related and Recommended Resources, cont.
 * Gets recommended items for the user
 * @see http://developer.directededge.com/article/REST_API#Related_.2F_recommended_resources
 */
DirectedEdge.prototype.getRecommended = function (userId,params,callback) {
	  if (typeof params == 'function') {
	      callback = params;
	      params = [];
	  }

    var path = encodeURIComponent(userId);
		var qs = QueryString.stringify(params);
		this.get(path + '/recommended?' + qs, callback);
}
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 *
 */

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(["require", "deepjs/deep"], function(require, deep){
	deep.compose.dom = deep.compose.dom || {};
	var DomComposer = deep.compose.dom.Composer = new deep.Composer(deep.compose.dom);	// create composer manager for namespace deep.sheet
	var Args = deep.Arguments;
	DomComposer.add("inPlaceEditable", "after", function() {
		return function(entry, options) {
			console.log("In place editable enhancement")
			return Args([entry, options]);
		};
	});
	DomComposer.add("hide", "after", function() {
		return function(entry, options) {
			// console.log("dom hide")
			deep.$(entry).hide();
			return Args([entry, options]);
		};
	});
	DomComposer.add("show", "after", function() {
		return function(entry, options) {
			// console.log("dom show")
			deep.$(entry).show();
			return Args([entry, options]);
		};
	});
	DomComposer.add("fadeIn", "after", function(ms) {
		return function(entry, options) {
			deep.$(entry).fadeIn(ms);
			return Args([entry, options]);
		};
	});
	DomComposer.add("click", "after", function(handler, args) {
		// console.log('csheeter click 1 : ', handler, args);
		return function(entry, options) {
			if(deep.context("isServer"))
				return Args([entry, options]);
			// console.log("sheeter.click : entry, options, handler, args : ", entry, options, handler, args)
			var $ = deep.$();
			var self = this;
			$(entry).click(function(e){
				if(typeof handler === 'function')
					return handler.call(self, this, e);
				if(e && e.preventDefault)
					e.preventDefault();
				self[handler].apply(self, args || []);
				return false;
			});
		};
	});
	DomComposer.add("each", "after", function(handler) {
		return function(entry, context) {
			var $ = deep.$(),
				promises = [];
			var self = this;
			$(entry).each(function(){
				promises.push(handler.call(self, this));
			});
			return deep.all(promises)
			.when(Args([entry, context]))
		};
	});
	DomComposer.add("find", "after", function(selector) {
		return function(entry, context) {
			return Args([deep.$(entry).find(selector), context]);
		};
	});
	//____________________________________________________________________ STILL TO IMPLEMENT AND TEST
	DomComposer.add("control", "after", function(from) {
		return function(node, context) {
			var $ = deep.$(),
				controller = this;
			var d = deep.nodes({});
			return d.up.apply(d, from.split(","))
			.done(function(ctrl) {
				if (!ctrl)
					return deep.errors.Internal("dp-control has retrieved nothing");
				var config = ctrl.config || {};
				if (config.scope && config.scope != "both")
					if (deep.context("isServer")) {
						if (config.scope != "server")
							return;
					}
					else if (config.scope != "browser")
						return;
				if(controller && controller.addSubControlled)
					controller.addSubControlled(ctrl);
				ctrl.placed = function() {
					return node;
				};
				return ctrl.refresh();
			})
			.when(Args([node, context]));
		};
	});
	DomComposer.add("from", "after", function(path) {
		return function(node, context) {
			var $ = deep.$();
			var controller = this;
			return deep.getAll(path.split(","))
				.done(function(result) {
					//console.log("dp-from ", from," : get : ", result)
					if (typeof result === 'function')
						$(node).html(result({
							_ctrl: controller
						}));
					else
						$(node).html(result);
				});
		};
	});

	return deep.compose.dom;
});<commit_msg>add compose.dom.validate, work on compose/dom.click, remove compose.dom.control + clean<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 *
 */

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(["require", "deepjs/deep"], function(require, deep){
	deep.compose.dom = deep.compose.dom || {};
	var DomComposer = deep.compose.dom.Composer = new deep.Composer(deep.compose.dom);	// create composer manager for namespace deep.sheet
	var Args = deep.Arguments;
	DomComposer.add("inPlaceEditable", "after", function() {
		return function(entry, renderNode) {
			console.log("In place editable enhancement")
			return Args([entry, renderNode]);
		};
	});
	DomComposer.add("hide", "after", function() {
		return function(entry, renderNode) {
			deep.$(entry).hide();
			return Args([entry, renderNode]);
		};
	});
	DomComposer.add("validate", "after", function(map, schema) {
		return function(entry, renderNode) {
			var $ = deep.$(),
				obj = {};
			for (var i in map){
				var input = $(renderNode.placed).find(map[i]),
					val = $(input).val();
				deep.utils.toPath(obj, i, val, ".");
			}
			var report = deep.validate(obj, schema);
			if(!report.valid)
			{
				deep.log("error : ", report)
				return deep.errors.PreconditionFail("composer.dom.validate", report);
			}
			return obj;
		};
	});
	DomComposer.add("show", "after", function() {
		return function(entry, renderNode) {
			// console.log("dom show")
			deep.$(entry).show();
			return Args([entry, renderNode]);
		};
	});
	DomComposer.add("fadeIn", "after", function(ms) {
		return function(entry, renderNode) {
			deep.$(entry).fadeIn(ms);
			return Args([entry, renderNode]);
		};
	});
	DomComposer.add("fadeIn", "after", function(ms) {
		return function(entry, renderNode) {
			deep.$(entry).fadeIn(ms);
			return Args([entry, renderNode]);
		};
	});
	DomComposer.add("click", "after", function() {
		var args = Array.prototype.slice.call(arguments);
		return function(entry, renderNode) {
			if(deep.context("isServer"))
				return Args([entry, renderNode]);
			var self = this, handler = args.shift();
			console.log('click : ', self, handler, args);
			deep.$(entry)
			.click(function(e){
				var ar = [this, renderNode].concat(args);
				if(typeof handler === 'function')
					return handler.apply(self, ar);
				self[handler].apply(self, ar);
				if(e && e.preventDefault)
					e.preventDefault();
				return false;
			});
		};
	});
	DomComposer.add("each", "after", function(handler) {
		return function(entry, renderNode) {
			var $ = deep.$(),
				promises = [];
			var self = this;
			$(entry).each(function(){
				promises.push(handler.call(self, this));
			});
			return deep.all(promises)
			.when(Args([entry, renderNode]))
		};
	});
	DomComposer.add("find", "after", function(selector) {
		return function(entry, renderNode) {
			return Args([deep.$(entry).find(selector), renderNode]);
		};
	});
	//____________________________________________________________________ STILL TO IMPLEMENT AND TEST
	DomComposer.add("from", "after", function(path) {
		return function(node, renderNode) {
			var $ = deep.$();
			var controller = this;
			return deep.getAll(path.split(","))
				.done(function(result) {
					//console.log("dp-from ", from," : get : ", result)
					if (typeof result === 'function')
						$(node).html(result({
							_ctrl: controller
						}));
					else
						$(node).html(result);
				})
				.when(Args([node, renderNode]));
		};
	});

	return deep.compose.dom;
});<|endoftext|>


<commit_before>'use strict';

/* jshint node: true */

var Dropbox = require('dropbox');
var fs      = require('fs');
var os      = require('os');
var client  = null;
var folder  = null;

/**
 * Create a new Dropbox Client with the given credentials as well as the cached
 * oAuth token.
 * @param {!object] options
 * @return {Dropbox.Client}
 */
exports.connect = function (options) {
  options.token = fs.readFileSync(__dirname + '/../.oauth-token').toString('UTF-8').trim();
  client = new Dropbox.Client(options);

  return client;
};

/**
 * Set the name of the directory to store files in.
 * @param {!string} prefix
 */
exports.setDirectory = function (prefix) {
  folder = prefix;
};

/**
 * Transmit a file to Dropbox.
 * @param {!string} localFile
 * @param {!function(err, response)} callback
 */
exports.send = function (localFile, callback) {
  var remoteFile = '/' + os.hostname() + '/' + folder + '/' + localFile + '.tar.gz';

  fs.open('/tmp/' + localFile + '.tar.gz', 'r', function (err, fd) {
    var stats     = fs.fstatSync(fd);
    var chunkSize = 1024 * 1024; // 1 MB
    var buffer    = new Buffer(chunkSize);
    var chunks    = Math.ceil(stats.size / (1024 * 1024));
    var chunk     = 0;

    function next (err, cursor) {
      if (chunk < chunks) {
        fs.readSync(fd, buffer, 0, chunkSize, chunk * chunkSize);

        client.resumableUploadStep(buffer, cursor, next);

        chunk++;
      } else {
        client.resumableUploadFinish(remoteFile, cursor, callback);
      }
    }

    next(null, false);
  });
};

/**
 * Remove old files that exceed the number of backups to keep.
 * @param {!integer} max
 * @param {!function(err, filesRemoved)} callback
 */
exports.cleanOld = function (max, callback) {
  var remoteDir = '/' + os.hostname() + '/' + folder;

  client.readdir(remoteDir, function (err, files) {
    // If we haven't hit the file limit, do nothing
    if (files.length < max || err) {
      callback(err, []);
    }

    // Sort by file name
    files = files.sort(function (a, b) { return a > b ? 1 : -1 });

    // How many do we need to remove?
    files = files.slice(0, files.length - max);

    // Keep track of our callbacks
    var asyncCounter = 0;

    // Remove them
    files.forEach(function (f) {
      client.unlink(remoteDir + '/' + f, function () {
        asyncCounter++;

        if (asyncCounter >= files.length) {
          callback(err, files);
        }
      });
    });
  });
};
<commit_msg>Don't round up the size of the last chunk<commit_after>'use strict';

/* jshint node: true */

var Dropbox = require('dropbox');
var fs      = require('fs');
var os      = require('os');
var client  = null;
var folder  = null;

/**
 * Create a new Dropbox Client with the given credentials as well as the cached
 * oAuth token.
 * @param {!object] options
 * @return {Dropbox.Client}
 */
exports.connect = function (options) {
  options.token = fs.readFileSync(__dirname + '/../.oauth-token').toString('UTF-8').trim();
  client = new Dropbox.Client(options);

  return client;
};

/**
 * Set the name of the directory to store files in.
 * @param {!string} prefix
 */
exports.setDirectory = function (prefix) {
  folder = prefix;
};

/**
 * Transmit a file to Dropbox.
 * @param {!string} localFile
 * @param {!function(err, response)} callback
 */
exports.send = function (localFile, callback) {
  var remoteFile = '/' + os.hostname() + '/' + folder + '/' + localFile + '.tar.gz';

  fs.open('/tmp/' + localFile + '.tar.gz', 'r', function (err, fd) {
    var stats     = fs.fstatSync(fd);
    var chunkSize = 1024 * 1024; // 1 MB
    var chunks    = Math.ceil(stats.size / (1024 * 1024));
    var chunk     = 0;

    function next (err, cursor) {
      if (chunk < chunks) {
        var buffer = new Buffer(Math.min(stats.size, chunkSize));
        fs.readSync(fd, buffer, 0, chunkSize, chunk * chunkSize);

        client.resumableUploadStep(buffer, cursor, next);

        chunk++;
      } else {
        client.resumableUploadFinish(remoteFile, cursor, callback);
      }
    }

    next(null, false);
  });
};

/**
 * Remove old files that exceed the number of backups to keep.
 * @param {!integer} max
 * @param {!function(err, filesRemoved)} callback
 */
exports.cleanOld = function (max, callback) {
  var remoteDir = '/' + os.hostname() + '/' + folder;

  client.readdir(remoteDir, function (err, files) {
    // If we haven't hit the file limit, do nothing
    if (files.length < max || err) {
      callback(err, []);
    }

    // Sort by file name
    files = files.sort(function (a, b) { return a > b ? 1 : -1 });

    // How many do we need to remove?
    files = files.slice(0, files.length - max);

    // Keep track of our callbacks
    var asyncCounter = 0;

    // Remove them
    files.forEach(function (f) {
      client.unlink(remoteDir + '/' + f, function () {
        asyncCounter++;

        if (asyncCounter >= files.length) {
          callback(err, files);
        }
      });
    });
  });
};
<|endoftext|>


<commit_before>(function(dust){

/* make a safe version of console if it is not available
 * currently supporting:
 *   _console.log
 * */
var _console = (typeof console !== 'undefined')? console: {
  log: function(){
     /* a noop*/
   }
};

function isSelect(context) {
  var value = context.current();
  return typeof value === "object" && value.isSelect === true;
}

function filter(chunk, context, bodies, params, filter) {
  var params = params || {},
      actual, expected;
  if (params.key) {
    actual = context.get(params.key);
  } else if (isSelect(context)) {
    actual = context.current().value;
    if (context.current().isResolved) {
      filter = function() { return false; };
    }
  } else {
    throw "No key specified for filter and no key found in context from select statement";
  }
  expected = helpers.tap(params.value, chunk, context);
  if (filter(expected, coerce(actual, params.type, context))) {
    if (isSelect(context)) {
      context.current().isResolved = true;
    }
    return chunk.render(bodies.block, context);
  } else if (bodies['else']) {
    return chunk.render(bodies['else'], context);
  }

  return chunk.write('');
}

function coerce (value, type, context) {
  if (value) {
    switch (type || typeof(value)) {
      case 'number': return +value;
      case 'string': return String(value);
      case 'boolean': return Boolean(value);
      case 'date': return new Date(value);
      case 'context': return context.get(value);
    }
  }

  return value;
}

var helpers = {

  sep: function(chunk, context, bodies) {
    if (context.stack.index === context.stack.of - 1) {
      return chunk;
    }
    return bodies.block(chunk, context);
  },

  idx: function(chunk, context, bodies) {
    return bodies.block(chunk, context.push(context.stack.index));
  },
  contextDump: function(chunk, context, bodies) {
    _console.log(JSON.stringify(context.stack));
    return chunk;
  },// Utility helping to resolve dust references in the given chunk
  tap: function( input, chunk, context ){
    // return given input if there is no dust reference to resolve
    var output = input;
    // dust compiles a string to function, if there are references
    if( typeof input === "function"){
      output = '';
      chunk.tap(function(data){
        output += data;
        return '';
      }).render(input, context).untap();
      if( output === '' ){
        output = false;
      }
    }
    return output;
  },

  "if": function( chunk, context, bodies, params ){
    if( params && params.cond ){
      var cond = params.cond;
      cond = this.tap(cond, chunk, context);
      // eval expressions with no dust references
      if( eval( cond ) ){
       return chunk.render( bodies.block, context );
      }
      if( bodies['else'] ){
       return chunk.render( bodies['else'], context );
      }
    }
    // no condition
    else {
      _console.log( "No expression given!" );
    }
    return chunk;
  },
  select: function(chunk, context, bodies, params) {
    if( params && params.key){
      var key = params.key;
      key = this.tap(key, chunk, context);
      if( key ){
        return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, value: context.get(key) }));
      }
      return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, value: context.get(params.key) }));
    }
    // no key
    else {
      _console.log( "No expression given!" );
    }
    return chunk;
  },

  eq: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual === expected; });
  },

  lt: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual < expected; });
  },

  lte: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual <= expected; });
  },

  gt: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual > expected; });
  },

  gte: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual >= expected; });
  },

  "else": function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return true; });
  }
};

dust.helpers = helpers;

})(typeof exports !== 'undefined' ? exports : getGlobal());
<commit_msg>error message updated<commit_after>(function(dust){

/* make a safe version of console if it is not available
 * currently supporting:
 *   _console.log
 * */
var _console = (typeof console !== 'undefined')? console: {
  log: function(){
     /* a noop*/
   }
};

function isSelect(context) {
  var value = context.current();
  return typeof value === "object" && value.isSelect === true;
}

function filter(chunk, context, bodies, params, filter) {
  var params = params || {},
      actual, expected;
  if (params.key) {
    actual = context.get(params.key);
  } else if (isSelect(context)) {
    actual = context.current().value;
    if (context.current().isResolved) {
      filter = function() { return false; };
    }
  } else {
    throw "No key specified for filter and no key found in context from select statement";
  }
  expected = helpers.tap(params.value, chunk, context);
  if (filter(expected, coerce(actual, params.type, context))) {
    if (isSelect(context)) {
      context.current().isResolved = true;
    }
    return chunk.render(bodies.block, context);
  } else if (bodies['else']) {
    return chunk.render(bodies['else'], context);
  }

  return chunk.write('');
}

function coerce (value, type, context) {
  if (value) {
    switch (type || typeof(value)) {
      case 'number': return +value;
      case 'string': return String(value);
      case 'boolean': return Boolean(value);
      case 'date': return new Date(value);
      case 'context': return context.get(value);
    }
  }

  return value;
}

var helpers = {

  sep: function(chunk, context, bodies) {
    if (context.stack.index === context.stack.of - 1) {
      return chunk;
    }
    return bodies.block(chunk, context);
  },

  idx: function(chunk, context, bodies) {
    return bodies.block(chunk, context.push(context.stack.index));
  },
  contextDump: function(chunk, context, bodies) {
    _console.log(JSON.stringify(context.stack));
    return chunk;
  },// Utility helping to resolve dust references in the given chunk
  tap: function( input, chunk, context ){
    // return given input if there is no dust reference to resolve
    var output = input;
    // dust compiles a string to function, if there are references
    if( typeof input === "function"){
      output = '';
      chunk.tap(function(data){
        output += data;
        return '';
      }).render(input, context).untap();
      if( output === '' ){
        output = false;
      }
    }
    return output;
  },

  "if": function( chunk, context, bodies, params ){
    if( params && params.cond ){
      var cond = params.cond;
      cond = this.tap(cond, chunk, context);
      // eval expressions with no dust references
      if( eval( cond ) ){
       return chunk.render( bodies.block, context );
      }
      if( bodies['else'] ){
       return chunk.render( bodies['else'], context );
      }
    }
    // no condition
    else {
      _console.log( "NO condition given in the if helper!" );
    }
    return chunk;
  },
  select: function(chunk, context, bodies, params) {
    if( params && params.key){
      var key = params.key;
      key = this.tap(key, chunk, context);
      return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, value: context.get(key) }));
    }
    // no key
    else {
      _console.log( "No key given for the select tag!" );
    }
    return chunk;
  },

  eq: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual === expected; });
  },

  lt: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual < expected; });
  },

  lte: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual <= expected; });
  },

  gt: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual > expected; });
  },

  gte: function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return actual >= expected; });
  },

  "else": function(chunk, context, bodies, params) {
    return filter(chunk, context, bodies, params, function(expected, actual) { return true; });
  }
};

dust.helpers = helpers;

})(typeof exports !== 'undefined' ? exports : getGlobal());
<|endoftext|>


<commit_before>'use strict';
var q = require('q'),
    Rect = require('./geometery/rect');

exports.getMultiple = function getMultiple(elements) {
    return q.all(Object.keys(elements).map(function(key) {
            return exports.get(elements[key]);
        }))
        .then(function(rects) {
            return rects
                .filter(function(rect) {
                    return !rect.isZero();
                })
                .reduce(function(first, second) {
                    return first.merge(second);
                });
        });
};

exports.get = function get(element) {
    return element.getLocation()
        .then(function(pos) {
            return element.getSize().then(function(size) {
                return new Rect(pos.x, pos.y, size.width, size.height);
            });
        })
        .then(function(rect) {
            return element.getCssValue('box-shadow').then(function(boxShadow) {
                var shadows = parseBoxShadow(boxShadow);
                return shadows.reduce(addBoxShadowRect, rect);
            });
        });
};

function parseBoxShadow(value) {
    var regex = /.+? ((?:\d*)(?:\.\d+)?)px ((?:\d*)(?:\.\d+)?)px ((?:\d*)(?:\.\d+)?)px ((?:\d*)(?:\.\d+)?)px( inset)?/,
        results = [],
        match;

    while ((match = value.match(regex))) {
        //ignore inset shadows
        if (!match[5]) {
            results.push({
                offsetX: +match[1],
                offsetY: +match[2],
                blurRadius: +match[3],
                spreadRadius: +match[4]
            });
        }

        value = value.substring(match.index + match[0].length);
    }
    return results;
}

function addBoxShadowRect(rect, shadow) {
    var size = shadow.blurRadius + shadow.spreadRadius,
        shadowRect = new Rect(
            rect.x + shadow.offsetX - size,
            rect.y + shadow.offsetY - size,
            rect.width - shadow.offsetX + 2 * size,
            rect.height - shadow.offsetY + 2 *size
        );
    return rect.merge(shadowRect);
}
<commit_msg>Correctly handle box-shadows<commit_after>'use strict';
var q = require('q'),
    Rect = require('./geometery/rect');

exports.getMultiple = function getMultiple(elements) {
    return q.all(Object.keys(elements).map(function(key) {
            return exports.get(elements[key]);
        }))
        .then(function(rects) {
            return rects
                .filter(function(rect) {
                    return !rect.isZero();
                })
                .reduce(function(first, second) {
                    return first.merge(second);
                });
        });
};

exports.get = function get(element) {
    return element.getLocation()
        .then(function(pos) {
            return element.getSize().then(function(size) {
                return new Rect(pos.x, pos.y, size.width, size.height);
            });
        })
        .then(function(rect) {
            return element.getCssValue('box-shadow').then(function(boxShadow) {
                var shadows = parseBoxShadow(boxShadow);
                return adjustRect(rect, shadows);
            });
        });
};

function parseBoxShadow(value) {
    var regex = /.+? ([-+]?\d*\.?\d+)px ([-+]?\d*\.?\d+)px ([-+]?\d*\.?\d+)px ([-+]?\d*\.?\d+)px( inset)?/,
        results = [],
        match;

    while ((match = value.match(regex))) {
        results.push({
            offsetX: +match[1],
            offsetY: +match[2],
            blurRadius: +match[3],
            spreadRadius: +match[4],
            inset: !!match[5]
        });
        value = value.substring(match.index + match[0].length);
    }
    return results;
}

function adjustRect(rect, shadows) {
    var extent = calculateShadowExtent(shadows);
    return new Rect(
        Math.max(0, rect.x + extent.left),
        Math.max(0, rect.y + extent.top),
        rect.width - extent.left + extent.right,
        rect.height - extent.top + extent.bottom
    );
}

function calculateShadowExtent(shadows) {
    var result = {top: 0, left: 0, right: 0, bottom: 0};
    shadows.forEach(function(shadow) {
        if (shadow.inset) {
            //skip inset shadows
            return;
        }

        var blurAndSpread = shadow.spreadRadius + shadow.blurRadius;
        result.left = Math.min(shadow.offsetX - blurAndSpread, result.left);
        result.right = Math.max(shadow.offsetX + blurAndSpread, result.right);
        result.top = Math.min(shadow.offsetY - blurAndSpread, result.top);
        result.bottom = Math.max(shadow.offsetY + blurAndSpread, result.bottom);
    });
    return result;
}
<|endoftext|>


<commit_before>
(function(){
  Express = {
    version : '0.0.1',
    routes  : [],

    // --- Response

    response : {
      body : null,
      status : 200,
      headers : {},
      cookie : {}
    },

    // --- Defaults

    defaults : {
      cookie : {
        maxAge : 3600
      },
      route : {
        callback : function() {
          Express.status('Not Found')
          'Not Found'
        }
      }
    },

    hookCallbacks : {
      request : [

        // Cookie parsing

        function (request, response) {
          Express.response.cookie = request.cookie = Express.parseCookie(request.headers['Cookie'])
        }
      ],

      response : [

        // Content length

        function(request, response) {
          Express.header('Content-Length', (Express.response.body || '').length)
        }
      ]
    },

    /**
     * Invoke hook _name_ with _args_.
     *
     * @param  {string} name
     * @param  {...} args
     * @api public
     */

    hook : function(name, args) {
      if (this.hookCallbacks[name])
        for (i = 0, len = this.hookCallbacks[name].length; i < len; ++i)
          this.hookCallbacks[name][i].apply(this, this.argsArray(arguments, 1))
    },

    /**
     * Add middlware _callback_ for hook _name_.
     *
     * @param  {string} name
     * @param  {function} callback
     * @api public
     */

    use : function(name, callback) {
      this.hookCallbacks[name].push(callback)
    },

    /**
     * Start express, binding to _port_.
     *
     * @param {int} port
     * @api public
     */

    start : function(port) {
      this.server.listen(port || 3000, function(request, response){
        Express.request = request
        request.headers = Express.arrayToHash(request.headers)
        Express.hook('request', request, response)
        request.uri.params = Express.parseNestedParams(request.uri.params)
        request.uri.path = Express.normalizePath(request.uri.path)
        Express.response.body = Express.callRouteFor(request)
        Express.prepareCookie()
        Express.hook('response', request, response)
        response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))
        response.sendBody(Express.response.body || '')
        response.finish()
      })
    },

    server : {

      /**
       * Listen to _port_ with _callback_.
       *
       * @param {int} port
       * @param {function} callback
       * @api private
       */

      listen : function(port, callback) {
        node.http.createServer(callback).listen(port)
        puts('Express listening to http://localhost:' + port)
      }
    },

    prepareCookie : function() {
      var cookie = []
      for (var key in this.response.cookie)
        if (this.response.cookie.hasOwnProperty(key))
          cookie.push(key + '=' + this.response.cookie[key])
      if (cookie.length)
        this.header('Set-Cookie', cookie.join('; '))
    },

    /**
     * Return an associative array generated
     * from the key / value pairs in _hash_.
     *
     * @param  {hash} hash
     * @return {array}
     * @api public
     */

    hashToArray : function(hash) {
      var array = []
      for (var key in hash)
        if (hash.hasOwnProperty(key))
          array.push([key, hash[key]])
      return array
    },

    /**
     * Return hash generated from an
     * associative array.
     *
     * @param  {array} array
     * @return {hash}
     * @api public
     */

    arrayToHash : function(array) {
      var hash = {}
      for (i = 0, len = array.length; i < len; ++i)
        hash[array[i][0]] = array[i][1]
      return hash
    },

    /**
     * Set response status to _value_. Where value may be
     * a case-insensitive string such as 'Not Found', 'forbidden',
     * or a numeric HTTP response status code.
     *
     * @param  {int, string} value
     * @return {int}
     * @api public
     */

    status : function(value) {
      if (typeof value == 'number') return this.response.status = value
      for (var code in node.http.STATUS_CODES)
        if (node.http.STATUS_CODES.hasOwnProperty(code))
          if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())
            return this.response.status = code
    },

    /**
     * Sets _name_ header to _value_. When _value_
     * is not present the value of the header _name_
     * will be returned (if available).
     *
     * @param {string} name
     * @param {string} value
     * @api public
     */

    header : function(name, value) {
      return value ? this.response.headers[name] = value :
               this.response.headers[name]
    },

    /**
     * Return param _key_'s value or _defaultValue_ when
     * the param has not been set.
     *
     * @param  {string} key
     * @param  {mixed} defaultValue
     * @return {mixed}
     * @api public
     */

    param : function(key, defaultValue) {
      return this.request.uri.params[key] || defaultValue
    },

    /**
     * Return cookie _key_. When _value_ is present
     * then a response cookie field will be set.
     *
     * @param  {string} key
     * @param  {string} value
     * @return {string, hash}
     * @api public
     */

    cookie : function(key, value) {
      return value ? this.response.cookie[key] = value :
               this.response.cookie[key]
    },

    /**
     * Parse _params_, splitting { user[info][name] : 'tj' } into
     * { user : { info : { name : 'tj' }}}
     *
     * @param  {hash} params
     * @return {hash}
     * @api public
     */

    parseNestedParams : function(params) {
      for (var key in params)
        if (params.hasOwnProperty(key))
          if (parts = key.split('['))
            if (parts.length > 1)
              for (i = 0, prop = params, len = parts.length; i < len; ++i) {
                if (i == len - 1) {
                  var name = parts[i].replace(']', '')
                  prop[name] = params[key]
                  prop = params, delete params[key]
                }
                else {
                  var name = parts[i].replace(']', '')
                  prop = prop[name] = prop[name] || {}
                }
              }

      return params
    },

    /**
     * Parse _cookie_ string into an object (hash).
     *
     * @param  {string} cookie
     * @return {hash}
     * @api public
     */

    parseCookie : function(cookie) {
      var hash = {}
      if (!cookie) return hash
      var attrs = cookie.split(/\s*;\s*/)
      for (i = 0; i < attrs.length; ++i)
        hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])
      return hash
    },

    /**
     * Normalize a path. Strips trailing / leading whitespace
     * and slashes ('/').
     *
     * @param  {string} path
     * @return {string}
     * @api public
     */

    normalizePath : function(path) {
      if (typeof path != 'string') return path
      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')
    },

    /**
     * Normalize _path_. When a RegExp it is simply returned,
     * otherwise a string is converted to a regular expression
     * surrounded by ^$. So /user/:id/edit would become:
     *
     * \^/user/(.*?)\/edit\$/
     *
     * Each param key (:id) will be captured and placed in the
     * params array, so param('id') would give the string captured.
     *
     * @param  {string} path
     * @return {regexp}
     * @api public
     */

    pathToRegexp : function(path) {
      Express.regexpKeys = []
      if (path.constructor == RegExp) return path
      path = path.replace(/:(\w+)/g, function(_, key){
        Express.regexpKeys.push(key)
        return '(.*?)'
      })
      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')
    },

    /**
     * Escape RegExp _chars_ in _string_. Where _chars_
     * defaults to regular expression special characters.
     *
     * _chars_ should be a space delimited list of characters,
     * for example '[ ] ( )'.
     *
     * @param  {string} string
     * @param  {string} chars
     * @return {Type}
     * @api public
     */

    escapeRegexp : function(string, chars) {
      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')
      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')
    },

    /**
     * Return the contents of a function body.
     *
     * @param  {function} body
     * @return {string}
     * @api public
     */

    contentsOf : function(body) {
      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
    },

    /**
     * Eval _string_ in context of Express.
     *
     * @param  {string} string
     * @return {mixed}
     * @api public
     */

    eval : function(string) {
      return eval('with (Express){' + string + '}')
    },

    /**
     * Escape special characters in _html_.
     *
     * @param  {string} html
     * @return {string}
     * @api public
     */

    escape : function(html) {
      return html.
        replace(/&/g, '&').
        replace(/"/g, '"').
        replace(/</g, '<').
        replace(/>/g, '>')
    },

    /**
     * Convert native arguments object into an
     * array with optional _offset_.
     *
     * @param  {arguments} args
     * @param  {int} offset
     * @return {array}
     * @api public
     */

    argsArray : function(args, offset) {
      return Array.prototype.slice.call(args, offset)
    },

    /**
     * Check if _route_ matches the proper _request_ method.
     *
     * @param  {hash} route
     * @param  {hash} request
     * @return {bool}
     * @api private
     */

    routeMethod : function(route, request) {
      return route.method.toUpperCase() == request.method
    },

    /**
     * Check if _route_ matches provides the proper
     * encoding types listed in _request_'s Accept header.
     *
     * @param  {hash} route
     * @param  {hash} request
     * @return {bool}
     * @api private
     */

    routeProvides : function(route, request) {
      if (!route.options.provides) return true
      if (route.options.provides.constructor != Array)
        route.options.provides = [route.options.provides]
      for (i = 0, len = route.options.provides.length; i < len; ++i)
        if (request.headers['Accept'].match(route.options.provides[i]))
          return true
      return false
    },

    /**
     * Attept to match and call a route for
     * the given _request_, returning the data
     * returned by the route callback.
     *
     * @param  {object} request
     * @return {mixed}
     * @api private
     */

    callRouteFor : function(request) {
      var route = this.findRouteFor(request) || this.defaults.route
      if (route.keys)
        for (i = 0, len = route.keys.length; i < len; ++i)
          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null
      return this.eval(Express.contentsOf(route.callback)).toString()
    },

    /**
     * Attemp to find and return a route matching _request_.
     *
     * @param  {object} request
     * @return {object}
     * @api private
     */

    findRouteFor : function(request) {
      for (i = 0, len = this.routes.length; i < len; ++i)
        if (this.routeMatches(this.routes[i], request))
          return this.routes[i]
    },

    /**
     * Check if _route_ matches _request_
     *
     * @param  {object} route
     * @param  {object} request
     * @return {bool}
     * @api private
     */

    routeMatches : function(route, request) {
      // var conditions = [Express.routeMethod]
      // for (i = 0, len = conditions.length; i < len; ++i)
      //   if (!conditions[i](route, request))
      //     return false
      switch (route.path.constructor) {
        case String: return route.path == request.uri.path
        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))
      }
    },

    /**
     * Return a routing function for _method_.
     *
     * @param  {string} method
     * @return {function}
     * @api private
     */

    routeFunctionFor : function(method) {
      return function(path, options, callback) {
        if (options.constructor == Function) callback = options, options = {}
        path = Express.pathToRegexp(Express.normalizePath(path))
        Express.routes.push({
          keys : Express.regexpKeys,
          path : path,
          method : method,
          options : options,
          callback : callback
        })
      }
    },

    readFile : function(path, callback, errorCallback) {
      var promise = node.fs.cat(path, "utf8")
      errorCallback = errorCallback || function(){
        throw "failed to read file `" + path + "'"
      }
      promise.addCallback(callback)
      promise.addErrback(errorCallback)
    },

    parseView : function(contents, context) {

    },

    display : function(path) {

    }
  }

  get = Express.routeFunctionFor('get')
  post = Express.routeFunctionFor('post')
  del = Express.routeFunctionFor('delete')
  put = Express.routeFunctionFor('put')

})()

Logger = function(request, response){
  puts('"' + request.method + ' /' + request.uri.path + ' HTTP/' + request.httpVersion + '" - ' + Express.response.status)
}

Express.use('response', Logger)

get('user/:name/:operation', function(){
 p(request.headers['User-Agent'])
 p(request.headers['Accept'])
 p(request.headers['Accept-Encoding'])
 p(request.headers['Cookie'])
 p(request.cookie)
 param('operation') + 'ing ' + param('name')
})

get('cookies', function(){
  cookie('foo', 'bar')
  cookie('some-thing', 'some value')
  cookie('max-age', '1000')
  p(request.headers)
  p(response.headers)
  'Wahoo!'
})

get('articles', function(){
  display('spec/data/example.html.js')
  'list of articles'
})

get(/articles\/(\d+)/, function(){
  'article id ' + captures[1]
})

get('articles/:name', function(){
  if (param('name') == 'tj')
    'hello tj'
  else
    'article name ' + param('name')
})

Express.start()
<commit_msg>Exporting use()<commit_after>
(function(){
  Express = {
    version : '0.0.1',
    routes  : [],

    // --- Response

    response : {
      body : null,
      status : 200,
      headers : {},
      cookie : {}
    },

    // --- Defaults

    defaults : {
      cookie : {
        maxAge : 3600
      },
      route : {
        callback : function() {
          Express.status('Not Found')
          'Not Found'
        }
      }
    },

    hookCallbacks : {
      request : [

        // Cookie parsing

        function (request, response) {
          Express.response.cookie = request.cookie = Express.parseCookie(request.headers['Cookie'])
        }
      ],

      response : [

        // Content length

        function(request, response) {
          Express.header('Content-Length', (Express.response.body || '').length)
        }
      ]
    },

    /**
     * Invoke hook _name_ with _args_.
     *
     * @param  {string} name
     * @param  {...} args
     * @api public
     */

    hook : function(name, args) {
      if (this.hookCallbacks[name])
        for (i = 0, len = this.hookCallbacks[name].length; i < len; ++i)
          this.hookCallbacks[name][i].apply(this, this.argsArray(arguments, 1))
    },

    /**
     * Add middlware _callback_ for hook _name_.
     *
     * @param  {string} name
     * @param  {function} callback
     * @api public
     */

    use : function(name, callback) {
      Express.hookCallbacks[name].push(callback)
    },

    /**
     * Start express, binding to _port_.
     *
     * @param {int} port
     * @api public
     */

    start : function(port) {
      this.server.listen(port || 3000, function(request, response){
        Express.request = request
        request.headers = Express.arrayToHash(request.headers)
        Express.hook('request', request, response)
        request.uri.params = Express.parseNestedParams(request.uri.params)
        request.uri.path = Express.normalizePath(request.uri.path)
        Express.response.body = Express.callRouteFor(request)
        Express.prepareCookie()
        Express.hook('response', request, response)
        response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))
        response.sendBody(Express.response.body || '')
        response.finish()
      })
    },

    server : {

      /**
       * Listen to _port_ with _callback_.
       *
       * @param {int} port
       * @param {function} callback
       * @api private
       */

      listen : function(port, callback) {
        node.http.createServer(callback).listen(port)
        puts('Express listening to http://localhost:' + port)
      }
    },

    prepareCookie : function() {
      var cookie = []
      for (var key in this.response.cookie)
        if (this.response.cookie.hasOwnProperty(key))
          cookie.push(key + '=' + this.response.cookie[key])
      if (cookie.length)
        this.header('Set-Cookie', cookie.join('; '))
    },

    /**
     * Return an associative array generated
     * from the key / value pairs in _hash_.
     *
     * @param  {hash} hash
     * @return {array}
     * @api public
     */

    hashToArray : function(hash) {
      var array = []
      for (var key in hash)
        if (hash.hasOwnProperty(key))
          array.push([key, hash[key]])
      return array
    },

    /**
     * Return hash generated from an
     * associative array.
     *
     * @param  {array} array
     * @return {hash}
     * @api public
     */

    arrayToHash : function(array) {
      var hash = {}
      for (i = 0, len = array.length; i < len; ++i)
        hash[array[i][0]] = array[i][1]
      return hash
    },

    /**
     * Set response status to _value_. Where value may be
     * a case-insensitive string such as 'Not Found', 'forbidden',
     * or a numeric HTTP response status code.
     *
     * @param  {int, string} value
     * @return {int}
     * @api public
     */

    status : function(value) {
      if (typeof value == 'number') return this.response.status = value
      for (var code in node.http.STATUS_CODES)
        if (node.http.STATUS_CODES.hasOwnProperty(code))
          if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())
            return this.response.status = code
    },

    /**
     * Sets _name_ header to _value_. When _value_
     * is not present the value of the header _name_
     * will be returned (if available).
     *
     * @param {string} name
     * @param {string} value
     * @api public
     */

    header : function(name, value) {
      return value ? this.response.headers[name] = value :
               this.response.headers[name]
    },

    /**
     * Return param _key_'s value or _defaultValue_ when
     * the param has not been set.
     *
     * @param  {string} key
     * @param  {mixed} defaultValue
     * @return {mixed}
     * @api public
     */

    param : function(key, defaultValue) {
      return this.request.uri.params[key] || defaultValue
    },

    /**
     * Return cookie _key_. When _value_ is present
     * then a response cookie field will be set.
     *
     * @param  {string} key
     * @param  {string} value
     * @return {string, hash}
     * @api public
     */

    cookie : function(key, value) {
      return value ? this.response.cookie[key] = value :
               this.response.cookie[key]
    },

    /**
     * Parse _params_, splitting { user[info][name] : 'tj' } into
     * { user : { info : { name : 'tj' }}}
     *
     * @param  {hash} params
     * @return {hash}
     * @api public
     */

    parseNestedParams : function(params) {
      for (var key in params)
        if (params.hasOwnProperty(key))
          if (parts = key.split('['))
            if (parts.length > 1)
              for (i = 0, prop = params, len = parts.length; i < len; ++i) {
                if (i == len - 1) {
                  var name = parts[i].replace(']', '')
                  prop[name] = params[key]
                  prop = params, delete params[key]
                }
                else {
                  var name = parts[i].replace(']', '')
                  prop = prop[name] = prop[name] || {}
                }
              }

      return params
    },

    /**
     * Parse _cookie_ string into an object (hash).
     *
     * @param  {string} cookie
     * @return {hash}
     * @api public
     */

    parseCookie : function(cookie) {
      var hash = {}
      if (!cookie) return hash
      var attrs = cookie.split(/\s*;\s*/)
      for (i = 0; i < attrs.length; ++i)
        hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])
      return hash
    },

    /**
     * Normalize a path. Strips trailing / leading whitespace
     * and slashes ('/').
     *
     * @param  {string} path
     * @return {string}
     * @api public
     */

    normalizePath : function(path) {
      if (typeof path != 'string') return path
      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')
    },

    /**
     * Normalize _path_. When a RegExp it is simply returned,
     * otherwise a string is converted to a regular expression
     * surrounded by ^$. So /user/:id/edit would become:
     *
     * \^/user/(.*?)\/edit\$/
     *
     * Each param key (:id) will be captured and placed in the
     * params array, so param('id') would give the string captured.
     *
     * @param  {string} path
     * @return {regexp}
     * @api public
     */

    pathToRegexp : function(path) {
      Express.regexpKeys = []
      if (path.constructor == RegExp) return path
      path = path.replace(/:(\w+)/g, function(_, key){
        Express.regexpKeys.push(key)
        return '(.*?)'
      })
      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')
    },

    /**
     * Escape RegExp _chars_ in _string_. Where _chars_
     * defaults to regular expression special characters.
     *
     * _chars_ should be a space delimited list of characters,
     * for example '[ ] ( )'.
     *
     * @param  {string} string
     * @param  {string} chars
     * @return {Type}
     * @api public
     */

    escapeRegexp : function(string, chars) {
      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')
      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')
    },

    /**
     * Return the contents of a function body.
     *
     * @param  {function} body
     * @return {string}
     * @api public
     */

    contentsOf : function(body) {
      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
    },

    /**
     * Eval _string_ in context of Express.
     *
     * @param  {string} string
     * @return {mixed}
     * @api public
     */

    eval : function(string) {
      return eval('with (Express){' + string + '}')
    },

    /**
     * Escape special characters in _html_.
     *
     * @param  {string} html
     * @return {string}
     * @api public
     */

    escape : function(html) {
      return html.
        replace(/&/g, '&').
        replace(/"/g, '"').
        replace(/</g, '<').
        replace(/>/g, '>')
    },

    /**
     * Convert native arguments object into an
     * array with optional _offset_.
     *
     * @param  {arguments} args
     * @param  {int} offset
     * @return {array}
     * @api public
     */

    argsArray : function(args, offset) {
      return Array.prototype.slice.call(args, offset)
    },

    /**
     * Check if _route_ matches the proper _request_ method.
     *
     * @param  {hash} route
     * @param  {hash} request
     * @return {bool}
     * @api private
     */

    routeMethod : function(route, request) {
      return route.method.toUpperCase() == request.method
    },

    /**
     * Check if _route_ matches provides the proper
     * encoding types listed in _request_'s Accept header.
     *
     * @param  {hash} route
     * @param  {hash} request
     * @return {bool}
     * @api private
     */

    routeProvides : function(route, request) {
      if (!route.options.provides) return true
      if (route.options.provides.constructor != Array)
        route.options.provides = [route.options.provides]
      for (i = 0, len = route.options.provides.length; i < len; ++i)
        if (request.headers['Accept'].match(route.options.provides[i]))
          return true
      return false
    },

    /**
     * Attept to match and call a route for
     * the given _request_, returning the data
     * returned by the route callback.
     *
     * @param  {object} request
     * @return {mixed}
     * @api private
     */

    callRouteFor : function(request) {
      var route = this.findRouteFor(request) || this.defaults.route
      if (route.keys)
        for (i = 0, len = route.keys.length; i < len; ++i)
          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null
      return this.eval(Express.contentsOf(route.callback)).toString()
    },

    /**
     * Attemp to find and return a route matching _request_.
     *
     * @param  {object} request
     * @return {object}
     * @api private
     */

    findRouteFor : function(request) {
      for (i = 0, len = this.routes.length; i < len; ++i)
        if (this.routeMatches(this.routes[i], request))
          return this.routes[i]
    },

    /**
     * Check if _route_ matches _request_
     *
     * @param  {object} route
     * @param  {object} request
     * @return {bool}
     * @api private
     */

    routeMatches : function(route, request) {
      // var conditions = [Express.routeMethod]
      // for (i = 0, len = conditions.length; i < len; ++i)
      //   if (!conditions[i](route, request))
      //     return false
      switch (route.path.constructor) {
        case String: return route.path == request.uri.path
        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))
      }
    },

    /**
     * Return a routing function for _method_.
     *
     * @param  {string} method
     * @return {function}
     * @api private
     */

    routeFunctionFor : function(method) {
      return function(path, options, callback) {
        if (options.constructor == Function) callback = options, options = {}
        path = Express.pathToRegexp(Express.normalizePath(path))
        Express.routes.push({
          keys : Express.regexpKeys,
          path : path,
          method : method,
          options : options,
          callback : callback
        })
      }
    },

    readFile : function(path, callback, errorCallback) {
      var promise = node.fs.cat(path, "utf8")
      errorCallback = errorCallback || function(){
        throw "failed to read file `" + path + "'"
      }
      promise.addCallback(callback)
      promise.addErrback(errorCallback)
    },

    parseView : function(contents, context) {

    },

    display : function(path) {

    },

    Logger : function(request, response){
      puts('"' + request.method + ' /' + request.uri.path + ' HTTP/' + request.httpVersion + '" - ' + Express.response.status)
    }
  }

  get = Express.routeFunctionFor('get')
  post = Express.routeFunctionFor('post')
  del = Express.routeFunctionFor('delete')
  put = Express.routeFunctionFor('put')
  use = Express.use

})()

use('response', Express.Logger)

get('user/:name/:operation', function(){
 p(request.headers['User-Agent'])
 p(request.headers['Accept'])
 p(request.headers['Accept-Encoding'])
 p(request.headers['Cookie'])
 p(request.cookie)
 param('operation') + 'ing ' + param('name')
})

get('cookies', function(){
  cookie('foo', 'bar')
  cookie('some-thing', 'some value')
  cookie('max-age', '1000')
  p(request.headers)
  p(response.headers)
  'Wahoo!'
})

get('articles', function(){
  display('spec/data/example.html.js')
  'list of articles'
})

get(/articles\/(\d+)/, function(){
  'article id ' + captures[1]
})

get('articles/:name', function(){
  if (param('name') == 'tj')
    'hello tj'
  else
    'article name ' + param('name')
})

Express.start()
<|endoftext|>


<commit_before>var chalk = require('chalk');
var filesize = require('filesize');
var timestamp = require('./timestamp');
var fs = require('fs');

function FireantSave(file) {
    fs.writeFileSync(file, this.stdout || this.toString(), 'utf8');
    console.log(timestamp(), chalk.magenta(file) + ' ' + chalk.green(filesize(fs.statSync(file).size, {base: 10})));
    return this;
}

String.prototype.save = FireantSave;

module.exports = FireantSave;
<commit_msg>Refuse to write empty file and display warning<commit_after>var chalk = require('chalk');
var filesize = require('filesize');
var timestamp = require('./timestamp');
var fs = require('fs');

function FireantSave(file) {
    var str = this.toString();

    if (str.length > 0) {
        fs.writeFileSync(file, str, 'utf8');
        console.log(timestamp(), chalk.magenta(file) + ' ' + chalk.green(filesize(fs.statSync(file).size, {base: 10})));
    } else {
        console.log(timestamp(), chalk.red.bold('WARNING!'), chalk.red('Refused to write empty file'));
    }
}

String.prototype.save = FireantSave;

module.exports = FireantSave;
<|endoftext|>


<commit_before>/* eslint-disable no-magic-numbers,no-undef,semi */

user_pref('accessibility.force_disabled', 1);
user_pref('app.shield.optoutstudies.enabled', false);
user_pref('browser.cache.cache_isolation', true);
user_pref('browser.discovery.enabled', false);
user_pref('browser.fixup.alternate.enabled', false);
user_pref('browser.formfill.enable', false);
user_pref('browser.link.open_newwindow', 1);
user_pref('browser.newtabpage.enabled', false);
user_pref('browser.safebrowsing.downloads.remote.enabled', false);
user_pref('browser.startup.homepage', 'about:blank');
user_pref('browser.urlbar.doubleClickSelectsAll', false);
user_pref('browser.urlbar.openViewOnFocus', false);
user_pref('browser.urlbar.speculativeConnect.enabled', false);
user_pref('browser.urlbar.update1', false);
user_pref('devtools.debugger.remote-enabled', false);
user_pref('devtools.inspector.activeSidebar', 'ruleview');
user_pref('devtools.inspector.showUserAgentStyles', true);
user_pref('devtools.inspector.three-pane-enabled', false);
user_pref('devtools.inspector.three-pane-first-run', false);
user_pref('dom.gamepad.enabled', false);
user_pref('dom.targetBlankNoOpener.enabled', true);
user_pref('extensions.activeThemeID', 'firefox-compact-light@mozilla.org');
user_pref('extensions.fxmonitor.enabled', false);
user_pref('extensions.htmlaboutaddons.recommendations.enabled', false);
user_pref('extensions.pocket.enabled', false);
user_pref('font.default.x-western', 'sans-serif');
user_pref('font.name.monospace.x-western', 'PragmataPro Mono Liga');
user_pref('font.name.sans-serif.el', 'Source Sans Pro');
user_pref('font.name.sans-serif.ja', 'Source Han Sans');
user_pref('font.name.sans-serif.ko', 'Source Han Sans K');
user_pref('font.name.sans-serif.x-cyrillic', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-western', 'Source Sans Pro');
user_pref('font.name.sans-serif.zh-CN', 'Source Han Sans SC');
user_pref('font.name.sans-serif.zh-HK', 'Source Han Sans HC');
user_pref('font.name.sans-serif.zh-TW', 'Source Han Sans TC');
user_pref('font.name.sans.x-western', 'Source Sans Pro');
user_pref('font.name.serif.el', 'Source Serif Pro');
user_pref('font.name.serif.ja', 'Source Han Serif');
user_pref('font.name.serif.ko', 'Source Han Serif K');
user_pref('font.name.serif.x-cyrillic', 'Source Serif Pro');
user_pref('font.name.serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.serif.x-western', 'Source Serif Pro');
user_pref('font.name.serif.zh-CN', 'Source Han Serif SC');
user_pref('font.name.serif.zh-HK', 'Source Han Serif TC');
user_pref('font.name.serif.zh-TW', 'Source Han Serif TC');
user_pref('font.size.monospace.x-western', '16');
user_pref('gfx.color_management.enablev4', true);
user_pref('gfx.color_management.mode', 1);
user_pref('media.autoplay.default', 5);
user_pref('media.peerconnection.ice.default_address_only', true);
user_pref('media.peerconnection.ice.no_host', true);
user_pref('network.IDN_show_punycode', true);
user_pref('network.cookie.cookieBehavior', 1);
user_pref('network.cookie.thirdparty.sessionOnly', true);
user_pref('network.dns.disablePrefetch', true);
user_pref('network.http.referer.XOriginPolicy', 1);
user_pref('network.http.referer.XOriginTrimmingPolicy', 2);
user_pref('network.http.speculative-parallel-limit', 0);
user_pref('network.manage-offline-status', false);
user_pref('network.predictor.enabled', false);
user_pref('network.prefetch-next', false);
user_pref('network.proxy.socks_remote_dns', true);
user_pref('network.trr.mode', 5);
user_pref('permissions.default.desktop-notification', 2);
user_pref('permissions.default.geo', 2);
user_pref('plugin.state.flash', 0);
user_pref('privacy.clearOnShutdown.offlineApps', true);
user_pref('privacy.clearOnShutdown.siteSettings', true);
user_pref('privacy.firstparty.isolate', true);
user_pref('privacy.firstparty.isolate.restrict_opener_access', true);
user_pref('privacy.trackingprotection.cryptomining.enabled', true);
user_pref('privacy.trackingprotection.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('privacy.trackingprotection.fingerprinting.enabled', true);
user_pref('privacy.trackingprotection.pbmode.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('reader.content_width', 4);
user_pref('reader.font_size', 5);
user_pref('reader.font_type', 'sans-serif');
user_pref('reader.line_height', 3);
user_pref('security.mixed_content.block_display_content', true);
user_pref('security.mixed_content.block_object_subrequest', true);
user_pref('security.mixed_content.upgrade_display_content', true);
user_pref('signon.rememberSignons', false);
user_pref('toolkit.legacyUserProfileCustomizations.stylesheets', true);
user_pref('toolkit.telemetry.archive.enabled', false);
user_pref('toolkit.telemetry.enabled', false);
user_pref('toolkit.telemetry.unified', false);
<commit_msg>firefox: Disable paste on middle click<commit_after>/* eslint-disable no-magic-numbers,no-undef,semi */

user_pref('accessibility.force_disabled', 1);
user_pref('app.shield.optoutstudies.enabled', false);
user_pref('browser.cache.cache_isolation', true);
user_pref('browser.discovery.enabled', false);
user_pref('browser.fixup.alternate.enabled', false);
user_pref('browser.formfill.enable', false);
user_pref('browser.link.open_newwindow', 1);
user_pref('browser.newtabpage.enabled', false);
user_pref('browser.safebrowsing.downloads.remote.enabled', false);
user_pref('browser.startup.homepage', 'about:blank');
user_pref('browser.urlbar.doubleClickSelectsAll', false);
user_pref('browser.urlbar.openViewOnFocus', false);
user_pref('browser.urlbar.speculativeConnect.enabled', false);
user_pref('browser.urlbar.update1', false);
user_pref('devtools.debugger.remote-enabled', false);
user_pref('devtools.inspector.activeSidebar', 'ruleview');
user_pref('devtools.inspector.showUserAgentStyles', true);
user_pref('devtools.inspector.three-pane-enabled', false);
user_pref('devtools.inspector.three-pane-first-run', false);
user_pref('dom.gamepad.enabled', false);
user_pref('dom.targetBlankNoOpener.enabled', true);
user_pref('extensions.activeThemeID', 'firefox-compact-light@mozilla.org');
user_pref('extensions.fxmonitor.enabled', false);
user_pref('extensions.htmlaboutaddons.recommendations.enabled', false);
user_pref('extensions.pocket.enabled', false);
user_pref('font.default.x-western', 'sans-serif');
user_pref('font.name.monospace.x-western', 'PragmataPro Mono Liga');
user_pref('font.name.sans-serif.el', 'Source Sans Pro');
user_pref('font.name.sans-serif.ja', 'Source Han Sans');
user_pref('font.name.sans-serif.ko', 'Source Han Sans K');
user_pref('font.name.sans-serif.x-cyrillic', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-western', 'Source Sans Pro');
user_pref('font.name.sans-serif.zh-CN', 'Source Han Sans SC');
user_pref('font.name.sans-serif.zh-HK', 'Source Han Sans HC');
user_pref('font.name.sans-serif.zh-TW', 'Source Han Sans TC');
user_pref('font.name.sans.x-western', 'Source Sans Pro');
user_pref('font.name.serif.el', 'Source Serif Pro');
user_pref('font.name.serif.ja', 'Source Han Serif');
user_pref('font.name.serif.ko', 'Source Han Serif K');
user_pref('font.name.serif.x-cyrillic', 'Source Serif Pro');
user_pref('font.name.serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.serif.x-western', 'Source Serif Pro');
user_pref('font.name.serif.zh-CN', 'Source Han Serif SC');
user_pref('font.name.serif.zh-HK', 'Source Han Serif TC');
user_pref('font.name.serif.zh-TW', 'Source Han Serif TC');
user_pref('font.size.monospace.x-western', '16');
user_pref('gfx.color_management.enablev4', true);
user_pref('gfx.color_management.mode', 1);
user_pref('media.autoplay.default', 5);
user_pref('media.peerconnection.ice.default_address_only', true);
user_pref('media.peerconnection.ice.no_host', true);
user_pref('middlemouse.paste', false);
user_pref('network.IDN_show_punycode', true);
user_pref('network.cookie.cookieBehavior', 1);
user_pref('network.cookie.thirdparty.sessionOnly', true);
user_pref('network.dns.disablePrefetch', true);
user_pref('network.http.referer.XOriginPolicy', 1);
user_pref('network.http.referer.XOriginTrimmingPolicy', 2);
user_pref('network.http.speculative-parallel-limit', 0);
user_pref('network.manage-offline-status', false);
user_pref('network.predictor.enabled', false);
user_pref('network.prefetch-next', false);
user_pref('network.proxy.socks_remote_dns', true);
user_pref('network.trr.mode', 5);
user_pref('permissions.default.desktop-notification', 2);
user_pref('permissions.default.geo', 2);
user_pref('plugin.state.flash', 0);
user_pref('privacy.clearOnShutdown.offlineApps', true);
user_pref('privacy.clearOnShutdown.siteSettings', true);
user_pref('privacy.firstparty.isolate', true);
user_pref('privacy.firstparty.isolate.restrict_opener_access', true);
user_pref('privacy.trackingprotection.cryptomining.enabled', true);
user_pref('privacy.trackingprotection.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('privacy.trackingprotection.fingerprinting.enabled', true);
user_pref('privacy.trackingprotection.pbmode.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('reader.content_width', 4);
user_pref('reader.font_size', 5);
user_pref('reader.font_type', 'sans-serif');
user_pref('reader.line_height', 3);
user_pref('security.mixed_content.block_display_content', true);
user_pref('security.mixed_content.block_object_subrequest', true);
user_pref('security.mixed_content.upgrade_display_content', true);
user_pref('signon.rememberSignons', false);
user_pref('toolkit.legacyUserProfileCustomizations.stylesheets', true);
user_pref('toolkit.telemetry.archive.enabled', false);
user_pref('toolkit.telemetry.enabled', false);
user_pref('toolkit.telemetry.unified', false);
<|endoftext|>