<commit_before>'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';
import del from 'del';
// import ts from 'gulp-typescript';
import sass from 'gulp-sass';
import autoprefixer from 'gulp-autoprefixer';
import sourceMaps from 'gulp-sourcemaps';
import rename from 'gulp-rename';

import browserify from 'browserify';
import watchify from 'watchify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import assign from 'lodash.assign';
import tsify from 'tsify';
import gutil from 'gulp-util';
import notify from 'gulp-notify';
import runSequence from 'run-sequence';
import uglify from 'gulp-uglify';
import plumber from 'gulp-plumber';

import jade from 'gulp-jade';
import pug from 'gulp-pug';
import data from 'gulp-data';
import gPath from 'path';

// let tsProject = ts.createProject("tsconfig.json");

const base = {
	src: './src',
	dist: './dist',
	folder: 'assets'
};

const path = {
	style: {
		src: `${base.src}/${base.folder}/scss/**/*.scss`,
		dist: `${base.dist}/${base.folder}/css/`
	},
	script: {
		src: `${base.src}/${base.folder}/ts/**/*.ts`,
		dist: `${base.dist}/${base.folder}/js/`
	},
	images: {
		src: `${base.src}/${base.folder}/images/**/*.+(jpg|jpeg|gif|png)`,
		dist: `${base.dist}/${base.folder}/images/`
	},
	html: {
		src: `${base.src}/*.html`,
		dist: `${base.dist}/`
	},
	jade: {
		src: `${base.src}/*.jade`,
		dist: `${base.dist}/`
	},
	pug: {
		src: `${base.src}/*.pug`,
		dist: `${base.dist}/`
	},
	data: {
		src: `${base.src}/`
	}
};

const customOpts = {
    basedir: '.',
    debug: true,
    entries: [`${base.src}/${base.folder}/ts/app.ts`],
    cache: {},
    packageCache: {},
    plugin: [tsify]
};
const errHandler = notify.onError("Error: <%= error.title %> <%= error.message %>");
//set browserify oprions
const opts = assign({}, watchify.args, customOpts);
//watchify od browserify
let b = watchify(browserify(opts));
//wrapp all files in one
let bundle = () => {
	return b.transform('babelify', {
	    	presets: ['env'],
	    	extensions: ['.ts']
	    })
		.bundle()
		.on('error', gutil.log.bind(gutil, 'Browserify Error'))
		.pipe(source('app-bundle.min.js'))
		.pipe(buffer())
		.pipe(sourceMaps.init({loadMaps: true}))
		// .pipe(uglify())
		.pipe(sourceMaps.write('./'))
		.pipe(gulp.dest(path.script.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
};

gulp.task('clean', () => {
	return del([`${base.dist}/*`]).then( paths => {
		let log = paths.length > 0 ? `Deleted files and folders:\n  ${paths.join('\n')}` : "No files to delete";
		console.log(log);
	});
});

gulp.task('build:js', bundle); // build the file

gulp.task('sass', () => {
	return gulp.src(path.style.src)
		.pipe(sourceMaps.init())
		.pipe(sass({outputStyle: 'compressed'}).on('error', errHandler))
		// .pipe(sass().on('error', errHandler))
		.pipe(autoprefixer())
		.pipe(rename({suffix: ".min"}))
		.pipe(sourceMaps.write('.'))
		.pipe(gulp.dest(path.style.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
});

gulp.task("copy:html", () => {
    return gulp.src(path.html.src)
        .pipe(gulp.dest(path.html.dist));
});

gulp.task("copy:img", () => {
    return gulp.src(path.images.src)
        .pipe(gulp.dest(path.images.dist))
        .pipe(browserSync.reload({ stream: true })); // Reload browser
});

// gulp.task('jade:transform', () => {
// 	let YOUR_LOCALS = {};

// 	return gulp.src(path.jade.src)
// 		.pipe(plumber({
// 			errorHandler: errHandler
// 		}))
// 		.pipe(jade({
// 			locals: YOUR_LOCALS,
// 			pretty: true
// 		}))
// 		.pipe(plumber.stop())
// 		.pipe(gulp.dest(path.jade.dist))
// 		.pipe(browserSync.reload({ stream: true })); // Reload browser
// });

let getJsonData = (file) => {
	delete require.cache[require.resolve(`${path.data.src}${gPath.basename(file.path)}.json`)];

	// console.log(require(`${path.data.src}${gPath.basename(file.path)}.json`));
 	return require(`${path.data.src}${gPath.basename(file.path)}.json`);
};

gulp.task('pug:transform', () => {
	return gulp.src(path.pug.src)
		.pipe(plumber({
			errorHandler: errHandler
		}))
		.pipe(data(getJsonData))
		.pipe(pug({
			pretty: true
		}))
		.pipe(plumber.stop())
		.pipe(gulp.dest(path.pug.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
});

gulp.task('browser-sync', () => {
	browserSync({ server: {
		baseDir: path.html.dist
	}});
});

gulp.task('build:jade', (cb) => {
	runSequence('clean', ['sass', 'build:js', 'copy:img', 'jade:transform'], 'browser-sync', cb);
});

gulp.task('build:pug', (cb) => {
	runSequence('clean', ['sass', 'build:js', 'copy:img', 'pug:transform'], 'browser-sync', cb);
});

// Reload browser
gulp.task('reload', () => {
  browserSync.reload();
});

gulp.task('watch', () => {
	gulp.watch(path.style.src, ['sass']); // Watch sass files
	// gulp.watch(path.html.src, ['reload']); // Watch html files
	gulp.watch(path.images.src, ['copy:img']); // Watch img files
	gulp.watch(path.jade.src, ['jade:transform']); // Watch jade files
	gulp.watch(path.pug.src, ['pug:transform']); // Watch pug files
	gulp.watch(`${path.data.src}*.json`, ['pug:transform']); // Watch json files

	b.on('update', bundle); // on any dep update, runs the js bundler
	b.on('log', gutil.log); // output build logs to terminal
});

gulp.task('default', (cb) => {
	runSequence('build:pug', 'watch', cb);
});<commit_msg>gulpfile update<commit_after>'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';
import del from 'del';
// import ts from 'gulp-typescript';
import sass from 'gulp-sass';
import autoprefixer from 'gulp-autoprefixer';
import sourceMaps from 'gulp-sourcemaps';
import rename from 'gulp-rename';

import browserify from 'browserify';
import watchify from 'watchify';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import assign from 'lodash.assign';
import tsify from 'tsify';
import gutil from 'gulp-util';
import notify from 'gulp-notify';
import runSequence from 'run-sequence';
import uglify from 'gulp-uglify';
import plumber from 'gulp-plumber';

import pug from 'gulp-pug';
import data from 'gulp-data';
import gPath from 'path';

// let tsProject = ts.createProject("tsconfig.json");

const base = {
	src: './src',
	dist: './dist',
	folder: 'assets'
};

const path = {
	style: {
		src: `${base.src}/${base.folder}/scss/**/*.scss`,
		dist: `${base.dist}/${base.folder}/css/`
	},
	script: {
		src: `${base.src}/${base.folder}/ts/**/*.ts`,
		dist: `${base.dist}/${base.folder}/js/`
	},
	images: {
		src: `${base.src}/${base.folder}/images/**/*.+(jpg|jpeg|gif|png)`,
		dist: `${base.dist}/${base.folder}/images/`
	},
	html: {
		src: `${base.src}/*.html`,
		dist: `${base.dist}/`
	},
	jade: {
		src: `${base.src}/*.jade`,
		dist: `${base.dist}/`
	},
	pug: {
		src: `${base.src}/*.pug`,
		dist: `${base.dist}/`
	},
	data: {
		src: `${base.src}/`
	}
};

const customOpts = {
    basedir: '.',
    debug: true,
    entries: [`${base.src}/${base.folder}/ts/app.ts`],
    cache: {},
    packageCache: {},
    plugin: [tsify]
};
const errHandler = notify.onError("Error: <%= error.title %> <%= error.message %>");
//set browserify oprions
const opts = assign({}, watchify.args, customOpts);
//watchify od browserify
let b = watchify(browserify(opts));
//wrapp all files in one
let bundle = () => {
	return b.transform('babelify', {
	    	presets: ['env'],
	    	extensions: ['.ts']
	    })
		.bundle()
		.on('error', gutil.log.bind(gutil, 'Browserify Error'))
		.pipe(source('app-bundle.min.js'))
		.pipe(buffer())
		.pipe(sourceMaps.init({loadMaps: true}))
		// .pipe(uglify())
		.pipe(sourceMaps.write('./'))
		.pipe(gulp.dest(path.script.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
};

gulp.task('clean', () => {
	return del([`${base.dist}/*`]).then( paths => {
		let log = paths.length > 0 ? `Deleted files and folders:\n  ${paths.join('\n')}` : "No files to delete";
		console.log(log);
	});
});

gulp.task('build:js', bundle); // build the file

gulp.task('sass', () => {
	return gulp.src(path.style.src)
		.pipe(sourceMaps.init())
		.pipe(sass({outputStyle: 'compressed'}).on('error', errHandler))
		// .pipe(sass().on('error', errHandler))
		.pipe(autoprefixer())
		.pipe(rename({suffix: ".min"}))
		.pipe(sourceMaps.write('.'))
		.pipe(gulp.dest(path.style.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
});

gulp.task("copy:html", () => {
    return gulp.src(path.html.src)
        .pipe(gulp.dest(path.html.dist));
});

gulp.task("copy:img", () => {
    return gulp.src(path.images.src)
        .pipe(gulp.dest(path.images.dist))
        .pipe(browserSync.reload({ stream: true })); // Reload browser
});

let getJsonData = (file) => {
	delete require.cache[require.resolve(`${path.data.src}${gPath.basename(file.path)}.json`)];
	// console.log(require(`${path.data.src}${gPath.basename(file.path)}.json`));
 	return require(`${path.data.src}${gPath.basename(file.path)}.json`);
};

gulp.task('pug:transform', () => {
	return gulp.src(path.pug.src)
		.pipe(plumber({
			errorHandler: errHandler
		}))
		.pipe(data(getJsonData))
		.pipe(pug({
			pretty: true
		}))
		.pipe(plumber.stop())
		.pipe(gulp.dest(path.pug.dist))
		.pipe(browserSync.reload({ stream: true })); // Reload browser
});

gulp.task('browser-sync', () => {
	browserSync({ server: {
		baseDir: path.html.dist
	}});
});

gulp.task('build:pug', (cb) => {
	runSequence('clean', ['sass', 'build:js', 'copy:img', 'pug:transform'], 'browser-sync', cb);
});

// Reload browser
gulp.task('reload', () => {
  browserSync.reload();
});

gulp.task('watch', () => {
	gulp.watch(path.style.src, ['sass']); // Watch sass files
	// gulp.watch(path.html.src, ['reload']); // Watch html files
	gulp.watch(path.images.src, ['copy:img']); // Watch img files
	gulp.watch(path.jade.src, ['jade:transform']); // Watch jade files
	gulp.watch(path.pug.src, ['pug:transform']); // Watch pug files
	gulp.watch(`${path.data.src}*.json`, ['pug:transform']); // Watch json files

	b.on('update', bundle); // on any dep update, runs the js bundler
	b.on('log', gutil.log); // output build logs to terminal
});

gulp.task('default', (cb) => {
	runSequence('build:pug', 'watch', cb);
});<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.3.0-rc.2";
}
<commit_msg>Update version string to 2.3.0-rc.3<commit_after>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.3.0-rc.3";
}
<|endoftext|>


<commit_before>'use strict'
let utils = require('loader-utils');

module.exports = function(source){
    this.cacheable && this.cacheable();

    // get config
    let config = utils.getLoaderConfig(this);
    // config = utils.getLoaderConfig(this, config.use);

    // get the specific context involved, defaulting to Webpack's declared context
    let context = {
        context: config.context || utils.getLoaderConfig(this, "context"),
        content: source
    };

    // define a specific extension either through the query or through the options
    // if no extension given, default to the one sent aong
    // create the general basic filepath
    let default_path = "[path][name]." + (config.extension || "[ext]");
    let file_path = config.export || default_path;

    // lets sub out all the placeholders
    var file = utils.interpolateName(
        this,
        file_path,
        context
    );

    // output the file and remove it from the stream as we don't need it anymore.
    if (file_path !== "") {
        this.emitFile(file, source);
    }

    if (config.passSource) {
        return source;
    }
    else {
        return "";
    }
}
module.exports.raw = true;
<commit_msg>remove some comments<commit_after>'use strict'
let utils = require('loader-utils');

module.exports = function(source){
    this.cacheable && this.cacheable();

    // get config
    let config = utils.getLoaderConfig(this);

    // get the specific context involved, defaulting to Webpack's declared context
    let context = {
        context: config.context || utils.getLoaderConfig(this, "context"),
        content: source
    };

    // define a specific extension either through the query or through the options
    // if no extension given, default to the one sent aong
    // create the general basic filepath
    let default_path = "[path][name]." + (config.extension || "[ext]");
    let file_path = config.export || default_path;

    // lets sub out all the placeholders
    var file = utils.interpolateName(
        this,
        file_path,
        context
    );

    // output the file and remove it from the stream as we don't need it anymore.
    if (file_path !== "") {
        this.emitFile(file, source);
    }

    if (config.passSource) {
        return source;
    }
    else {
        return "";
    }
}
module.exports.raw = true;
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.layout = "2.6.0-pre.1.dev";
}
<commit_msg>Update version string to 2.6.0-pre.1<commit_after>if (enyo && enyo.version) {
	enyo.version.layout = "2.6.0-pre.1";
}
<|endoftext|>


<commit_before>var debug = require('debug')('loopback-ds-changed-mixin');
var utils = require('loopback-datasource-juggler/lib/utils');
var _ = require('lodash');

function changed(Model, options) {
  'use strict';

  // Trigger a warning when one of the defined callbacks is not found
  _.mapKeys(options.properties, function(callback, property) {
    if (typeof Model[callback] !== 'function') {
      console.warn('Callback %s for %s is not a model function', callback, property);
    }
  });

  debug('Changed mixin for Model %s', Model.modelName);

  var loopback = require('loopback');

  // This is the structure that we want to return
  function ChangeSet(changeset) {
    this.ids = changeset.ids;
    this.values = changeset.values;
  }
  ChangeSet.prototype.getIdList = function() {
    return Object.keys(this.ids);
  };
  ChangeSet.prototype.getIds = function() {
    return this.ids;
  };
  ChangeSet.prototype.getId = function(id) {
    return this.ids[id];
  };
  ChangeSet.prototype.getValueList = function() {
    return Object.keys(this.values);
  };
  ChangeSet.prototype.getValues = function() {
    return this.values;
  };
  ChangeSet.prototype.getValue = function(value) {
    return this.values[value];
  };

  /**
   * Helper method that converts the set of items to a set of property
   * In the future this structure should be used directly by the code
   * that detects the changes.
   *
   * Input:
   *
   * {
   *    '5586c51948fb091e068f80f4': {
   *        status: 'pending'
   *    },
   *    '5586c51948fb091e068f80f5': {
   *        status: 'pending'
   *    }
   * }
   *
   * Output:
   *
   * {
   *    status: {
   *        ids: {
   *            '5586c58848fb091e068f8115': 'pending',
   *            '5586c58848fb091e068f8116': 'pending'
   *        },
   *        values: {
   *            pending: [
   *                '5586c58848fb091e068f8115',
   *                '5586c58848fb091e068f8116'
   *            ]
   *        }
   *    }
   * }
   *
   * @returns {{}}
   */
  function convertItemsToProperties(items) {

    // The object that contains the converted items
    var result = {};

    // Loop through all the inserted items
    _.mapKeys(items, function(changes, itemId) {

      // Loop through changes for this item
      _.mapKeys(changes, function(value, property) {

        // Add basic structure to hold ids and values
        if (_.isUndefined(result[property])) {
          result[property] = { ids: {}, values: {} };
        }

        // Create an array to hold ids for each value
        if (_.isUndefined(result[property].values[value])) {
          result[property].values[value] = [];
        }

        // Create an object { itemId: value }
        result[property].ids[itemId] = value;

        // Enter itemId in the array for this value
        result[property].values[value].push(itemId);
      });

    });

    var changedProperties = {};
    _.mapKeys(result, function(changeset, property) {
      changedProperties[property] = new ChangeSet(changeset);
    });

    return changedProperties;
  }

  /**
   * Determine which properties are changed and store them in changedItems
   */
  Model.observe('before save', function(ctx, next) {
    // Do nothing if a new instance if being created.
    if (ctx.instance && ctx.isNewInstance) {
      return next();
    }

    if (!ctx.hookState.changedItems) {
      ctx.hookState.changedItems = [];
    }

    var properties = _.keys(options.properties);

    debug('before save ctx.instance: %o', ctx.instance);
    debug('before save ctx.currentInstance: %o', ctx.currentInstance);
    debug('before save ctx.data: %o', ctx.data);
    debug('before save ctx.where: %o', ctx.where);

    if (ctx.currentInstance) {
      debug('Detected prototype.updateAttributes');

      ctx.hookState.changedItems = Model.getChangedProperties(ctx.currentInstance, ctx.data, properties);

      next();
    } else if (ctx.instance) {
      debug('Working with existing instance %o', ctx.instance);
      // Figure out wether this item has changed properties.
      ctx.instance.itemHasChangedProperties(ctx.instance, properties)
        .then(function(changed) {
          ctx.hookState.changedItems = changed;
          next();
        }).catch(next);
    } else {
      debug('anything else: upsert, updateAll');
      // Figure out which items have changed properties.
      Model.itemsWithChangedProperties(ctx.where, ctx.data, properties)
        .then(function(changed) {
          ctx.hookState.changedItems = changed;
          next();
        }).catch(next);
    }
  });

  Model.observe('after save', function(ctx, next) {

    // Convert the changeItems to Properties
    if (ctx.hookState.changedItems && !_.isEmpty(ctx.hookState.changedItems)) {

      var properties = convertItemsToProperties(ctx.hookState.changedItems);

      debug('after save changedProperties %o', properties);

      _.mapKeys(properties, function(changeset, property) {
        var callback = options.properties[property];
        if (typeof Model[callback] !== 'function') {
          console.warn('Function %s not found on Model', callback);
          return false;
        }
        debug('after save: invoke %s with %o', callback, changeset);
        Model[callback](changeset);
      });

      next();
    } else {
      next();
    }

  });

  /**
   * Searches for items with properties that differ from a specific set.
   *
   * @param {Object} conditions Where clause detailing items to compare.
   * @param {Object} properties Properties to compare with the found instances.
   * @param {Function} cb A Cllback function.
   * @returns {Array} Returns a list of Model instance Ids whose data differ from
   *                  that in the properties argument.
   */
  Model.itemsWithChangedProperties = function(conditions, newVals, properties, cb) {
    debug('itemsWithChangedProperties: Looking for items with changed properties...');
    debug('itemsWithChangedProperties: conditions is: %o', conditions);
    debug('itemsWithChangedProperties: newVals is: %o', newVals);
    debug('itemsWithChangedProperties: properties is 1 : %o', properties);
    cb = cb || utils.createPromiseCallback();

    conditions = conditions || {};
    newVals = typeof newVals.toJSON === 'function' ? newVals.toJSON() : newVals || {};
    properties = properties || {};

    var filterFields = [
      Model.getIdName()
    ];

    // Build up a list of property conditions to include in the query.
    var propertyConditions = {or: []};
    _.forEach(newVals, function(value, key) {
      if (_.includes(properties, key)) {
        var fieldFilter = {};
        fieldFilter[key] = {'neq': value};
        propertyConditions.or.push(fieldFilter);
        filterFields.push(key);
      }
    });

    if (!propertyConditions.or.length) propertyConditions = {};

    debug('itemsWithChangedProperties: propertyConditions 1 : %o', propertyConditions);

    // If there are no property conditions, do nothing.
    if (_.isEmpty(propertyConditions)) {
      process.nextTick(function() {
        cb(null, false);
      });
      return cb.promise;
    }

    // Build the final filter.
    var filter = {
      fields: filterFields,
      where: {
        and: [propertyConditions, conditions]
      }
    };

    debug('itemsWithChangedProperties: propertyConditions 2 : %o', propertyConditions);
    debug('itemsWithChangedProperties: filter Fields %o', filterFields);
    debug('itemsWithChangedProperties: conditions %o', conditions);
    debug('itemsWithChangedProperties: final filter %o', filter);

    Model.find(filter)
      .then(function(results) {

        debug('itemsWithChangedProperties: filter results %o', results);

        var changedProperties = {};

        results.map(function(oldVals) {

          debug('itemsWithChangedProperties: oldVals %o', oldVals);
          debug('itemsWithChangedProperties: newVals %o', newVals);

          //changedProperties[oldVals.id] = {};

          var changed = {};

          properties.map(function(property) {

            debug('itemsWithChangedProperties: Matching property %s', property);

            if (newVals[property] !== undefined) {

              var newVal = newVals[property];

              debug('itemsWithChangedProperties:   - newVal %s : %s : ', property, newVal);

              if (!oldVals[property]) {
                changed[property] = newVal;
                debug('itemsWithChangedProperties:   - no oldVal %s : %s : ', property, newVal);
              } else if (newVal !== oldVals[property]) {
                var oldVal = oldVals[property];
                debug('itemsWithChangedProperties:   - oldVal %s : %s : ', property, newVal);

                changed[property] = newVal;
              }

            }
          });

          debug('itemsWithChangedProperties: changed %o', changed);
          changedProperties[oldVals.id] = changed;

        });

        debug('itemsWithChangedProperties: changedProperties %o', changedProperties);
        cb(null, changedProperties);
      }).catch(cb);

    return cb.promise;
  };

  /**
   * Compare self with data to see if specific properties have been altered.
   *
   * @param {Object} data Target object to compare with.
   * @param {Array} properties List of properties to be chacked.
   * @returns {Boolean} Returns true if the properties have been altered.
   */
  Model.prototype.itemHasChangedProperties = function(data, properties, cb) {
    cb = cb || utils.createPromiseCallback();

    properties = properties || {};

    if (_.isEmpty(properties)) {
      process.nextTick(function() {
        cb(null, false);
      });
      return cb.promise;
    }

    Model.findById(this.getId())
      .then(function(instance) {
        var changedProperties = Model.getChangedProperties(instance, data, properties);
        debug('itemHasChangedProperties: found supposedly changed items: %o', changedProperties);
        cb(null, changedProperties);
      }).catch(cb);

    return cb.promise;
  };

  /**
   * Compare source and target objects to see if specific properties have
   * been altered.
   *
   * @param {Object} source Source object to compare against.
   * @param {Object} target Target object to compare with.
   * @param {Array} properties List of properties to be chacked.
   * @returns {Boolean} Returns true if the properties have been altered.
   */
  Model.propertiesChanged = function(source, target, properties) {
    debug('comparing source %o with target %o in properties %o', source, target, properties);

    var changed = false;
    _.forEach(properties, function(key) {
      debug('checking property %s ', key);
      if (target[key]) {
        if (!source[key] || target[key] !== source[key]) {
          changed = true;
        }
      }
    });
    if (changed) {
      debug('propertiesChanged: properties were changed');
    }
    return changed;
  };

  Model.getChangedProperties = function(oldVals, newVals, properties) {
    debug('getChangedProperties: comparing oldVals %o with newVals %o in properties %o', oldVals, newVals, properties);

    var itemId = oldVals[Model.getIdName()];
    var changedProperties = {};
    changedProperties[itemId] = {};

    _.forEach(properties, function(key) {
      debug('getChangedProperties: - checking property %s ', key);

      if (newVals[key]) {
        var newVal = newVals[key];
        debug('getChangedProperties:   - new value %s ', newVal);

        if (!oldVals[key] || newVal !== oldVals[key]) {
          debug('getChangedProperties:   - changed or new value %s itemId %s', newVal, itemId);

          changedProperties[itemId][key] = newVal;
        }
      }
    });
    if (!_.isEmpty(changedProperties[itemId])) {
      debug('getChangedProperties: Properties were changed %o', changedProperties);
      return changedProperties;
    }
    return false;
  };

  Model.extractChangedItemIds = function(items) {
    return _.pluck(items, Model.getIdName());
  };

}

module.exports = function mixin(app) {
  app.loopback.modelBuilder.mixins.define('Changed', changed);
};
<commit_msg>Trigger warning when a property defined in the mixin is not found on the model<commit_after>var debug = require('debug')('loopback-ds-changed-mixin');
var utils = require('loopback-datasource-juggler/lib/utils');
var _ = require('lodash');

function changed(Model, options) {
  'use strict';

  // Trigger a warning and remove the property from the watchlist when one of
  // the property is not found on the model or the defined callback is not found
  _.mapKeys(options.properties, function(callback, property) {
    var removeProperty = false;
    if (_.isUndefined(Model.definition.properties[property])) {
      console.warn('Property %s on %s is undefined', property, Model.modelName);
      removeProperty = true;
    }

    if (typeof Model[callback] !== 'function') {
      console.warn('Callback %s for %s is not a model function', callback, property);
      removeProperty = true;
    }

    if(removeProperty) {
      debug('Remove Changed %s for %s ', property, Model.modelName);
      delete options.properties[property];
    }
  });

  debug('Changed mixin for Model %s with properties', Model.modelName,
    options.properties);

  var loopback = require('loopback');

  // This is the structure that we want to return
  function ChangeSet(changeset) {
    this.ids = changeset.ids;
    this.values = changeset.values;
  }
  ChangeSet.prototype.getIdList = function() {
    return Object.keys(this.ids);
  };
  ChangeSet.prototype.getIds = function() {
    return this.ids;
  };
  ChangeSet.prototype.getId = function(id) {
    return this.ids[id];
  };
  ChangeSet.prototype.getValueList = function() {
    return Object.keys(this.values);
  };
  ChangeSet.prototype.getValues = function() {
    return this.values;
  };
  ChangeSet.prototype.getValue = function(value) {
    return this.values[value];
  };

  /**
   * Helper method that converts the set of items to a set of property
   * In the future this structure should be used directly by the code
   * that detects the changes.
   *
   * Input:
   *
   * {
   *    '5586c51948fb091e068f80f4': {
   *        status: 'pending'
   *    },
   *    '5586c51948fb091e068f80f5': {
   *        status: 'pending'
   *    }
   * }
   *
   * Output:
   *
   * {
   *    status: {
   *        ids: {
   *            '5586c58848fb091e068f8115': 'pending',
   *            '5586c58848fb091e068f8116': 'pending'
   *        },
   *        values: {
   *            pending: [
   *                '5586c58848fb091e068f8115',
   *                '5586c58848fb091e068f8116'
   *            ]
   *        }
   *    }
   * }
   *
   * @returns {{}}
   */
  function convertItemsToProperties(items) {

    // The object that contains the converted items
    var result = {};

    // Loop through all the inserted items
    _.mapKeys(items, function(changes, itemId) {

      // Loop through changes for this item
      _.mapKeys(changes, function(value, property) {

        // Add basic structure to hold ids and values
        if (_.isUndefined(result[property])) {
          result[property] = { ids: {}, values: {} };
        }

        // Create an array to hold ids for each value
        if (_.isUndefined(result[property].values[value])) {
          result[property].values[value] = [];
        }

        // Create an object { itemId: value }
        result[property].ids[itemId] = value;

        // Enter itemId in the array for this value
        result[property].values[value].push(itemId);
      });

    });

    var changedProperties = {};
    _.mapKeys(result, function(changeset, property) {
      changedProperties[property] = new ChangeSet(changeset);
    });

    return changedProperties;
  }

  /**
   * Determine which properties are changed and store them in changedItems
   */
  Model.observe('before save', function(ctx, next) {
    // Do nothing if a new instance if being created.
    if (ctx.instance && ctx.isNewInstance) {
      return next();
    }

    if (!ctx.hookState.changedItems) {
      ctx.hookState.changedItems = [];
    }

    var properties = _.keys(options.properties);

    debug('before save ctx.instance: %o', ctx.instance);
    debug('before save ctx.currentInstance: %o', ctx.currentInstance);
    debug('before save ctx.data: %o', ctx.data);
    debug('before save ctx.where: %o', ctx.where);

    if (ctx.currentInstance) {
      debug('Detected prototype.updateAttributes');

      ctx.hookState.changedItems = Model.getChangedProperties(ctx.currentInstance, ctx.data, properties);

      next();
    } else if (ctx.instance) {
      debug('Working with existing instance %o', ctx.instance);
      // Figure out wether this item has changed properties.
      ctx.instance.itemHasChangedProperties(ctx.instance, properties)
        .then(function(changed) {
          ctx.hookState.changedItems = changed;
          next();
        }).catch(next);
    } else {
      debug('anything else: upsert, updateAll');
      // Figure out which items have changed properties.
      Model.itemsWithChangedProperties(ctx.where, ctx.data, properties)
        .then(function(changed) {
          ctx.hookState.changedItems = changed;
          next();
        }).catch(next);
    }
  });

  Model.observe('after save', function(ctx, next) {

    // Convert the changeItems to Properties
    if (ctx.hookState.changedItems && !_.isEmpty(ctx.hookState.changedItems)) {

      var properties = convertItemsToProperties(ctx.hookState.changedItems);

      debug('after save changedProperties %o', properties);

      _.mapKeys(properties, function(changeset, property) {
        var callback = options.properties[property];
        if (typeof Model[callback] !== 'function') {
          console.warn('Function %s not found on Model', callback);
          return false;
        }
        debug('after save: invoke %s with %o', callback, changeset);
        Model[callback](changeset);
      });

      next();
    } else {
      next();
    }

  });

  /**
   * Searches for items with properties that differ from a specific set.
   *
   * @param {Object} conditions Where clause detailing items to compare.
   * @param {Object} properties Properties to compare with the found instances.
   * @param {Function} cb A Cllback function.
   * @returns {Array} Returns a list of Model instance Ids whose data differ from
   *                  that in the properties argument.
   */
  Model.itemsWithChangedProperties = function(conditions, newVals, properties, cb) {
    debug('itemsWithChangedProperties: Looking for items with changed properties...');
    debug('itemsWithChangedProperties: conditions is: %o', conditions);
    debug('itemsWithChangedProperties: newVals is: %o', newVals);
    debug('itemsWithChangedProperties: properties is 1 : %o', properties);
    cb = cb || utils.createPromiseCallback();

    conditions = conditions || {};
    newVals = typeof newVals.toJSON === 'function' ? newVals.toJSON() : newVals || {};
    properties = properties || {};

    var filterFields = [
      Model.getIdName()
    ];

    // Build up a list of property conditions to include in the query.
    var propertyConditions = {or: []};
    _.forEach(newVals, function(value, key) {
      if (_.includes(properties, key)) {
        var fieldFilter = {};
        fieldFilter[key] = {'neq': value};
        propertyConditions.or.push(fieldFilter);
        filterFields.push(key);
      }
    });

    if (!propertyConditions.or.length) propertyConditions = {};

    debug('itemsWithChangedProperties: propertyConditions 1 : %o', propertyConditions);

    // If there are no property conditions, do nothing.
    if (_.isEmpty(propertyConditions)) {
      process.nextTick(function() {
        cb(null, false);
      });
      return cb.promise;
    }

    // Build the final filter.
    var filter = {
      fields: filterFields,
      where: {
        and: [propertyConditions, conditions]
      }
    };

    debug('itemsWithChangedProperties: propertyConditions 2 : %o', propertyConditions);
    debug('itemsWithChangedProperties: filter Fields %o', filterFields);
    debug('itemsWithChangedProperties: conditions %o', conditions);
    debug('itemsWithChangedProperties: final filter %o', filter);

    Model.find(filter)
      .then(function(results) {

        debug('itemsWithChangedProperties: filter results %o', results);

        var changedProperties = {};

        results.map(function(oldVals) {

          debug('itemsWithChangedProperties: oldVals %o', oldVals);
          debug('itemsWithChangedProperties: newVals %o', newVals);

          //changedProperties[oldVals.id] = {};

          var changed = {};

          properties.map(function(property) {

            debug('itemsWithChangedProperties: Matching property %s', property);

            if (newVals[property] !== undefined) {

              var newVal = newVals[property];

              debug('itemsWithChangedProperties:   - newVal %s : %s : ', property, newVal);

              if (!oldVals[property]) {
                changed[property] = newVal;
                debug('itemsWithChangedProperties:   - no oldVal %s : %s : ', property, newVal);
              } else if (newVal !== oldVals[property]) {
                var oldVal = oldVals[property];
                debug('itemsWithChangedProperties:   - oldVal %s : %s : ', property, newVal);

                changed[property] = newVal;
              }

            }
          });

          debug('itemsWithChangedProperties: changed %o', changed);
          changedProperties[oldVals.id] = changed;

        });

        debug('itemsWithChangedProperties: changedProperties %o', changedProperties);
        cb(null, changedProperties);
      }).catch(cb);

    return cb.promise;
  };

  /**
   * Compare self with data to see if specific properties have been altered.
   *
   * @param {Object} data Target object to compare with.
   * @param {Array} properties List of properties to be chacked.
   * @returns {Boolean} Returns true if the properties have been altered.
   */
  Model.prototype.itemHasChangedProperties = function(data, properties, cb) {
    cb = cb || utils.createPromiseCallback();

    properties = properties || {};

    if (_.isEmpty(properties)) {
      process.nextTick(function() {
        cb(null, false);
      });
      return cb.promise;
    }

    Model.findById(this.getId())
      .then(function(instance) {
        var changedProperties = Model.getChangedProperties(instance, data, properties);
        debug('itemHasChangedProperties: found supposedly changed items: %o', changedProperties);
        cb(null, changedProperties);
      }).catch(cb);

    return cb.promise;
  };

  /**
   * Compare source and target objects to see if specific properties have
   * been altered.
   *
   * @param {Object} source Source object to compare against.
   * @param {Object} target Target object to compare with.
   * @param {Array} properties List of properties to be chacked.
   * @returns {Boolean} Returns true if the properties have been altered.
   */
  Model.propertiesChanged = function(source, target, properties) {
    debug('comparing source %o with target %o in properties %o', source, target, properties);

    var changed = false;
    _.forEach(properties, function(key) {
      debug('checking property %s ', key);
      if (target[key]) {
        if (!source[key] || target[key] !== source[key]) {
          changed = true;
        }
      }
    });
    if (changed) {
      debug('propertiesChanged: properties were changed');
    }
    return changed;
  };

  Model.getChangedProperties = function(oldVals, newVals, properties) {
    debug('getChangedProperties: comparing oldVals %o with newVals %o in properties %o', oldVals, newVals, properties);

    var itemId = oldVals[Model.getIdName()];
    var changedProperties = {};
    changedProperties[itemId] = {};

    _.forEach(properties, function(key) {
      debug('getChangedProperties: - checking property %s ', key);

      if (newVals[key]) {
        var newVal = newVals[key];
        debug('getChangedProperties:   - new value %s ', newVal);

        if (!oldVals[key] || newVal !== oldVals[key]) {
          debug('getChangedProperties:   - changed or new value %s itemId %s', newVal, itemId);

          changedProperties[itemId][key] = newVal;
        }
      }
    });
    if (!_.isEmpty(changedProperties[itemId])) {
      debug('getChangedProperties: Properties were changed %o', changedProperties);
      return changedProperties;
    }
    return false;
  };

  Model.extractChangedItemIds = function(items) {
    return _.pluck(items, Model.getIdName());
  };

}

module.exports = function mixin(app) {
  app.loopback.modelBuilder.mixins.define('Changed', changed);
};
<|endoftext|>


<commit_before>import {src, dest, watch, parallel, series} from 'gulp';
import del from 'del';
import postcss from 'gulp-postcss';
import autoprefixer from 'autoprefixer';
import atImport from 'postcss-import';
import minify from 'cssnano';
import simpleVars from 'postcss-simple-vars';
import rename from 'gulp-rename';
import svgo from 'gulp-svgo';
import imagemin from 'gulp-imagemin';

// Sources
const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const CSS_GLOB = `${SRC_DIR}/**/*.css`;
const IMG_GLOB = `${SRC_DIR}/images/**/*`;

// Clean task
export function clean() {
  return del([BUILD_DIR]);
}

// CSS
const processors = [
  atImport,
  simpleVars,
  autoprefixer({browsers: ['last 2 versions']})
];
export function styles() {
  return src(CSS_GLOB)
    .pipe(postcss(processors))
    .pipe(postcss([minify]))
    .pipe(rename({suffix: '.min'}))
    .pipe(dest(BUILD_DIR));
}

// Images
export function images() {
  return src(IMG_GLOB, {base: SRC_DIR})
    .pipe(svgo())
    .pipe(imagemin())
    .pipe(dest(BUILD_DIR));
}

// Pipe other files
export function misc() {
  return src([`${SRC_DIR}/**/*`, `!${CSS_GLOB}`, `!${IMG_GLOB}`])
    .pipe(dest(BUILD_DIR));
}

export function watchSrc() {
  watch(CSS_GLOB, styles);
  watch(IMG_GLOB, images);
};

export const mainTasks = parallel(styles, images, misc);
export const build = series(clean, mainTasks);
export const dev = series(clean, mainTasks, watchSrc);

export default build;
<commit_msg>Dont export watch task<commit_after>import {src, dest, watch, parallel, series} from 'gulp';
import del from 'del';
import postcss from 'gulp-postcss';
import autoprefixer from 'autoprefixer';
import atImport from 'postcss-import';
import minify from 'cssnano';
import simpleVars from 'postcss-simple-vars';
import rename from 'gulp-rename';
import svgo from 'gulp-svgo';
import imagemin from 'gulp-imagemin';

// Sources
const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const CSS_GLOB = `${SRC_DIR}/**/*.css`;
const IMG_GLOB = `${SRC_DIR}/images/**/*`;

// Clean task
export function clean() {
  return del([BUILD_DIR]);
}

// CSS
const processors = [
  atImport,
  simpleVars,
  autoprefixer({browsers: ['last 2 versions']})
];
export function styles() {
  return src(CSS_GLOB)
    .pipe(postcss(processors))
    .pipe(postcss([minify]))
    .pipe(rename({suffix: '.min'}))
    .pipe(dest(BUILD_DIR));
}

// Images
export function images() {
  return src(IMG_GLOB, {base: SRC_DIR})
    .pipe(svgo())
    .pipe(imagemin())
    .pipe(dest(BUILD_DIR));
}

// Pipe other files
export function misc() {
  return src([`${SRC_DIR}/**/*`, `!${CSS_GLOB}`, `!${IMG_GLOB}`])
    .pipe(dest(BUILD_DIR));
}

function watchSrc() {
  watch(CSS_GLOB, styles);
  watch(IMG_GLOB, images);
};

export const mainTasks = parallel(styles, images, misc);
export const build = series(clean, mainTasks);
export const dev = series(clean, mainTasks, watchSrc);

export default build;
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.4.0";
}
<commit_msg>ENYO-4044: Update version to 2.5.0-pre.1<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.0-pre.1";
}
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var _ = require('lodash');
var utils = require('../../../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;

/**
 * Model.toObject()
 *
 * Returns a cloned object containing just the model
 * values. Useful for doing operations on the current values
 * minus the instance methods.
 *
 * @param {Object} context, Waterline collection instance
 * @param {Object} proto, model prototype
 * @api public
 * @return {Object}
 */

var toObject = module.exports = function(context, proto) {

  var self = this;

  this.context = context;
  this.proto = proto;

  // Hold joins used in the query
  this.usedJoins = [];

  // Create an object that can hold the values to be returned
  this.object = {};

  // Run methods to add and modify values to the above object
  this.addAssociations();
  this.addProperties();
  this.makeObject();
  this.filterJoins();
  this.filterFunctions();

  // Ok now we want to create a POJO that can be serialized for use in a response.
  // This is after all usually called in a toJSON method so lets make sure its all
  // good in there. This could be faster and safer I recon.
  try {

    // Stringify/parse the object
    var _obj = JSON.parse(JSON.stringify(this.object));

    return _obj;

  // Return a nicer error message than just throwing the json parse message
  } catch (e) {
    var err = new Error();
    err.message = 'There was an error turning the model into an object.';
    err.data = self.object;
    throw err;
  }
};

/**
 * Add Association Keys
 *
 * If a showJoins flag is active, add all association keys.
 *
 * @param {Object} keys
 * @api private
 */

toObject.prototype.addAssociations = function() {
  var self = this;

  if (!this.proto._properties) return;
  if (!this.proto._properties.showJoins) return;

  // Copy prototype over for attributes
  for (var association in this.proto.associations) {

    // Handle hasMany attributes
    if (hasOwnProperty(this.proto.associations[association], 'value')) {

      var records = [];
      var values = this.proto.associations[association].value;

      values.forEach(function(record) {
        if (typeof record !== 'object') return;
        // Since `typeof null` === `"object"`, we should also check for that case:
        if (record === null) return;
        var item = Object.create(record.__proto__);
        Object.keys(record).forEach(function(key) {
          item[key] = _.cloneDeep(record[key]);
        });
        records.push(item);
      });

      this.object[association] = records;
      continue;
    }

    // Handle belongsTo attributes
    var record = this.proto[association];
    var item;

    // Check if the association foreign key is a date. If so set the object's
    // association and continue. Manual check here is needed because _.isObject
    // matches dates and you will end up with a loop that never exits.
    if (_.isDate(record)) {

      item = new Date(record);
      _.extend(item.__proto__ , record.__proto__);

      this.object[association] = item;
    }

    // Is the record is a populated object, create a new object from it.
    // _.isObject() does not match null, so we're good here.
    else if (_.isObject(record) && !Array.isArray(record)) {

      item = Object.create(record.__proto__);

      Object.keys(record).forEach(function(key) {
        item[key] = _.cloneDeep(record[key]);
      });

      this.object[association] = item;
    }

    else if (!_.isUndefined(record)) {
      this.object[association] = record;
    }
  }
};

/**
 * Add Properties
 *
 * Copies over non-association attributes to the newly created object.
 *
 * @api private
 */

toObject.prototype.addProperties = function() {
  var self = this;

  Object.keys(this.proto).forEach(function(key) {
    if (hasOwnProperty(self.object, key)) return;
    self.object[key] = _.cloneDeep(self.proto[key]);
  });

};

/**
 * Make Object
 *
 * Runs toJSON on all associated values
 *
 * @api private
 */

toObject.prototype.makeObject = function() {
  var self = this;

  if (!this.proto._properties) return;
  if (!this.proto._properties.showJoins) return;

  // Handle Joins
  Object.keys(this.proto.associations).forEach(function(association) {

    // Don't run toJSON on records that were not populated
    if (!self.proto._properties || !self.proto._properties.joins) return;

    // Build up a join key name based on the attribute's model/collection name
    var joinsName = association;
    if (self.context._attributes[association].model) joinsName = self.context._attributes[association].model.toLowerCase();
    if (self.context._attributes[association].collection) joinsName = self.context._attributes[association].collection.toLowerCase();

    // Check if the join was used
    if (self.proto._properties.joins.indexOf(joinsName) < 0 && self.proto._properties.joins.indexOf(association) < 0) return;
    self.usedJoins.push(association);

    // Call toJSON on each associated record
    if (Array.isArray(self.object[association])) {
      var records = [];

      self.object[association].forEach(function(item) {
        if (!hasOwnProperty(item.__proto__, 'toJSON')) return;
        records.push(item.toJSON());
      });

      self.object[association] = records;
      return;
    }

    if (!self.object[association]) return;

    // Association was null or not valid
    // (don't try to `hasOwnProperty` it so we don't throw)
    if (typeof self.object[association] !== 'object') {
      self.object[association] = self.object[association];
      return;
    }

    if (!hasOwnProperty(self.object[association].__proto__, 'toJSON')) return;
    self.object[association] = self.object[association].toJSON();
  });

};

/**
 * Remove Non-Joined Associations
 *
 * @api private
 */

toObject.prototype.filterJoins = function() {
  var attributes = this.context._attributes;
  var properties = this.proto._properties;

  for (var attribute in attributes) {
    if (!hasOwnProperty(attributes[attribute], 'model') && !hasOwnProperty(attributes[attribute], 'collection')) continue;

    // If no properties and a collection attribute, delete the association and return
    if (!properties && hasOwnProperty(attributes[attribute], 'collection')) {
      delete this.object[attribute];
      continue;
    }

    // If showJoins is false remove the association object
    if (properties && !properties.showJoins) {

      // Don't delete belongs to keys
      if (!attributes[attribute].model) delete this.object[attribute];
    }

    if (properties && properties.joins) {
      if (this.usedJoins.indexOf(attribute) < 0) {

        // Don't delete belongs to keys
        if (!attributes[attribute].model) delete this.object[attribute];
      }
    }
  }
};

/**
 * Filter Functions
 *
 * @api private
 */

toObject.prototype.filterFunctions = function() {
  for (var key in this.object) {
    if (typeof this.object[key] === 'function') {
      delete this.object[key];
    }
  }
};
<commit_msg>remove clone deep<commit_after>/**
 * Module dependencies
 */

var _ = require('lodash');
var utils = require('../../../utils/helpers');
var hasOwnProperty = utils.object.hasOwnProperty;

/**
 * Model.toObject()
 *
 * Returns an object containing just the model values. Useful for doing
 * operations on the current values minus the instance methods.
 *
 * @param {Object} context, Waterline collection instance
 * @param {Object} proto, model prototype
 * @api public
 * @return {Object}
 */

var toObject = module.exports = function(context, proto) {

  var self = this;

  this.context = context;
  this.proto = proto;

  // Hold joins used in the query
  this.usedJoins = [];

  // Create an object that can hold the values to be returned
  this.object = {};

  // Run methods to add and modify values to the above object
  this.addAssociations();
  this.addProperties();
  this.makeObject();
  this.filterJoins();
  this.filterFunctions();

  // Ok now we want to create a POJO that can be serialized for use in a response.
  // This is after all usually called in a toJSON method so lets make sure its all
  // good in there. This could be faster and safer I recon.
  try {

    // Stringify/parse the object
    var _obj = JSON.parse(JSON.stringify(this.object));

    return _obj;

  // Return a nicer error message than just throwing the json parse message
  } catch (e) {
    var err = new Error();
    err.message = 'There was an error turning the model into an object.';
    err.data = self.object;
    throw err;
  }
};

/**
 * Add Association Keys
 *
 * If a showJoins flag is active, add all association keys.
 *
 * @param {Object} keys
 * @api private
 */

toObject.prototype.addAssociations = function() {
  var self = this;

  if (!this.proto._properties) return;
  if (!this.proto._properties.showJoins) return;

  // Copy prototype over for attributes
  for (var association in this.proto.associations) {

    // Handle hasMany attributes
    if (hasOwnProperty(this.proto.associations[association], 'value')) {

      var records = [];
      var values = this.proto.associations[association].value;

      values.forEach(function(record) {
        if (typeof record !== 'object') return;
        // Since `typeof null` === `"object"`, we should also check for that case:
        if (record === null) return;
        var item = Object.create(record.__proto__);
        Object.keys(record).forEach(function(key) {
          item[key] = _.cloneDeep(record[key]);
        });
        records.push(item);
      });

      this.object[association] = records;
      continue;
    }

    // Handle belongsTo attributes
    var record = this.proto[association];
    var item;

    // Check if the association foreign key is a date. If so set the object's
    // association and continue. Manual check here is needed because _.isObject
    // matches dates and you will end up with a loop that never exits.
    if (_.isDate(record)) {

      item = new Date(record);
      _.extend(item.__proto__ , record.__proto__);

      this.object[association] = item;
    }

    // Is the record is a populated object, create a new object from it.
    // _.isObject() does not match null, so we're good here.
    else if (_.isObject(record) && !Array.isArray(record)) {

      item = Object.create(record.__proto__);

      Object.keys(record).forEach(function(key) {
        item[key] = record[key];
      });

      this.object[association] = item;
    }

    else if (!_.isUndefined(record)) {
      this.object[association] = record;
    }
  }
};

/**
 * Add Properties
 *
 * Copies over non-association attributes to the newly created object.
 *
 * @api private
 */

toObject.prototype.addProperties = function() {
  var self = this;

  Object.keys(this.proto).forEach(function(key) {
    if (hasOwnProperty(self.object, key)) return;
    self.object[key] = self.proto[key];
  });

};

/**
 * Make Object
 *
 * Runs toJSON on all associated values
 *
 * @api private
 */

toObject.prototype.makeObject = function() {
  var self = this;

  if (!this.proto._properties) return;
  if (!this.proto._properties.showJoins) return;

  // Handle Joins
  Object.keys(this.proto.associations).forEach(function(association) {

    // Don't run toJSON on records that were not populated
    if (!self.proto._properties || !self.proto._properties.joins) return;

    // Build up a join key name based on the attribute's model/collection name
    var joinsName = association;
    if (self.context._attributes[association].model) joinsName = self.context._attributes[association].model.toLowerCase();
    if (self.context._attributes[association].collection) joinsName = self.context._attributes[association].collection.toLowerCase();

    // Check if the join was used
    if (self.proto._properties.joins.indexOf(joinsName) < 0 && self.proto._properties.joins.indexOf(association) < 0) return;
    self.usedJoins.push(association);

    // Call toJSON on each associated record
    if (Array.isArray(self.object[association])) {
      var records = [];

      self.object[association].forEach(function(item) {
        if (!hasOwnProperty(item.__proto__, 'toJSON')) return;
        records.push(item.toJSON());
      });

      self.object[association] = records;
      return;
    }

    if (!self.object[association]) return;

    // Association was null or not valid
    // (don't try to `hasOwnProperty` it so we don't throw)
    if (typeof self.object[association] !== 'object') {
      self.object[association] = self.object[association];
      return;
    }

    if (!hasOwnProperty(self.object[association].__proto__, 'toJSON')) return;
    self.object[association] = self.object[association].toJSON();
  });

};

/**
 * Remove Non-Joined Associations
 *
 * @api private
 */

toObject.prototype.filterJoins = function() {
  var attributes = this.context._attributes;
  var properties = this.proto._properties;

  for (var attribute in attributes) {
    if (!hasOwnProperty(attributes[attribute], 'model') && !hasOwnProperty(attributes[attribute], 'collection')) continue;

    // If no properties and a collection attribute, delete the association and return
    if (!properties && hasOwnProperty(attributes[attribute], 'collection')) {
      delete this.object[attribute];
      continue;
    }

    // If showJoins is false remove the association object
    if (properties && !properties.showJoins) {

      // Don't delete belongs to keys
      if (!attributes[attribute].model) delete this.object[attribute];
    }

    if (properties && properties.joins) {
      if (this.usedJoins.indexOf(attribute) < 0) {

        // Don't delete belongs to keys
        if (!attributes[attribute].model) delete this.object[attribute];
      }
    }
  }
};

/**
 * Filter Functions
 *
 * @api private
 */

toObject.prototype.filterFunctions = function() {
  for (var key in this.object) {
    if (typeof this.object[key] === 'function') {
      delete this.object[key];
    }
  }
};
<|endoftext|>


<commit_before>module.exports = {
    plugins: [
        'vue'
    ],
    extends: [
        'vast',
        'plugin:vue/recommended'
    ],
    rules: {
        // Possible errors:
        // this rule only covers case when used in code like: Vue.component...
        'vue/no-shared-component-data': 2,
        'vue/require-valid-default-prop': 2,

        // Best practices:
        'vue/html-end-tags': 2,
        'vue/no-async-in-computed-properties': 2,
        'vue/no-duplicate-attributes': 2,
        'vue/no-side-effects-in-computed-properties': 2,
        // this could be part of the Stylistic Issues
        'vue/order-in-components': 1,

        // Stylistic Issues:
        'vue/html-indent': 1,
        'vue/html-quotes': 1,
        'vue/html-self-closing': 1,
        'vue/max-attributes-per-line': 1,
        'vue/mustache-interpolation-spacing': 1,
        'vue/name-property-casing': 1,
        'vue/no-multi-spaces': 1,
        'vue/v-bind-style': 1,
        'vue/v-on-style': 1

    }
};
<commit_msg>Remove html-indent rule<commit_after>module.exports = {
    plugins: [
        'vue'
    ],
    extends: [
        'vast',
        'plugin:vue/recommended'
    ],
    rules: {
        // Possible errors:
        // this rule only covers case when used in code like: Vue.component...
        'vue/no-shared-component-data': 2,
        'vue/require-valid-default-prop': 2,

        // Best practices:
        'vue/html-end-tags': 2,
        'vue/no-async-in-computed-properties': 2,
        'vue/no-duplicate-attributes': 2,
        'vue/no-side-effects-in-computed-properties': 2,
        // this could be part of the Stylistic Issues
        'vue/order-in-components': 1,

        // Stylistic Issues:
        // 'vue/html-indent': 1 // Rule not found?
        'vue/html-quotes': 1,
        'vue/html-self-closing': 1,
        'vue/max-attributes-per-line': 1,
        'vue/mustache-interpolation-spacing': 1,
        'vue/name-property-casing': 1,
        'vue/no-multi-spaces': 1,
        'vue/v-bind-style': 1,
        'vue/v-on-style': 1

    }
};
<|endoftext|>


<commit_before>(function (enyo, scope) {

	/**
	* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
	* and multiple types of buttons.
	*
	* @namespace onyx
	*/

	if (enyo && enyo.version) {
		enyo.version.onyx = "2.6.0-pre.2";
	}

})(enyo, this);
<commit_msg>Update version string to 2.6.0-pre.2.dev<commit_after>(function (enyo, scope) {

	/**
	* Features a variety of commonly used widgets, including toolbars, text inputs, checkboxes, groups
	* and multiple types of buttons.
	*
	* @namespace onyx
	*/

	if (enyo && enyo.version) {
		enyo.version.onyx = "2.6.0-pre.2.dev";
	}

})(enyo, this);
<|endoftext|>


<commit_before>'use strict';

var CloudFoundry = require('cf-nodejs-client'),
    Promise = require('bluebird'),
    util = require('util'),
    Spinner = require('cli-spinner').Spinner,
    spinner = new Spinner('%s'),
    cf = new CloudFoundry.CloudFoundry(),
    routes = new CloudFoundry.Routes(),
    manifest = require('./lib/manifest'),
    config = require('./lib/config'),
    apps = new CloudFoundry.Apps();

module.exports = function (options) {
  spinner.start();

  config(options).then(function (config) {
    cf.setEndPoint(config.endpoint);
    routes.setEndPoint(config.endpoint);
    apps.setEndPoint(config.endpoint);

    return cf.getInfo().then(function (result) {
      return cf.login(result.authorization_endpoint,
        config.username,
        config.password);
    }).then(function (auth) {
      return apps.getApps(auth.token_type, auth.access_token).then(function (result) {
        var guid;

        result.resources.forEach(function (item) {
	  if (item.entity.name === config.app) {
            guid = item.metadata.guid;
          }
        });

	return manifest(auth, guid).then(function (settings) {
	  spinner.stop();
	  console.log(settings);
	  return settings;
	});
      });
    })
  }).catch(function (error) {
    spinner.stop(true);
    console.error('Error: ' + error);
    process.exit(1);
  });
}

<commit_msg>:art: Clean manifest pipe<commit_after>'use strict';

var CloudFoundry = require('cf-nodejs-client'),
    Promise = require('bluebird'),
    util = require('util'),
    Spinner = require('cli-spinner').Spinner,
    spinner = new Spinner('%s'),
    cf = new CloudFoundry.CloudFoundry(),
    routes = new CloudFoundry.Routes(),
    manifest = require('./lib/manifest'),
    config = require('./lib/config'),
    apps = new CloudFoundry.Apps();

module.exports = function (options) {
  spinner.start();

  config(options).then(function (config) {
    cf.setEndPoint(config.endpoint);
    routes.setEndPoint(config.endpoint);
    apps.setEndPoint(config.endpoint);

    return cf.getInfo().then(function (result) {
      return cf.login(result.authorization_endpoint,
        config.username,
        config.password);
    }).then(function (auth) {
      return apps.getApps(auth.token_type, auth.access_token).then(function (result) {
        var guid;

        result.resources.forEach(function (item) {
          if (item.entity.name === config.app) {
            guid = item.metadata.guid;
          }
        });

        return manifest(auth, guid).then(function (settings) {
          spinner.stop();
          console.log(settings);
          return settings;
        });
      });
    })
  }).catch(function (error) {
    spinner.stop(true);
    console.error('Error: ' + error);
    process.exit(1);
  });
}

<|endoftext|>


<commit_before>exports.osmbc_version = "0.3.12d";

<commit_msg>VERSION<commit_after>exports.osmbc_version = "0.3.12e";

<|endoftext|>


<commit_before>module.exports = {
    NotFound: require("./lib/NotFoundError.js"),
    Http: require("./lib/HttpError.js"),
    Custom: require("./lib/CustomError.js"),
    is: require("./lib/is.js"),
    Conflict: require("./lib/ConflictError.js"),
    InvalidArgument: require("./lib/InvalidArgumentError.js"),
    MissingArgument: require("./lib/MissingArgumentError.js"),
    Internal: require("./lib/InternalError.js")
};
<commit_msg>Add the new error to interface<commit_after>module.exports = {
    NotFound: require("./lib/NotFoundError.js"),
    Http: require("./lib/HttpError.js"),
    Custom: require("./lib/CustomError.js"),
    is: require("./lib/is.js"),
    Conflict: require("./lib/ConflictError.js"),
    InvalidArgument: require("./lib/InvalidArgumentError.js"),
    MissingArgument: require("./lib/MissingArgumentError.js"),
    Unauthorized: require("./lib/UnauthorizedError.js"),
    Internal: require("./lib/InternalError.js")
};
<|endoftext|>


<commit_before>

var EventEmitter = require('events').EventEmitter

function each(obj, iter) {
  for(var k in obj) iter(k, obj[k])
}
function hasEdge (g, f, t) {
  return g[f] && Object.hasOwnProperty(g[f], t)
}

function addNode(g, n) {
  g[n] = g[n] || {}
  return g
}

function get (g, f, t) {
  if(t == null) throw new Error('not implemented')
  return g[f] && g[f][t] || null
}

function addEdge (g, from, to, data) {

  (g[from] = g[from] || {})[to] = (data === undefined ? true : data)
  return g
}

function delEdge (g, from, to) {
  delete g[from][to]
}

function eachEdge (g, iter) {
  each(g, function (from, n) {
    each(n, function (to, data) {
      iter(from, to, data)
    })
  })
}

//get a random node
function randomNode (g) {
  var keys = Object.keys(g)
  return keys[~~(keys.length*Math.random())]
}

//add another subgraph
function addGraph (g1, g2) {
  eachEdge(g2, function (from, to, data) {
    addEdge(g1, from, to, data)
  })
  return g1
}

//
// graph generators
//

function random (nodes, edges, prefix) {
  prefix = prefix || '#'
  if(isNaN(+nodes)) throw new Error('nodes must be a number')
  if(isNaN(+edges)) throw new Error('edges must be a number')

  var n = 0, g = {}

  function rand(n) {
    return prefix+~~(Math.random()*n)
  }

  for(var i = 0; i < nodes; i++)
    addNode(g, prefix+i)

  for(var i = 0; i < edges; i++) {
    var a = rand(nodes), b = rand(nodes)
    addEdge(g, a, b)
    addEdge(g, b, a)
  }

  return g
}

exports.random = random
exports.each = each
exports.addEdge = addEdge
exports.eachEdge = eachEdge
exports.addGraph = addGraph
exports.get = get

function count(obj) {
  var c = 0
  for(var k in obj) c++
  return c
}

exports.rank = function (g, opts) {
  opts = opts || {}

  var ranks = {}, links = {}, _ranks = {}
  var N = count(g)
  var iterations = opts.iterations || 1
  var damping = opts.damping || 0.85
  var init = (1 - damping) / N

  //initialize
  each(g, function (k, n) {
    ranks[k] = 1/N; _ranks[k] = init
    links[k] = count(n)
  })

  while(iterations --> 0) {

    //iteration
    each(g, function (j, n) {
      var r = damping*(ranks[j]/links[j])
      each(n, function (k) { _ranks[k] += r })
    })

    //reset
    for(var k in ranks)
      ranks[k] = init

    var __ranks = ranks
    ranks = _ranks
    _ranks = __ranks
  }
  return ranks
}

exports.hops = function (g, start, initial, max, seen) {
  if(!g[start]) return {}
  var visited = {}
  var queue = [start]
  visited[start] = initial
  while(queue.length) {
    var node = queue.shift()
    var h = visited[node]
    for(var k in g[node]) {
      if(
        visited[k] == null
      && (!seen || (seen[k] == null || seen[k] > h+1))
      && h < max
      ) {
        queue.push(k)
        visited[k] = h + 1
      }
    }
  }
  return visited
}

<commit_msg>export removeEdge and hasEdge<commit_after>

var EventEmitter = require('events').EventEmitter

function each(obj, iter) {
  for(var k in obj) iter(k, obj[k])
}
function hasEdge (g, f, t) {
  return g[f] && Object.hasOwnProperty(g[f], t)
}

function addNode(g, n) {
  g[n] = g[n] || {}
  return g
}

function get (g, f, t) {
  if(t == null) throw new Error('not implemented')
  return g[f] && g[f][t] || null
}

function addEdge (g, from, to, data) {

  (g[from] = g[from] || {})[to] = (data === undefined ? true : data)
  return g
}

function removeEdge (g, from, to) {
  delete g[from][to]
}

function eachEdge (g, iter) {
  each(g, function (from, n) {
    each(n, function (to, data) {
      iter(from, to, data)
    })
  })
}

//get a random node
function randomNode (g) {
  var keys = Object.keys(g)
  return keys[~~(keys.length*Math.random())]
}

//add another subgraph
function addGraph (g1, g2) {
  eachEdge(g2, function (from, to, data) {
    addEdge(g1, from, to, data)
  })
  return g1
}

//
// graph generators
//

function random (nodes, edges, prefix) {
  prefix = prefix || '#'
  if(isNaN(+nodes)) throw new Error('nodes must be a number')
  if(isNaN(+edges)) throw new Error('edges must be a number')

  var n = 0, g = {}

  function rand(n) {
    return prefix+~~(Math.random()*n)
  }

  for(var i = 0; i < nodes; i++)
    addNode(g, prefix+i)

  for(var i = 0; i < edges; i++) {
    var a = rand(nodes), b = rand(nodes)
    addEdge(g, a, b)
    addEdge(g, b, a)
  }

  return g
}

exports.random = random
exports.each = each
exports.addEdge = addEdge
exports.hasEdge = hasEdge
exports.removeEdge = removeEdge
exports.eachEdge = eachEdge
exports.addGraph = addGraph
exports.get = get

function count(obj) {
  var c = 0
  for(var k in obj) c++
  return c
}

exports.rank = function (g, opts) {
  opts = opts || {}

  var ranks = {}, links = {}, _ranks = {}
  var N = count(g)
  var iterations = opts.iterations || 1
  var damping = opts.damping || 0.85
  var init = (1 - damping) / N

  //initialize
  each(g, function (k, n) {
    ranks[k] = 1/N; _ranks[k] = init
    links[k] = count(n)
  })

  while(iterations --> 0) {

    //iteration
    each(g, function (j, n) {
      var r = damping*(ranks[j]/links[j])
      each(n, function (k) { _ranks[k] += r })
    })

    //reset
    for(var k in ranks)
      ranks[k] = init

    var __ranks = ranks
    ranks = _ranks
    _ranks = __ranks
  }
  return ranks
}

exports.hops = function (g, start, initial, max, seen) {
  if(!g[start]) return {}
  var visited = {}
  var queue = [start]
  visited[start] = initial
  while(queue.length) {
    var node = queue.shift()
    var h = visited[node]
    for(var k in g[node]) {
      if(
        visited[k] == null
      && (!seen || (seen[k] == null || seen[k] > h+1))
      && h < max
      ) {
        queue.push(k)
        visited[k] = h + 1
      }
    }
  }
  return visited
}

<|endoftext|>


<commit_before>'use strict';
/*jshint browser:true, globalstrict:true */
/*globals _ */

var syncDividers = document.querySelectorAll('[sync]');
var syncGroups = [];
_.forEach(syncDividers, function (element) {
	var syncId = element.getAttribute('sync');
	var keyForId = _.findKey(syncGroups, {id: syncId});
	if (keyForId) {
		syncGroups[keyForId].elements.push(element);
	} else {
		syncGroups.push({
			elements: [element],
			id: syncId
		});
	}
});

function findPreviousDivider(element) {
	while (element.previousElementSibling) {
		var previousElement = element.previousElementSibling;
		if (previousElement.hasAttribute('sync')) {
			return previousElement;
		} else {
			return findPreviousDivider(previousElement);
		}
	}
}

/*
 * Must iterate over syncGroups in order of top-to-bottom.
 */
_.forEach(syncGroups, function (syncGroup) {
	var groupID = syncGroup.id;
	var maxOffsetTop = _.max(syncGroup.elements, 'offsetTop').offsetTop;

	_.forEach(syncGroup.elements, function (syncDivider) {
		syncDivider.innerHTML = groupID;

		var siblings = _.toArray(syncDivider.parentElement.children);
		var currentDividerIndex = _.indexOf(siblings, syncDivider);
		var previousDividerIndex = _.indexOf(siblings, findPreviousDivider(syncDivider));
		previousDividerIndex = previousDividerIndex < 0 ? 0 : previousDividerIndex + 1;
		var elementsAfterPreviousDivider = siblings.slice(previousDividerIndex, currentDividerIndex);
		var height = maxOffsetTop - syncDivider.offsetTop;

		if (elementsAfterPreviousDivider.length === 0) {
			if (height !== 0) {
				syncDivider.style.paddingTop = height + 'px';
			}
		} else {
			var paddingPerElement =  height / elementsAfterPreviousDivider.length;
			if (paddingPerElement !== 0) {
				_.forEach(elementsAfterPreviousDivider, function (element) {
					element.style.padding = (paddingPerElement / 2) + 'px 0';
				});
			}
		}
	});
});
<commit_msg>Calculate maxOffsetTop every time we run for a syncDivider, add minimum padding for syncDividers.<commit_after>'use strict';
/*jshint browser:true, globalstrict:true */
/*globals _ */

var syncDividers = document.querySelectorAll('[sync]');
var syncGroups = [];
_.forEach(syncDividers, function (element) {
	var syncId = element.getAttribute('sync');
	var keyForId = _.findKey(syncGroups, {id: syncId});
	if (keyForId) {
		syncGroups[keyForId].elements.push(element);
	} else {
		syncGroups.push({
			elements: [element],
			id: syncId
		});
	}
});

function findPreviousDivider(element) {
	while (element.previousElementSibling) {
		var previousElement = element.previousElementSibling;
		if (previousElement.hasAttribute('sync')) {
			return previousElement;
		} else {
			return findPreviousDivider(previousElement);
		}
	}
}

/*
 * Must iterate over syncGroups in order of top-to-bottom.
 */
_.forEach(syncGroups, function (syncGroup) {
	var groupID = syncGroup.id;
	function maxOffsetTop() {
		var maxElement = _.max(syncGroup.elements, 'offsetTop');
		return maxElement.offsetTop + maxElement.offsetHeight; // Offset height is required when we add padding to the sync element itself.
	}

	_.forEach(syncGroup.elements, function (syncDivider) {
		syncDivider.innerHTML = groupID;

		var siblings = _.toArray(syncDivider.parentElement.children);
		var currentDividerIndex = _.indexOf(siblings, syncDivider);
		var previousDividerIndex = _.indexOf(siblings, findPreviousDivider(syncDivider));
		previousDividerIndex = previousDividerIndex < 0 ? 0 : previousDividerIndex + 1;
		var elementsAfterPreviousDivider = siblings.slice(previousDividerIndex, currentDividerIndex);
		var height = maxOffsetTop() - syncDivider.offsetTop;

		if (elementsAfterPreviousDivider.length === 0) {
			syncDivider.style.paddingTop = (height < 20 ? 20 : height) + 'px'; // Minimum padding of 20px
		} else {
			var paddingPerElement =  height / elementsAfterPreviousDivider.length;
			if (paddingPerElement !== 0) {
				_.forEach(elementsAfterPreviousDivider, function (element) {
					element.style.padding = (paddingPerElement / 2) + 'px 0';
				});
			}
		}
	});
});
<|endoftext|>


<commit_before>const { Cc, Ci} = require("chrome");
const windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Ci.nsIWindowMediator);
const self = require('sdk/self');
const services = require("sdk/preferences/service");
const newTabURL = self.data.url("sources/tab.html");
const helpTabUrl = self.data.url("sources/help.html");
const contentTabUrl = self.data.url("sources/content.html");
const { when: unload } = require("sdk/system/unload");
const prefSet = require("sdk/simple-prefs");
const pageMod = require("sdk/page-mod");
const ss = require("sdk/simple-storage");
const browserWindows = require("sdk/windows").browserWindows;
const tabs = require("sdk/tabs")
const defaultPrefs = require(self.data.url("sources/js/defaultConfig.js"));
const NewTabURL = require('resource:///modules/NewTabURL.jsm').NewTabURL;
var oldNewTab;
var blinkEnable = prefSet.prefs.blinkEnable;
var version = require("sdk/system").version;

// TODO: Code cleanup and restructuring. This can't be my code. It just can't be.

if(self.loadReason == "install" || self.loadReason == "enable") {
	oldNewTab = services.get("browser.newtab.url");
	ss.storage.originalNewTab = oldNewTab;
} else {
	oldNewTab = ss.storage.originalNewTab;
}
if(oldNewTab == undefined)
    oldNewTab = 'about:newtab';

const blinkInit = function() {
	/* Set new tab source */
	if(blinkEnable) {
        if(version >= 41.0) {
//            console.log("version: " + version + " type: " + typeof version)
            NewTabURL.override(newTabURL);
        } else {
		    services.set("browser.newtab.url", self.data.url("sources/tab.html"));
		    clearTabUrlbar();
        }
    }
};

const clearTabUrlbar = function() {
	/* Clear New tab's url bar. */
	let windows = windowMediator.getEnumerator(null);
	while (windows.hasMoreElements()) {
		let window = windows.getNext();
		if(window.gInitialPages.indexOf(newTabURL) == -1)
			window.gInitialPages.push(newTabURL);
		if(window.gInitialPages.indexOf(helpTabUrl) == -1)
			window.gInitialPages.push(helpTabUrl);
		if(window.gInitialPages.indexOf(contentTabUrl) == -1)
			window.gInitialPages.push(contentTabUrl);
	}
};

const clearSettings = function() {
	/* Clear the settings we changed */
    if(version >= 41.0) {
//        console.log("Clearing from " + version);
        NewTabURL.override(oldNewTab);
    } else {
	    services.set("browser.newtab.url", oldNewTab | "about:newtab");
	    let windows = windowMediator.getEnumerator(null);
	    while (windows.hasMoreElements()) {
		let window = windows.getNext();
		if(window.gInitialPages.indexOf(newTabURL) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(newTabURL), 1);
		if(window.gInitialPages.indexOf(helpTabUrl) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(helpTabUrl), 1);
		if(window.gInitialPages.indexOf(contentTabUrl) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(contentTabUrl), 1);
        }
	}
	browserWindows.removeListener("open", blinkInit);
}

// Feed sources with prefs
var feedPrefs;

if(self.loadReason == "install" || !ss.storage.feedprefs) {
	feedPrefs = defaultPrefs.getDefaultPrefs();
	ss.storage.feedprefs = feedPrefs;
} else {
	feedPrefs = ss.storage.feedprefs;
}

var getFeeds = function() {
	/* Refresh feeds */
	var f = [];
	for(var i = 0; i < feedPrefs.length; i++) {
		if(feedPrefs[i].wanted)
			f.push(feedPrefs[i].link)
	}
	return f;
}

 //feeds only
var feeds = getFeeds();

var refreshFeeds = function(feedList) {
	/* Refresh feed prefs */
	feedPrefs = feedList;
	feeds = getFeeds();
	ss.storage.feedprefs = feedList;
}

pageMod.PageMod({
	include: "resource://blink/data/sources/tab.html",
	contentScriptFile: self.data.url("sources/js/feeder.js"),
	contentScriptWhen: 'end',
	onAttach: function(worker) {
    	worker.port.emit("feedList", feeds);
    }
});

pageMod.PageMod({
	include: "resource://blink/data/sources/content.html",
	contentScriptFile: self.data.url("sources/js/feedListener.js"),
	contentScriptWhen: 'end',
	onAttach: function(worker) {
		worker.port.emit("feedPrefs", feedPrefs);
    	worker.port.on("newFeedList", function(newFeeds) {
      	refreshFeeds(newFeeds)
    });
  }
});

function onPrefChange(prefName) {
	/* A generic prefs change callback */
    if(prefName == "blinkEnable") {
    	blinkEnable = prefSet.prefs.blinkEnable;
    	if(blinkEnable)
    		blinkInit();
    	else
    		clearSettings();
    }
}

prefSet.on("blinkEnable", onPrefChange);

// Clear settings on Unload. (Redundant?)
unload(function() {
//	if(blinkEnable)
		clearSettings();
});

/* Clear settings on disable/uninstall.
 But due to bug https://bugzilla.mozilla.org/show_bug.cgi?id=627432#c12, uninstall is never called */
exports.onUnload = function (reason) {
	if (reason === "disable" || reason === "uninstall") {
//		if(blinkEnable)
			clearSettings();
	}
};

// Init Blink
blinkInit();
// Init Blink on new windows when they open
browserWindows.on("open", blinkInit);
<commit_msg>Minor bug fix, added loggging control<commit_after>const { Cc, Ci} = require("chrome");
const windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Ci.nsIWindowMediator);
const self = require('sdk/self');
const services = require("sdk/preferences/service");
const newTabURL = self.data.url("sources/tab.html");
const helpTabUrl = self.data.url("sources/help.html");
const contentTabUrl = self.data.url("sources/content.html");
const { when: unload } = require("sdk/system/unload");
const prefSet = require("sdk/simple-prefs");
const pageMod = require("sdk/page-mod");
const ss = require("sdk/simple-storage");
const browserWindows = require("sdk/windows").browserWindows;
const tabs = require("sdk/tabs")
const defaultPrefs = require(self.data.url("sources/js/defaultConfig.js"));
const NewTabURL = require('resource:///modules/NewTabURL.jsm').NewTabURL;
var oldNewTab;
var blinkEnable = prefSet.prefs.blinkEnable;
var version = require("sdk/system").version;
var devlogs = false;              // set true to enable logging
// TODO: Code cleanup and restructuring. This can't be my code. It just can't be.

if(self.loadReason == "install" || self.loadReason == "enable") {
	oldNewTab = services.get("browser.newtab.url");
	ss.storage.originalNewTab = oldNewTab;
} else {
	oldNewTab = ss.storage.originalNewTab;
}
if(oldNewTab == undefined)
    oldNewTab = 'about:newtab';

if(devlogs) console.log(oldNewTab)

const blinkInit = function() {
	/* Set new tab source */
	if(blinkEnable) {
        if(devlogs) console.log("version: " + version)
        if(version >= "41.0") {
            if(devlogs) console.log("Using new API")
            NewTabURL.override(newTabURL);
        } else {
            if(devlogs) console.log("Using old API")
		        services.set("browser.newtab.url", self.data.url("sources/tab.html"));
		        clearTabUrlbar();
        }
    }
};

const clearTabUrlbar = function() {
	/* Clear New tab's url bar. */
	let windows = windowMediator.getEnumerator(null);
	while (windows.hasMoreElements()) {
		let window = windows.getNext();
		if(window.gInitialPages.indexOf(newTabURL) == -1)
			window.gInitialPages.push(newTabURL);
		if(window.gInitialPages.indexOf(helpTabUrl) == -1)
			window.gInitialPages.push(helpTabUrl);
		if(window.gInitialPages.indexOf(contentTabUrl) == -1)
			window.gInitialPages.push(contentTabUrl);
	}
};

const clearSettings = function() {
	/* Clear the settings we changed */
    if(version >= "41.0") {
        if(devlogs) console.log("Clearing from " + version);
        NewTabURL.override(oldNewTab);
    } else {
      if(devlogs) console.log("Clearing from " + version + " the old way");
	    services.set("browser.newtab.url", oldNewTab);
	    let windows = windowMediator.getEnumerator(null);
	    while (windows.hasMoreElements()) {
		  let window = windows.getNext();
		  if(window.gInitialPages.indexOf(newTabURL) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(newTabURL), 1);
		  if(window.gInitialPages.indexOf(helpTabUrl) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(helpTabUrl), 1);
		  if(window.gInitialPages.indexOf(contentTabUrl) > -1)
		    window.gInitialPages.splice(window.gInitialPages.indexOf(contentTabUrl), 1);
      }
	}
	browserWindows.removeListener("open", blinkInit);
}

// Feed sources with prefs
var feedPrefs;

if(self.loadReason == "install" || !ss.storage.feedprefs) {
	feedPrefs = defaultPrefs.getDefaultPrefs();
	ss.storage.feedprefs = feedPrefs;
} else {
	feedPrefs = ss.storage.feedprefs;
}

var getFeeds = function() {
	/* Refresh feeds */
	var f = [];
	for(var i = 0; i < feedPrefs.length; i++) {
		if(feedPrefs[i].wanted)
			f.push(feedPrefs[i].link)
	}
	return f;
}

 //feeds only
var feeds = getFeeds();

var refreshFeeds = function(feedList) {
	/* Refresh feed prefs */
	feedPrefs = feedList;
	feeds = getFeeds();
	ss.storage.feedprefs = feedList;
}

pageMod.PageMod({
	include: "resource://blink/data/sources/tab.html",
	contentScriptFile: self.data.url("sources/js/feeder.js"),
	contentScriptWhen: 'end',
	onAttach: function(worker) {
    	worker.port.emit("feedList", feeds);
    }
});

pageMod.PageMod({
	include: "resource://blink/data/sources/content.html",
	contentScriptFile: self.data.url("sources/js/feedListener.js"),
	contentScriptWhen: 'end',
	onAttach: function(worker) {
		worker.port.emit("feedPrefs", feedPrefs);
    	worker.port.on("newFeedList", function(newFeeds) {
      	refreshFeeds(newFeeds)
    });
  }
});

function onPrefChange(prefName) {
	/* A generic prefs change callback */
    if(prefName == "blinkEnable") {
    	blinkEnable = prefSet.prefs.blinkEnable;
    	if(blinkEnable)
    		blinkInit();
    	else
    		clearSettings();
    }
}

prefSet.on("blinkEnable", onPrefChange);

// Clear settings on Unload. (Redundant?)
unload(function() {
//	if(blinkEnable)
		clearSettings();
});

/* Clear settings on disable/uninstall.
 But due to bug https://bugzilla.mozilla.org/show_bug.cgi?id=627432#c12, uninstall is never called */
exports.onUnload = function (reason) {
	if (reason === "disable" || reason === "uninstall") {
//		if(blinkEnable)
			clearSettings();
	}
};

// Init Blink
blinkInit();
// Init Blink on new windows when they open
browserWindows.on("open", blinkInit);
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const babel = require('gulp-babel');
const del = require('del');
const rev = require('gulp-rev');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-dart-sass');
const clean_css = require('gulp-clean-css');
const revdel = require('gulp-rev-delete-original');
const mode = require('gulp-mode')();
const run = require('gulp-run-command').default;

var jsFiles = {
  'jquery': {
    base: 'node_modules/jquery/dist',
    files: [
      'node_modules/jquery/dist/jquery.min.js'
    ]
  },
  'bootstrap': {
    base: null,
    files: [
      'node_modules/bootstrap/dist/js/bootstrap.bundle.min.js'
    ]
  },
  'bootstrap-notify': {
    base: 'node_modules/bootstrap-notify',
    files: [
      'node_modules/bootstrap-notify/bootstrap-notify.min.js'
    ]
  },
  'sweetalert2': {
    base: 'node_modules/sweetalert2/dist',
    files: [
      'node_modules/sweetalert2/dist/sweetalert2.min.js'
    ]
  },
  'material-icons': {
    files: [
      'font/*'
    ]
  },
  'roboto-fontface': {
    base: 'node_modules/roboto-fontface',
    files: [
      'node_modules/roboto-fontface/css/roboto/roboto-fontface.css',
      'node_modules/roboto-fontface/fonts/roboto/*'
    ]
  },
  'luxon': {
    files: [
      'node_modules/luxon/build/global/luxon.min.js'
    ]
  },
  'humanize-duration': {
    files: [
      'node_modules/humanize-duration/humanize-duration.js'
    ]
  },
  'clipboard': {
    base: 'node_modules/clipboard/dist',
    files: [
      'node_modules/clipboard/dist/clipboard.min.js'
    ]
  },
  'webcaster': {
    base: null,
    files: [
      'js/webcaster/*.js'
    ]
  },
};

var defaultTasks = Object.keys(jsFiles);

defaultTasks.forEach(function (libName) {
  gulp.task('scripts:' + libName, function () {
    return gulp.src(jsFiles[libName].files, {
      base: jsFiles[libName].base
    }).pipe(gulp.dest('../web/static/dist/lib/' + libName));
  });
});

gulp.task('bundle-deps', gulp.parallel(
  defaultTasks.map(function (name) {
    return 'scripts:' + name;
  })
));

gulp.task('clean', function () {
  return del([
    '../web/static/dist/**/*',
    '../web/static/webpack_dist/**/*',
    '../web/static/assets.json',
    '../web/static/webpack.json'
  ], { force: true });
});

gulp.task('concat-js', function () {
  return gulp.src('./js/inc/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(concat('app.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('build-vue', run('webpack -c webpack.config.js'));

gulp.task('build-js', function () {
  return gulp.src(['./js/*.js'])
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('build-css', function () {
  return gulp.src(['./scss/style.scss'])
    .pipe(mode.development(sourcemaps.init()))
    .pipe(sass())
    .pipe(clean_css())
    .pipe(mode.development(sourcemaps.write()))
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('watch', function () {
  gulp.watch(['./vue/**', './js/**/*.js'], buildAll);
});

const buildAll = gulp.series('clean', gulp.parallel('concat-js', 'build-vue', 'build-js', 'build-css', 'bundle-deps'), function () {
  return gulp.src(['../web/static/dist/**/*.{js,css}'], { base: '../web/static/' })
    .pipe(rev())
    .pipe(revdel())
    .pipe(gulp.dest('../web/static/'))
    .pipe(rev.manifest('assets.json'))
    .pipe(gulp.dest('../web/static/'));
});

exports.default = buildAll
<commit_msg>Add SCSS to Gulp watch.<commit_after>'use strict';

const gulp = require('gulp');
const babel = require('gulp-babel');
const del = require('del');
const rev = require('gulp-rev');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-dart-sass');
const clean_css = require('gulp-clean-css');
const revdel = require('gulp-rev-delete-original');
const mode = require('gulp-mode')();
const run = require('gulp-run-command').default;

var jsFiles = {
  'jquery': {
    base: 'node_modules/jquery/dist',
    files: [
      'node_modules/jquery/dist/jquery.min.js'
    ]
  },
  'bootstrap': {
    base: null,
    files: [
      'node_modules/bootstrap/dist/js/bootstrap.bundle.min.js'
    ]
  },
  'bootstrap-notify': {
    base: 'node_modules/bootstrap-notify',
    files: [
      'node_modules/bootstrap-notify/bootstrap-notify.min.js'
    ]
  },
  'sweetalert2': {
    base: 'node_modules/sweetalert2/dist',
    files: [
      'node_modules/sweetalert2/dist/sweetalert2.min.js'
    ]
  },
  'material-icons': {
    files: [
      'font/*'
    ]
  },
  'roboto-fontface': {
    base: 'node_modules/roboto-fontface',
    files: [
      'node_modules/roboto-fontface/css/roboto/roboto-fontface.css',
      'node_modules/roboto-fontface/fonts/roboto/*'
    ]
  },
  'luxon': {
    files: [
      'node_modules/luxon/build/global/luxon.min.js'
    ]
  },
  'humanize-duration': {
    files: [
      'node_modules/humanize-duration/humanize-duration.js'
    ]
  },
  'clipboard': {
    base: 'node_modules/clipboard/dist',
    files: [
      'node_modules/clipboard/dist/clipboard.min.js'
    ]
  },
  'webcaster': {
    base: null,
    files: [
      'js/webcaster/*.js'
    ]
  },
};

var defaultTasks = Object.keys(jsFiles);

defaultTasks.forEach(function (libName) {
  gulp.task('scripts:' + libName, function () {
    return gulp.src(jsFiles[libName].files, {
      base: jsFiles[libName].base
    }).pipe(gulp.dest('../web/static/dist/lib/' + libName));
  });
});

gulp.task('bundle-deps', gulp.parallel(
  defaultTasks.map(function (name) {
    return 'scripts:' + name;
  })
));

gulp.task('clean', function () {
  return del([
    '../web/static/dist/**/*',
    '../web/static/webpack_dist/**/*',
    '../web/static/assets.json',
    '../web/static/webpack.json'
  ], { force: true });
});

gulp.task('concat-js', function () {
  return gulp.src('./js/inc/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(concat('app.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('build-vue', run('webpack -c webpack.config.js'));

gulp.task('build-js', function () {
  return gulp.src(['./js/*.js'])
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('build-css', function () {
  return gulp.src(['./scss/style.scss'])
    .pipe(mode.development(sourcemaps.init()))
    .pipe(sass())
    .pipe(clean_css())
    .pipe(mode.development(sourcemaps.write()))
    .pipe(gulp.dest('../web/static/dist'));
});

gulp.task('watch', function () {
    gulp.watch([
        './vue/**',
        './js/**/*.js',
        './scss/**',
    ], buildAll);
});

const buildAll = gulp.series('clean', gulp.parallel('concat-js', 'build-vue', 'build-js', 'build-css', 'bundle-deps'), function () {
  return gulp.src(['../web/static/dist/**/*.{js,css}'], { base: '../web/static/' })
    .pipe(rev())
    .pipe(revdel())
    .pipe(gulp.dest('../web/static/'))
    .pipe(rev.manifest('assets.json'))
    .pipe(gulp.dest('../web/static/'));
});

exports.default = buildAll
<|endoftext|>


<commit_before>var tape = require("tape"),
    jsdom = require("./jsdom"),
    d3 = require("d3-selection"),
    d3_graphviz = require("../");

tape("Simple rendering an SVG from graphviz DOT.", function(test) {
    var window = global.window = jsdom('

');
    var document = global.document = window.document;
    var graphviz = d3_graphviz.graphviz("#graph");

    graphviz
        .renderDot('digraph {a -> b;}');

    test.equal(d3.selectAll('.node').size(), 2, 'Number of nodes');
    test.equal(d3.selectAll('.edge').size(), 1, 'Number of edges');
    test.equal(d3.selectAll('ellipse').size(), 2, 'Number of ellipses');
    test.equal(d3.selectAll('polygon').size(), 2, 'Number of polygons');
    test.equal(d3.selectAll('path').size(), 1, 'Number of paths');

    test.end();
});
<commit_msg>Port simple-test.js to hpcc-js-wasm<commit_after>var tape = require("tape"),
    jsdom = require("./jsdom"),
    d3 = require("d3-selection"),
    d3_graphviz = require("../");

tape("Simple rendering an SVG from graphviz DOT.", function(test) {
    var window = global.window = jsdom('

');
    var document = global.document = window.document;
    var graphviz = d3_graphviz.graphviz("#graph")
        .on('initEnd', startTest);

    function startTest() {
        graphviz
            .renderDot('digraph {a -> b;}');
        test.equal(d3.selectAll('.node').size(), 2, 'Number of nodes');
        test.equal(d3.selectAll('.edge').size(), 1, 'Number of edges');
        test.equal(d3.selectAll('ellipse').size(), 2, 'Number of ellipses');
        test.equal(d3.selectAll('polygon').size(), 2, 'Number of polygons');
        test.equal(d3.selectAll('path').size(), 1, 'Number of paths');

        test.end();
    }
});
<|endoftext|>


<commit_before>;(function($$){ 'use strict';

  var CanvasRenderer = $$('renderer', 'canvas');

  CanvasRenderer.prototype.getCachedImage = function(url, onLoad) {
    var r = this;
    var imageCache = r.imageCache = r.imageCache || {};

    if( imageCache[url] && imageCache[url].image ){
      return imageCache[url].image;
    }

    var cache = imageCache[url] = imageCache[url] || {};

    var image = cache.image = new Image();
    image.addEventListener('load', onLoad);
    image.src = url;

    return image;
  };

  CanvasRenderer.prototype.drawInscribedImage = function(context, img, node) {
    var r = this;
    var nodeX = node._private.position.x;
    var nodeY = node._private.position.y;
    var style = node._private.style;
    var fit = style['background-fit'].value;
    var xPos = style['background-position-x'];
    var yPos = style['background-position-y'];
    var repeat = style['background-repeat'].value;
    var nodeW = node.width();
    var nodeH = node.height();
    var rs = node._private.rscratch;
    var clip = style['background-clip'].value;
    var shouldClip = clip === 'node';
    var imgOpacity = style['background-image-opacity'].value;

    var w = img.width;
    var h = img.height;

    if( w === 0 || h === 0 ){
      return; // no point in drawing empty image (and chrome is broken in this case)
    }

    var bgW = style['background-width'];
    if( bgW !== 'auto' ){
      if( bgW.units === '%' ){
        w = bgW.value/100 * nodeW;
      } else {
        w = bgW.pxValue;
      }
    }

    var bgH = style['background-height'];
    if( bgH !== 'auto' ){
      if( bgH.units === '%' ){
        h = bgH.value/100 * nodeH;
      } else {
        h = bgH.pxValue;
      }
    }

    if( fit === 'contain' ){
      var scale = Math.min( nodeW/w, nodeH/h );

      w *= scale;
      h *= scale;

    } else if( fit === 'cover' ){
      var scale = Math.max( nodeW/w, nodeH/h );

      w *= scale;
      h *= scale;
    }

    var x = (nodeX - nodeW/2); // left
    if( xPos.units === '%' ){
      x += (nodeW - w) * xPos.value/100;
    } else {
      x += xPos.pxValue;
    }

    var y = (nodeY - nodeH/2); // top
    if( yPos.units === '%' ){
      y += (nodeH - h) * yPos.value/100;
    } else {
      y += yPos.pxValue;
    }

    if( rs.pathCache ){
      x -= nodeX;
      y -= nodeY;

      nodeX = 0;
      nodeY = 0;
    }

    var gAlpha = context.globalAlpha;

    context.globalAlpha = imgOpacity;

    if( repeat === 'no-repeat' ){

      if( shouldClip ){
        context.save();

        if( rs.pathCache ){
          context.clip( rs.pathCache );
        } else {
          CanvasRenderer.nodeShapes[r.getNodeShape(node)].drawPath(
            context,
            nodeX, nodeY,
            nodeW, nodeH);

          context.clip();
        }
      }

      context.drawImage( img, 0, 0, img.width, img.height, x, y, w, h );

      if( shouldClip ){
        context.restore();
      }
    } else {
      var pattern = context.createPattern( img, repeat );
      context.fillStyle = pattern;

      CanvasRenderer.nodeShapes[r.getNodeShape(node)].drawPath(
          context,
          nodeX, nodeY,
          nodeW, nodeH);

        context.translate(x, y);
        context.fill();
        context.translate(-x, -y);
    }

    context.globalAlpha = gAlpha;

  };

})( cytoscape );<commit_msg>fix typo re #705 and 28dd89c2f813b1e37fee239b6ac6cb6cb2aa0975<commit_after>;(function($$){ 'use strict';

  var CanvasRenderer = $$('renderer', 'canvas');

  CanvasRenderer.prototype.getCachedImage = function(url, onLoad) {
    var r = this;
    var imageCache = r.imageCache = r.imageCache || {};

    if( imageCache[url] && imageCache[url].image ){
      return imageCache[url].image;
    }

    var cache = imageCache[url] = imageCache[url] || {};

    var image = cache.image = new Image();
    image.addEventListener('load', onLoad);
    image.src = url;

    return image;
  };

  CanvasRenderer.prototype.drawInscribedImage = function(context, img, node) {
    var r = this;
    var nodeX = node._private.position.x;
    var nodeY = node._private.position.y;
    var style = node._private.style;
    var fit = style['background-fit'].value;
    var xPos = style['background-position-x'];
    var yPos = style['background-position-y'];
    var repeat = style['background-repeat'].value;
    var nodeW = node.width();
    var nodeH = node.height();
    var rs = node._private.rscratch;
    var clip = style['background-clip'].value;
    var shouldClip = clip === 'node';
    var imgOpacity = style['background-image-opacity'].value;

    var w = img.width;
    var h = img.height;

    // debugger;

    if( w === 0 || h === 0 ){
      return; // no point in drawing empty image (and chrome is broken in this case)
    }

    var bgW = style['background-width'];
    if( bgW.value !== 'auto' ){
      if( bgW.units === '%' ){
        w = bgW.value/100 * nodeW;
      } else {
        w = bgW.pxValue;
      }
    }

    var bgH = style['background-height'];
    if( bgH.value !== 'auto' ){
      if( bgH.units === '%' ){
        h = bgH.value/100 * nodeH;
      } else {
        h = bgH.pxValue;
      }
    }

    if( fit === 'contain' ){
      var scale = Math.min( nodeW/w, nodeH/h );

      w *= scale;
      h *= scale;

    } else if( fit === 'cover' ){
      var scale = Math.max( nodeW/w, nodeH/h );

      w *= scale;
      h *= scale;
    }

    var x = (nodeX - nodeW/2); // left
    if( xPos.units === '%' ){
      x += (nodeW - w) * xPos.value/100;
    } else {
      x += xPos.pxValue;
    }

    var y = (nodeY - nodeH/2); // top
    if( yPos.units === '%' ){
      y += (nodeH - h) * yPos.value/100;
    } else {
      y += yPos.pxValue;
    }

    if( rs.pathCache ){
      x -= nodeX;
      y -= nodeY;

      nodeX = 0;
      nodeY = 0;
    }

    var gAlpha = context.globalAlpha;

    context.globalAlpha = imgOpacity;

    if( repeat === 'no-repeat' ){

      if( shouldClip ){
        context.save();

        if( rs.pathCache ){
          context.clip( rs.pathCache );
        } else {
          CanvasRenderer.nodeShapes[r.getNodeShape(node)].drawPath(
            context,
            nodeX, nodeY,
            nodeW, nodeH);

          context.clip();
        }
      }

      context.drawImage( img, 0, 0, img.width, img.height, x, y, w, h );

      if( shouldClip ){
        context.restore();
      }
    } else {
      var pattern = context.createPattern( img, repeat );
      context.fillStyle = pattern;

      CanvasRenderer.nodeShapes[r.getNodeShape(node)].drawPath(
          context,
          nodeX, nodeY,
          nodeW, nodeH);

        context.translate(x, y);
        context.fill();
        context.translate(-x, -y);
    }

    context.globalAlpha = gAlpha;

  };

})( cytoscape );<|endoftext|>