<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.notification.email',
  name: 'DAOEmailService',

  documentation: 'Place generated EmailMessages into a DAO pipeline.',

  implements: [
    'foam.nanos.notification.email.EmailService'
  ],

  javaImports: [
    'foam.core.X',
    'foam.dao.ArraySink',
    'foam.dao.DAO',
    'foam.dao.NullDAO',
    'foam.dao.Sink',
    'foam.mlang.MLang',
    'foam.nanos.auth.User',
    'foam.nanos.auth.Group',
    'foam.nanos.logger.Logger',
    'foam.util.SafetyUtil',
    'java.nio.charset.StandardCharsets',
    'java.util.List',
    'org.jtwig.environment.EnvironmentConfiguration',
    'org.jtwig.environment.EnvironmentConfigurationBuilder',
    'org.jtwig.JtwigModel',
    'org.jtwig.JtwigTemplate',
    'org.jtwig.resource.loader.TypedResourceLoader'
  ],

  properties: [
    {
      class: 'String',
      name: 'replyTo'
    },
    {
      class: 'String',
      name: 'from'
    },
    {
      class: 'String',
      name: 'displayName'
    },
    {
      name: 'dao',
      class: 'foam.dao.DAOProperty',
      javaFactory: `
        initializing.set(true);
        String daoName = "emailMessageDAO";
        System.out.println("DAOEmailService initializing "+daoName);
        DAO dao = (DAO) getX().get(daoName);
        if ( dao == null ) {
          System.err.println("DAOEmailService DAO not found: "+daoName);
          dao = new NullDAO();
        }
        initializing.set(false);
        return dao;
`
    },
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:
          `
            protected ThreadLocal<Boolean> initializing = new ThreadLocal<Boolean>() {
              @Override
              protected Boolean initialValue() {
                return false;
              }
            };

            protected EnvironmentConfiguration config_ = null;
`
        }));
      }
    }
  ],

  methods: [
    {
      name: 'getConfig',
      javaType: 'EnvironmentConfiguration',
      args: [
        {
          name: 'group',
          type: 'String'
        }
      ],
      javaCode:
`if ( config_ == null ) {
  config_ = EnvironmentConfigurationBuilder
    .configuration()
    .resources()
      .resourceLoaders()
        .add(new TypedResourceLoader("dao", new DAOResourceLoader(getX(), group)))
      .and()
    .and()
  .build();
}
return config_;`
    },
    {
      name: 'sendEmail',
      javaCode: `
        getDao().inX(x).put(emailMessage);
      `
    },
    {
      name: 'sendEmailFromTemplate',
      javaCode: `
        String group = user != null ? (String) user.getGroup() : null;
        EmailTemplate emailTemplate = DAOResourceLoader.findTemplate(getX(), name, group);
        if ( emailMessage == null )
          return;

        for ( String key : templateArgs.keySet() ) {
          Object value = templateArgs.get(key);
          if ( value instanceof String ) {
            String s = (String) value;
            templateArgs.put(key, new String(s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
          }
        }

        JtwigModel model = JtwigModel.newModel(templateArgs);

        emailMessage = fillInEmailProperties(x, emailMessage, emailTemplate, model);

        sendEmail(x, emailMessage);
      `
    },
    {
      name: 'fillInEmailProperties',
      documentation: `
        Order of precedence:
        1) Properties set on the EmailMessage,
        2) Properties set on the EmailTemplate,
        3) Properties set on the Group,
        4) Properties set as default`,
      type: 'foam.nanos.notification.email.EmailMessage',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'emailMessage',
          javaType: 'final foam.nanos.notification.email.EmailMessage'
        },
        {
          name: 'emailTemplate',
          javaType: 'final foam.nanos.notification.email.EmailTemplate'
        },
        {
          name: 'model',
          javaType: 'org.jtwig.JtwigModel'
        }
      ],
      javaCode: `
        // VARIABLE SET UP:
        User user     = findUser(x, emailMessage);
        Logger logger = (Logger) x.get("logger");
        EnvironmentConfiguration config = getConfig(user.getGroup());
        DAO groupDAO   = ((DAO) x.get("groupDAO")).inX(x);
        Group group    = (Group) groupDAO.find(user.getGroup());

        if ( group == null ) {
          logger.warning("group null or unverified through DAO: failing at DAOEmailService.fillInEmailProperties()", new Exception());
        }

        // BODY:
        JtwigTemplate templateBody = JtwigTemplate.inlineTemplate(emailTemplate.getBody(), config);
        emailMessage.setBody(templateBody.render(model));

        // FROM:
        // The from property is the one property not on emailTemplate
        if ( SafetyUtil.isEmpty(emailMessage.getFrom()) ) {
          emailMessage.setFrom(
            ! SafetyUtil.isEmpty(group.getFrom()) ?
              group.getFrom() : getFrom()
          );
        }

        // REPLY TO:
        if ( SafetyUtil.isEmpty(emailMessage.getReplyTo()) ) {
          if ( ! foam.util.SafetyUtil.isEmpty(emailTemplate.getReplyTo()) ) {
            JtwigTemplate templateDisplayName = JtwigTemplate.inlineTemplate(emailTemplate.getReplyTo(), config);
            emailMessage.setReplyTo(templateDisplayName.render(model));
          } else {
            emailMessage.setReplyTo(
              ! SafetyUtil.isEmpty(group.getReplyTo()) ?
                group.getReplyTo() : getReplyTo()
            );
          }
        }

        // DISPLAY NAME:
        if ( SafetyUtil.isEmpty(emailMessage.getDisplayName()) ) {
          if ( ! foam.util.SafetyUtil.isEmpty(emailTemplate.getDisplayName()) ) {
            JtwigTemplate templateDisplayName = JtwigTemplate.inlineTemplate(emailTemplate.getDisplayName(), config);
            emailMessage.setDisplayName(templateDisplayName.render(model));
          } else {
            emailMessage.setDisplayName(
              ! SafetyUtil.isEmpty(group.getDisplayName()) ? group.getDisplayName() : getDisplayName()
            );
          }
        }

        // SUBJECT:
        // Since subject is very specific to each email there is no group field or default value for this property.
        if ( foam.util.SafetyUtil.isEmpty(emailMessage.getSubject()) &&
          ! foam.util.SafetyUtil.isEmpty(emailTemplate.getSubject()) ) {
            JtwigTemplate templateSubject = JtwigTemplate.inlineTemplate(emailTemplate.getSubject(), config);
            emailMessage.setSubject(templateSubject.render(model));
        }

        // SEND TO:
        // Since sendTo is very specific to each email there is no group field or default value for this property.
        if ( emailMessage.getTo().length == 0 &&
          ! foam.util.SafetyUtil.isEmpty(emailTemplate.getSendTo()) ) {
            JtwigTemplate templateSendTo = JtwigTemplate.inlineTemplate(emailTemplate.getSendTo(), config);
            emailMessage.setTo(new String[] {templateSendTo.render(model)});
        }

        return emailMessage;
      `
    },
    {
      name: 'findUser',
      type: 'foam.nanos.auth.User',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'emailMessage',
          javaType: 'final foam.nanos.notification.email.EmailMessage'
        }
      ],
      javaCode:
        `
        Logger logger = (Logger) x.get("logger");
        foam.nanos.session.Session session = x.get(foam.nanos.session.Session.class);

        DAO userDAO         = ((DAO) x.get("localUserDAO")).inX(x);
        User user           = (User) userDAO.find(session.getUserId());

        // 1. If the user doesn't login at this time, get the user from localUserDao
        // 2. If the user is the system user, get the real user from localUserDao
        if ( user == null || user.getId() == 1 ) {
          user = (User) userDAO.find(MLang.EQ(User.EMAIL, emailMessage.getTo()[0]));
          if ( user == null || user.getId() == 0) {
            logger.warning("User not found:", new Exception());
          }
        }

        return user;
      `
    }
  ]
});
<commit_msg>check for loginEnabled to confirm user is a user and not a business or contact<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.notification.email',
  name: 'DAOEmailService',

  documentation: 'Place generated EmailMessages into a DAO pipeline.',

  implements: [
    'foam.nanos.notification.email.EmailService'
  ],

  javaImports: [
    'foam.core.X',
    'foam.dao.ArraySink',
    'foam.dao.DAO',
    'foam.dao.NullDAO',
    'foam.dao.Sink',
    'foam.mlang.MLang',
    'foam.nanos.auth.User',
    'foam.nanos.auth.Group',
    'foam.nanos.logger.Logger',
    'foam.util.SafetyUtil',
    'java.nio.charset.StandardCharsets',
    'java.util.List',
    'org.jtwig.environment.EnvironmentConfiguration',
    'org.jtwig.environment.EnvironmentConfigurationBuilder',
    'org.jtwig.JtwigModel',
    'org.jtwig.JtwigTemplate',
    'org.jtwig.resource.loader.TypedResourceLoader'
  ],

  properties: [
    {
      class: 'String',
      name: 'replyTo'
    },
    {
      class: 'String',
      name: 'from'
    },
    {
      class: 'String',
      name: 'displayName'
    },
    {
      name: 'dao',
      class: 'foam.dao.DAOProperty',
      javaFactory: `
        initializing.set(true);
        String daoName = "emailMessageDAO";
        System.out.println("DAOEmailService initializing "+daoName);
        DAO dao = (DAO) getX().get(daoName);
        if ( dao == null ) {
          System.err.println("DAOEmailService DAO not found: "+daoName);
          dao = new NullDAO();
        }
        initializing.set(false);
        return dao;
`
    },
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(foam.java.Code.create({
          data:
          `
            protected ThreadLocal<Boolean> initializing = new ThreadLocal<Boolean>() {
              @Override
              protected Boolean initialValue() {
                return false;
              }
            };

            protected EnvironmentConfiguration config_ = null;
`
        }));
      }
    }
  ],

  methods: [
    {
      name: 'getConfig',
      javaType: 'EnvironmentConfiguration',
      args: [
        {
          name: 'group',
          type: 'String'
        }
      ],
      javaCode:
`if ( config_ == null ) {
  config_ = EnvironmentConfigurationBuilder
    .configuration()
    .resources()
      .resourceLoaders()
        .add(new TypedResourceLoader("dao", new DAOResourceLoader(getX(), group)))
      .and()
    .and()
  .build();
}
return config_;`
    },
    {
      name: 'sendEmail',
      javaCode: `
        getDao().inX(x).put(emailMessage);
      `
    },
    {
      name: 'sendEmailFromTemplate',
      javaCode: `
        String group = user != null ? (String) user.getGroup() : null;
        EmailTemplate emailTemplate = DAOResourceLoader.findTemplate(getX(), name, group);
        if ( emailMessage == null )
          return;

        for ( String key : templateArgs.keySet() ) {
          Object value = templateArgs.get(key);
          if ( value instanceof String ) {
            String s = (String) value;
            templateArgs.put(key, new String(s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
          }
        }

        JtwigModel model = JtwigModel.newModel(templateArgs);

        emailMessage = fillInEmailProperties(x, emailMessage, emailTemplate, model);

        sendEmail(x, emailMessage);
      `
    },
    {
      name: 'fillInEmailProperties',
      documentation: `
        Order of precedence:
        1) Properties set on the EmailMessage,
        2) Properties set on the EmailTemplate,
        3) Properties set on the Group,
        4) Properties set as default`,
      type: 'foam.nanos.notification.email.EmailMessage',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'emailMessage',
          javaType: 'final foam.nanos.notification.email.EmailMessage'
        },
        {
          name: 'emailTemplate',
          javaType: 'final foam.nanos.notification.email.EmailTemplate'
        },
        {
          name: 'model',
          javaType: 'org.jtwig.JtwigModel'
        }
      ],
      javaCode: `
        // VARIABLE SET UP:
        User user     = findUser(x, emailMessage);
        Logger logger = (Logger) x.get("logger");
        EnvironmentConfiguration config = getConfig(user.getGroup());
        DAO groupDAO   = ((DAO) x.get("groupDAO")).inX(x);
        Group group    = (Group) groupDAO.find(user.getGroup());

        if ( group == null ) {
          logger.warning("group null or unverified through DAO: failing at DAOEmailService.fillInEmailProperties()", new Exception());
        }

        // BODY:
        JtwigTemplate templateBody = JtwigTemplate.inlineTemplate(emailTemplate.getBody(), config);
        emailMessage.setBody(templateBody.render(model));

        // FROM:
        // The from property is the one property not on emailTemplate
        if ( SafetyUtil.isEmpty(emailMessage.getFrom()) ) {
          emailMessage.setFrom(
            ! SafetyUtil.isEmpty(group.getFrom()) ?
              group.getFrom() : getFrom()
          );
        }

        // REPLY TO:
        if ( SafetyUtil.isEmpty(emailMessage.getReplyTo()) ) {
          if ( ! foam.util.SafetyUtil.isEmpty(emailTemplate.getReplyTo()) ) {
            JtwigTemplate templateDisplayName = JtwigTemplate.inlineTemplate(emailTemplate.getReplyTo(), config);
            emailMessage.setReplyTo(templateDisplayName.render(model));
          } else {
            emailMessage.setReplyTo(
              ! SafetyUtil.isEmpty(group.getReplyTo()) ?
                group.getReplyTo() : getReplyTo()
            );
          }
        }

        // DISPLAY NAME:
        if ( SafetyUtil.isEmpty(emailMessage.getDisplayName()) ) {
          if ( ! foam.util.SafetyUtil.isEmpty(emailTemplate.getDisplayName()) ) {
            JtwigTemplate templateDisplayName = JtwigTemplate.inlineTemplate(emailTemplate.getDisplayName(), config);
            emailMessage.setDisplayName(templateDisplayName.render(model));
          } else {
            emailMessage.setDisplayName(
              ! SafetyUtil.isEmpty(group.getDisplayName()) ? group.getDisplayName() : getDisplayName()
            );
          }
        }

        // SUBJECT:
        // Since subject is very specific to each email there is no group field or default value for this property.
        if ( foam.util.SafetyUtil.isEmpty(emailMessage.getSubject()) &&
          ! foam.util.SafetyUtil.isEmpty(emailTemplate.getSubject()) ) {
            JtwigTemplate templateSubject = JtwigTemplate.inlineTemplate(emailTemplate.getSubject(), config);
            emailMessage.setSubject(templateSubject.render(model));
        }

        // SEND TO:
        // Since sendTo is very specific to each email there is no group field or default value for this property.
        if ( emailMessage.getTo().length == 0 &&
          ! foam.util.SafetyUtil.isEmpty(emailTemplate.getSendTo()) ) {
            JtwigTemplate templateSendTo = JtwigTemplate.inlineTemplate(emailTemplate.getSendTo(), config);
            emailMessage.setTo(new String[] {templateSendTo.render(model)});
        }

        return emailMessage;
      `
    },
    {
      name: 'findUser',
      type: 'foam.nanos.auth.User',
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'emailMessage',
          javaType: 'final foam.nanos.notification.email.EmailMessage'
        }
      ],
      javaCode:
        `
        Logger logger = (Logger) x.get("logger");
        foam.nanos.session.Session session = x.get(foam.nanos.session.Session.class);

        DAO userDAO         = ((DAO) x.get("localUserDAO")).inX(x);
        User user           = (User) userDAO.find(session.getUserId());

        // 1. If the user doesn't login at this time, get the user from localUserDao
        // 2. If the user is the system user, get the real user from localUserDao
        if ( user == null || user.getId() == 1 || ! user.getLoginEnabled() ) {
          user = (User) userDAO.find(MLang.EQ(User.EMAIL, emailMessage.getTo()[0]));
          if ( user == null || user.getId() == 0 || user.getLoginEnabled() ) {
            logger.warning("User not found:", new Exception());
          }
        }

        return user;
      `
    }
  ]
});
<|endoftext|>


<commit_before>var exec;

try{
    spawn = require('child_process').spawn;
}catch(E){
    // probably on Windows Node.js v0.5.0 - v0.5.2
}

module.exports = SendmailTransport;

function SendmailTransport(config){
    this.path = typeof config=="string"?config:"sendmail";
}

SendmailTransport.prototype.sendMail = function(emailMessage, callback) {

    if(!spawn){
        return callback && callback(new Error("No support for child processes in this version of Node.JS, use SMTP instead"));
    }

    // sendmail strips this header line
    emailMessage.options.keepBcc = true;

    var sendmail = spawn(this.path, "-t");

    sendmail.on('exit', function (code) {
        callback(code?new Error("Sendmail exited with "+code):null);
    });

    mailcomposer.pipe(sendmail.stdin);
    mailcomposer.streamMessage();
};<commit_msg>updated examples<commit_after>var exec;

try{
    spawn = require('child_process').spawn;
}catch(E){
    // probably on Windows Node.js v0.5.0 - v0.5.2
}

module.exports = SendmailTransport;

function SendmailTransport(config){
    this.path = typeof config=="string"?config:"sendmail";
}

SendmailTransport.prototype.sendMail = function(emailMessage, callback) {

    if(!spawn){
        return callback && callback(new Error("No support for child processes in this version of Node.JS, use SMTP instead"));
    }

    // sendmail strips this header line
    emailMessage.options.keepBcc = true;

    var sendmail = spawn(this.path, ["-t"]);

    sendmail.on('exit', function (code) {
        callback(code?new Error("Sendmail exited with "+code):null);
    });

    mailcomposer.pipe(sendmail.stdin);
    mailcomposer.streamMessage();
};<|endoftext|>


<commit_before>import Resolver from 'ember/resolver';
import config from '../../config/environment';

const resolver = Resolver.create();

resolver.namespace = {
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix
};

export default resolver;
<commit_msg>Use ember-resolver<commit_after>import Resolver from 'ember-resolver';
import config from '../../config/environment';

const resolver = Resolver.create();

resolver.namespace = {
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix
};

export default resolver;
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    var path = require('path');

    require('jit-grunt')(grunt, {
        'bower': 'grunt-bower-task'
    });

    var jshintFile = './src/js/.jshintrc';

    // Folder containing the Ink source files, Ink/*
    // (Relative to your "js" folder containing ink-all.js)
    // for source maps.
    // If you're serving the whole Ink tree on your server, the below works.
    var sourceMapPathToInkSource = '../../src/js';

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        ink: {
            folders: {
                bower: './bower_components/',
                js: {
                    srcBase: './src/js/',
                    src: './src/js/Ink/',
                    tests: './src/js/tests/',
                    dist: './dist/js/'
                },
                css: {
                    src: './src/less/',
                    dist: './dist/css/'
                }
            }
        },
        // handle 3rd party dependencies
        bower: {
            install: {
                options: {
                    copy: false,
                    targetDir: '<%= ink.folders.bower %>',
                    layout: 'byType',
                    install: true,
                    verbose: false,
                    cleanTargetDir: false,
                    bowerOptions: {
                        forceLatest: true
                    }
                }
            }
        },
        //
        copy: {
            /*
            [3.0.0]: uncomment this
            fontAwesome: {
                files: [{
                    cwd: '<%= ink.folders.bower %>font-awesome/less/',
                    src: [
                        '*.less',
                        '!variables.less',
                    ],
                    dest: '<%= ink.folders.css.src %>modules/icons/',
                    expand: true
                }]
            },
            */
            animate: {
                files: [{
                    cwd: '<%= ink.folders.bower %>animate.css',
                    src: ['animate.css'],
                    dest: '<%= ink.folders.css.src %>modules/animations/',
                    expand: true,
                }]
            },
            modernizr: {
                files: [{
                    cwd: '<%= ink.folders.bower %>modernizr',
                    src: 'modernizr.js',
                    dest: '<%= ink.folders.js.dist %>',
                    expand: true
                }]
            },
            html5shiv: {
                files: [{
                    cwd: '<%= ink.folders.bower %>html5shiv/dist',
                    src: '*',
                    dest: '<%= ink.folders.js.dist %>',
                    expand: true,
                }]
            }
        },

        // builds the javascript bundles
        concat: {

            // ink.js
            ink: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>',
                    src: [
                        '1/**/lib.js',
                        'Net/**/lib.js',
                        'Dom/**/lib.js',
                        'Util/**/lib.js',
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink.js';
                    }
                }]
            },

            // ink-all.js
            ink_all: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>',
                    src: [
                        '1/**/lib.js',
                        // Don't include autoload
                        'Net/**/lib.js',
                        'Dom/**/lib.js',
                        'Util/**/lib.js',
                        'UI/**/lib.js'
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink-all.js';
                    }
                }]
            },

            // ink-ui.js
            ink_ui: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>UI/',
                    src: [
                        '**/lib.js'
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink-ui.js';
                    }
                }]
            },

            // ui components as single files
            ui: {
                files: [{
                    expand: true,
                    cwd: '<%= ink.folders.js.src %>UI/',
                    src: ['**/[0-9]/lib.js'],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        // check if this is v1
                        // Here data is in the form of [UIComponent]/[ver]/lib.js
                        var split = src.split(/\//);
                        var modName = split[0].toLowerCase();
                        var version = split[1];

                        if (version === '1') {
                            // and it it is discard the version number
                            return dest + 'ink.' + modName + '.js';
                        } else {
                            // or replace the slash by an underscore and version number and prepend to dest file name
                            return dest + 'ink.' + modName + '-' + version + '.js';
                        }
                    }
                }
                ]
            },

            autoload: {
                files: [{
                    expand: true,
                    cwd: '<%= ink.folders.js.src %>Autoload',
                    src: ['**/lib.js'],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        var version = src.split('/')[0];
                        if (version === '1') {
                            return dest + 'autoload.js'
                        } else {
                            return dest + 'autoload-' + version + '.js';
                        }
                    }
                }]
            }
        },

        clean: {
            js: {
                src: [
                    '<%= ink.folders.js.dist %>/ink*.js',
                    '<%= ink.folders.js.dist %>/ink*.js.map',
                ]
            },
            css: {
                src: ['<%= ink.folders.css.dist %>/ink*.css']
            },
            /*
            [3.0.0]: uncomment this
            fontAwesome: {
                src: [
                    '<%= ink.folders.css.src %>modules/icons/*',
                    '!<%= ink.folders.css.src %>modules/icons/variables.less'
                ]
            },
            */
        },

        // [TODO] check if this works okay
        qunit: {
            options: {
                // inject: 'js/tests/assets/phantom.js',
                urls: ['http://localhost:8000/js/tests/index.html']
            },
            files: ['<%= ink.folders.js.src %>/tests/unit/**/*.html']
        },

        connect: {
            server: {
                options: {
                    port: 8000,
                    debug: true,
                    base: '.',
                    keepalive: true
                }
            }
        },

        // CONCATENATE JS
        uglify: {
            options: {
                report: 'min',
                sourceMapRoot: sourceMapPathToInkSource,
                sourceMapPrefix: 3,
                compress: {
                    sequences: true,
                    properties: true,
                    dead_code: false,
                    drop_debugger: false,
                    unsafe: false,
                    conditionals: true,
                    comparisons: true,
                    evaluate: true,
                    booleans: true,
                    loops: true,
                    unused: false,
                    hoist_funs: false,
                    hoist_vars: false,
                    if_return: true,
                    join_vars: true,
                    cascade: true
                }
            },
            ink: {
                src: [
                    '<%= ink.folders.js.src %>1/**/lib.js',
                    '<%= ink.folders.js.src %>Net/**/lib.js',
                    '<%= ink.folders.js.src %>Dom/**/lib.js',
                    '<%= ink.folders.js.src %>Util/**/lib.js',
                ],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>.js.map',
                    sourceMappingURL: '<%= pkg.name %>.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>.min.js'
            },
            ink_all: {
                src: ['<%= ink.folders.js.src %>**/lib.js'],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>-all.js.map',
                    sourceMappingURL: '<%= pkg.name %>-all.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>-all.min.js'
            },
            ink_ui: {
                src: ['<%= ink.folders.js.src %>UI/**/lib.js'],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>-ui.js.map',
                    sourceMappingURL: '<%= pkg.name %>-ui.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>-ui.min.js'
            }
        },

        // COMPILES THE CSS
        less: {
            distMin: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-min.css': ['<%= ink.folders.css.src %><%= pkg.name %>.less'],
                },
                // COMPILES THE MINIFIED CSS
                options: {
                    compress: true,
                    // LESS source maps
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: true,
                    sourceMapFilename: '<%= ink.folders.css.dist %><%= pkg.name %>-min.css.map',
                    sourceMapRootpath: '../../'
                }
            },
            IEMin: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-ie7-min.css': ['<%= ink.folders.css.src %><%= pkg.name %>-ie7.less']
                }
            },
            dist: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>.css': ['<%= ink.folders.css.src %><%= pkg.name %>.less'],
                },
                // COMPILES THE MINIFIED CSS
                options: {
                    compress: false,
                    // LESS source maps
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: true,
                    sourceMapFilename: '<%= ink.folders.css.dist %><%= pkg.name %>.css.map',
                    sourceMapRootpath: '../../'
                }
            },
            IE: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-ie7.css': ['<%= ink.folders.css.src %><%= pkg.name %>-ie7.less']
                }
            }
        },

        // Runs JSHint on the Ink.js JavaScript source
        jshint: {
            inkjs: {
                options: {
                    jshintrc: '<%= ink.folders.js.srcBase %>.jshintrc'
                },
                files: {
                    src: '<%= ink.folders.js.src %>**/lib.js'
                }
            }
        },

        // Creates a plato report
        plato: {
            inkjs: {
                options: {
                    jshint: grunt.file.readJSON(jshintFile, {
                        encoding: 'utf-8'
                    })
                },
                files: {
                    '<%= ink.folders.js.srcBase %>report': '<%= ink.folders.js.src %>**/lib.js'
                }
            }
        }
    });

    grunt.registerTask('default', ['bower', 'copy', 'clean:css', 'less', 'clean:js', 'concat', 'uglify']);
    grunt.registerTask('test', ['connect', 'qunit']);
    grunt.registerTask('custom_bundle', 'Create your custom bundle from a json file', function (fileName) {
        if (arguments.length === 0) {
            grunt.log.error('You need to specify a file name');
        }

        var bundle = grunt.file.readJSON(fileName);
        var dependencies = bundle.dependencies || [];
        grunt.config.set('concat.ink_custom', {
            files: [{
                expand: true,
                flatten: true,
                cwd: '<%= ink.folders.js.src %>',
                dest: '<%= ink.folders.js.dist %>' + bundle.name + '/',
                src: dependencies.map(function (depName) {
                    return depName.replace('Ink/', '') + '/lib.js';
                }),
                rename: function (dest, src) {
                    return dest + 'ink-custom.js';
                }
            }]
        });
        grunt.config.set('uglify.ink_custom', {
            src: '<%= ink.folders.js.dist %>' + bundle.name + '/' + 'ink-custom.js',
            dest: '<%= ink.folders.js.dist %>' + bundle.name + '/' + 'ink-custom.min.js'
        });
        grunt.task.run(['concat:ink_custom', 'uglify:ink_custom']);
    });
};
<commit_msg>removing Autoload from ink-all.min.js<commit_after>module.exports = function (grunt) {
    var path = require('path');

    require('jit-grunt')(grunt, {
        'bower': 'grunt-bower-task'
    });

    var jshintFile = './src/js/.jshintrc';

    // Folder containing the Ink source files, Ink/*
    // (Relative to your "js" folder containing ink-all.js)
    // for source maps.
    // If you're serving the whole Ink tree on your server, the below works.
    var sourceMapPathToInkSource = '../../src/js';

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        ink: {
            folders: {
                bower: './bower_components/',
                js: {
                    srcBase: './src/js/',
                    src: './src/js/Ink/',
                    tests: './src/js/tests/',
                    dist: './dist/js/'
                },
                css: {
                    src: './src/less/',
                    dist: './dist/css/'
                }
            }
        },
        // handle 3rd party dependencies
        bower: {
            install: {
                options: {
                    copy: false,
                    targetDir: '<%= ink.folders.bower %>',
                    layout: 'byType',
                    install: true,
                    verbose: false,
                    cleanTargetDir: false,
                    bowerOptions: {
                        forceLatest: true
                    }
                }
            }
        },
        //
        copy: {
            /*
            [3.0.0]: uncomment this
            fontAwesome: {
                files: [{
                    cwd: '<%= ink.folders.bower %>font-awesome/less/',
                    src: [
                        '*.less',
                        '!variables.less',
                    ],
                    dest: '<%= ink.folders.css.src %>modules/icons/',
                    expand: true
                }]
            },
            */
            animate: {
                files: [{
                    cwd: '<%= ink.folders.bower %>animate.css',
                    src: ['animate.css'],
                    dest: '<%= ink.folders.css.src %>modules/animations/',
                    expand: true,
                }]
            },
            modernizr: {
                files: [{
                    cwd: '<%= ink.folders.bower %>modernizr',
                    src: 'modernizr.js',
                    dest: '<%= ink.folders.js.dist %>',
                    expand: true
                }]
            },
            html5shiv: {
                files: [{
                    cwd: '<%= ink.folders.bower %>html5shiv/dist',
                    src: '*',
                    dest: '<%= ink.folders.js.dist %>',
                    expand: true,
                }]
            }
        },

        // builds the javascript bundles
        concat: {

            // ink.js
            ink: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>',
                    src: [
                        '1/**/lib.js',
                        'Net/**/lib.js',
                        'Dom/**/lib.js',
                        'Util/**/lib.js',
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink.js';
                    }
                }]
            },

            // ink-all.js
            ink_all: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>',
                    src: [
                        '1/**/lib.js',
                        // Don't include autoload
                        'Net/**/lib.js',
                        'Dom/**/lib.js',
                        'Util/**/lib.js',
                        'UI/**/lib.js'
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink-all.js';
                    }
                }]
            },

            // ink-ui.js
            ink_ui: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: '<%= ink.folders.js.src %>UI/',
                    src: [
                        '**/lib.js'
                    ],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        return dest + 'ink-ui.js';
                    }
                }]
            },

            // ui components as single files
            ui: {
                files: [{
                    expand: true,
                    cwd: '<%= ink.folders.js.src %>UI/',
                    src: ['**/[0-9]/lib.js'],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        // check if this is v1
                        // Here data is in the form of [UIComponent]/[ver]/lib.js
                        var split = src.split(/\//);
                        var modName = split[0].toLowerCase();
                        var version = split[1];

                        if (version === '1') {
                            // and it it is discard the version number
                            return dest + 'ink.' + modName + '.js';
                        } else {
                            // or replace the slash by an underscore and version number and prepend to dest file name
                            return dest + 'ink.' + modName + '-' + version + '.js';
                        }
                    }
                }
                ]
            },

            autoload: {
                files: [{
                    expand: true,
                    cwd: '<%= ink.folders.js.src %>Autoload',
                    src: ['**/lib.js'],
                    dest: '<%= ink.folders.js.dist %>',
                    rename: function (dest, src) {
                        var version = src.split('/')[0];
                        if (version === '1') {
                            return dest + 'autoload.js';
                        } else {
                            return dest + 'autoload-' + version + '.js';
                        }
                    }
                }]
            }
        },

        clean: {
            js: {
                src: [
                    '<%= ink.folders.js.dist %>/ink*.js',
                    '<%= ink.folders.js.dist %>/ink*.js.map',
                ]
            },
            css: {
                src: ['<%= ink.folders.css.dist %>/ink*.css']
            },
            /*
            [3.0.0]: uncomment this
            fontAwesome: {
                src: [
                    '<%= ink.folders.css.src %>modules/icons/*',
                    '!<%= ink.folders.css.src %>modules/icons/variables.less'
                ]
            },
            */
        },

        // [TODO] check if this works okay
        qunit: {
            options: {
                // inject: 'js/tests/assets/phantom.js',
                urls: ['http://localhost:8000/js/tests/index.html']
            },
            files: ['<%= ink.folders.js.src %>/tests/unit/**/*.html']
        },

        connect: {
            server: {
                options: {
                    port: 8000,
                    debug: true,
                    base: '.',
                    keepalive: true
                }
            }
        },

        // CONCATENATE JS
        uglify: {
            options: {
                report: 'min',
                sourceMapRoot: sourceMapPathToInkSource,
                sourceMapPrefix: 3,
                compress: {
                    sequences: true,
                    properties: true,
                    dead_code: false,
                    drop_debugger: false,
                    unsafe: false,
                    conditionals: true,
                    comparisons: true,
                    evaluate: true,
                    booleans: true,
                    loops: true,
                    unused: false,
                    hoist_funs: false,
                    hoist_vars: false,
                    if_return: true,
                    join_vars: true,
                    cascade: true
                }
            },
            ink: {
                src: [
                    '<%= ink.folders.js.src %>1/**/lib.js',
                    '<%= ink.folders.js.src %>Net/**/lib.js',
                    '<%= ink.folders.js.src %>Dom/**/lib.js',
                    '<%= ink.folders.js.src %>Util/**/lib.js',
                ],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>.js.map',
                    sourceMappingURL: '<%= pkg.name %>.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>.min.js'
            },
            ink_all: {
                src: [
                    '<%= ink.folders.js.src %>1/**/lib.js',
                    // Do not include autoload
                    '<%= ink.folders.js.src %>Net/**/lib.js',
                    '<%= ink.folders.js.src %>Dom/**/lib.js',
                    '<%= ink.folders.js.src %>UI/**/lib.js',
                    '<%= ink.folders.js.src %>Util/**/lib.js',
                ],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>-all.js.map',
                    sourceMappingURL: '<%= pkg.name %>-all.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>-all.min.js'
            },
            ink_ui: {
                src: ['<%= ink.folders.js.src %>UI/**/lib.js'],
                options: {
                    sourceMap: '<%= ink.folders.js.dist %><%= pkg.name %>-ui.js.map',
                    sourceMappingURL: '<%= pkg.name %>-ui.js.map'
                },
                dest: '<%= ink.folders.js.dist %><%= pkg.name %>-ui.min.js'
            }
        },

        // COMPILES THE CSS
        less: {
            distMin: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-min.css': ['<%= ink.folders.css.src %><%= pkg.name %>.less'],
                },
                // COMPILES THE MINIFIED CSS
                options: {
                    compress: true,
                    // LESS source maps
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: true,
                    sourceMapFilename: '<%= ink.folders.css.dist %><%= pkg.name %>-min.css.map',
                    sourceMapRootpath: '../../'
                }
            },
            IEMin: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-ie7-min.css': ['<%= ink.folders.css.src %><%= pkg.name %>-ie7.less']
                }
            },
            dist: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>.css': ['<%= ink.folders.css.src %><%= pkg.name %>.less'],
                },
                // COMPILES THE MINIFIED CSS
                options: {
                    compress: false,
                    // LESS source maps
                    // To enable, set sourceMap to true and update sourceMapRootpath based on your install
                    sourceMap: true,
                    sourceMapFilename: '<%= ink.folders.css.dist %><%= pkg.name %>.css.map',
                    sourceMapRootpath: '../../'
                }
            },
            IE: {
                files: {
                    '<%= ink.folders.css.dist %><%= pkg.name %>-ie7.css': ['<%= ink.folders.css.src %><%= pkg.name %>-ie7.less']
                }
            }
        },

        // Runs JSHint on the Ink.js JavaScript source
        jshint: {
            inkjs: {
                options: {
                    jshintrc: '<%= ink.folders.js.srcBase %>.jshintrc'
                },
                files: {
                    src: '<%= ink.folders.js.src %>**/lib.js'
                }
            }
        },

        // Creates a plato report
        plato: {
            inkjs: {
                options: {
                    jshint: grunt.file.readJSON(jshintFile, {
                        encoding: 'utf-8'
                    })
                },
                files: {
                    '<%= ink.folders.js.srcBase %>report': '<%= ink.folders.js.src %>**/lib.js'
                }
            }
        }
    });

    grunt.registerTask('default', ['bower', 'copy', 'clean:css', 'less', 'clean:js', 'concat', 'uglify']);
    grunt.registerTask('test', ['connect', 'qunit']);
    grunt.registerTask('custom_bundle', 'Create your custom bundle from a json file', function (fileName) {
        if (arguments.length === 0) {
            grunt.log.error('You need to specify a file name');
        }

        var bundle = grunt.file.readJSON(fileName);
        var dependencies = bundle.dependencies || [];
        grunt.config.set('concat.ink_custom', {
            files: [{
                expand: true,
                flatten: true,
                cwd: '<%= ink.folders.js.src %>',
                dest: '<%= ink.folders.js.dist %>' + bundle.name + '/',
                src: dependencies.map(function (depName) {
                    return depName.replace('Ink/', '') + '/lib.js';
                }),
                rename: function (dest, src) {
                    return dest + 'ink-custom.js';
                }
            }]
        });
        grunt.config.set('uglify.ink_custom', {
            src: '<%= ink.folders.js.dist %>' + bundle.name + '/' + 'ink-custom.js',
            dest: '<%= ink.folders.js.dist %>' + bundle.name + '/' + 'ink-custom.min.js'
        });
        grunt.task.run(['concat:ink_custom', 'uglify:ink_custom']);
    });
};
<|endoftext|>


<commit_before>/*

  base http error - do not call directly

*/
'use strict';

var map = require('super-iter').map;
var typeOf = require('super-is').typeOf;
var reRemoveBasePath = new RegExp( '' + process.cwd(), 'gim' );

function HttpError (message, errors) {
  Error.call(this, message);

  this.message = message;
  this.errors = typeOf('array', errors) ? errors : [errors];

  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor); // Creates the this.stack getter
  }
}
HttpError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: HttpError
  },
  name: {
    value: 'HttpError'
  },
  status: {
    value: undefined
  },
  logInternal: {
    value: function () {
      return map(this.errors, function (e) {
        return e.toString();
      });
    }
  },
  safeStack: {
    value: function () {
      return this.stack.replace(reRemoveBasePath, '').split('\n');
    }
  },
  stackTraces: {
    value: function () {
      return map(this.errors, function (e) {
        return e.stack.split('\n');
      });
    }
  },
  messages: {
    /**
     * @param {Boolean} [include_this] Default: true. Whether or not to include this error's message or just the previous errors' messages
     */
    value: function(include_this) {
      if (typeof include_this !== "boolean") {
        include_this = true;
      }
      var msgs = map(this.errors, function(e) {
        return (e.messages ? e.messages() : { message: e.toString()});
      });

      if (include_this === false) {
        return msgs;
      }
      else {
        return {
          message: this.toString(),
          messages: msgs
        };
      }
    }
  },
  toString: {
    value: function () {
      return this.name + ': ' + this.message;
    }
  },
  errors: {
    writable: true
  },
  valueOf: {
    value: function () {
      return "[object HttpError]";
    }
  }
});

module.exports = HttpError;
<commit_msg>fix issue where sometimes there is's no error in the errors array<commit_after>/*

  base http error - do not call directly

*/
'use strict';

var func = require('super-func');
var iter = require('super-iter');
var filter = iter.filter;
var identity = func.identity;
var map = iter.map;
var typeOf = require('super-is').typeOf;
var reRemoveBasePath = new RegExp( '' + process.cwd(), 'gim' );

function HttpError (message, errors) {
  Error.call(this, message);

  this.message = message;
  this.errors = typeOf('array', errors) ? errors : [errors];

  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor); // Creates the this.stack getter
  }
}
HttpError.prototype = Object.create(Error.prototype, {
  constructor: {
    value: HttpError
  },
  name: {
    value: 'HttpError'
  },
  status: {
    value: undefined
  },
  logInternal: {
    value: function () {
      return map(this.errors, function (e) {
        return e.toString();
      });
    }
  },
  safeStack: {
    value: function () {
      return this.stack.replace(reRemoveBasePath, '').split('\n');
    }
  },
  stackTraces: {
    value: function () {
      return map(this.errors, function (e) {
        return e.stack.split('\n');
      });
    }
  },
  messages: {
    /**
     * @param {Boolean} [include_this] Default: true. Whether or not to include this error's message or just the previous errors' messages
     */
    value: function(include_this) {
      if (typeof include_this !== "boolean") {
        include_this = true;
      }
      var msgs = map(filter(this.errors, identity), function(e) {
        return (e.messages ? e.messages() : { message: e.toString()});
      });

      if (include_this === false) {
        return msgs;
      }
      else {
        return {
          message: this.toString(),
          messages: msgs
        };
      }
    }
  },
  toString: {
    value: function () {
      return this.name + ': ' + this.message;
    }
  },
  errors: {
    writable: true
  },
  valueOf: {
    value: function () {
      return "[object HttpError]";
    }
  }
});

module.exports = HttpError;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  // load all tasks
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    jshint: {
      options: {
        asi: true,
        browser: true,
        laxcomma: true,
        globals: {}
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      dist: {
        src: [ 'js/*.js', '!js/*.min.js' ]
      }
    },
    sass: {
      dist: {
        files: {
          'css/styles.css': 'css/styles.scss',
          'css/styles_s6.css': 'css/styles_s6.scss'
        },
        options: {
          sourcemap: 'none',
          style: 'compressed',
          trace: true,
          update: true
        }
      }
    },
    uglify: {
      options: {
        compress: {
          drop_console: true
        }
      },
      dist: {
        files: {
          'js/videosearch.min.js': 'js/videosearch.js',
          'js/thesis.min.js': 'js/thesis.js',
          'js/nml-adv.min.js': 'js/nml-adv.js'
        }
      }
    },
    watch: {
      sass: {
        files: 'css/*.scss',
        tasks: ['sass']
      },
      jshint: {
        files: [
          'js/*.js'
          , '!js/jquery.*.js'
          ],
        tasks: ['jshint']
      }
    }
  });

  // shortcuts, multi-tasks
  grunt.registerTask('test', ['jshint']); // @todo scss-lint
  grunt.registerTask('build', ['sass', 'uglify']);
  grunt.registerTask('default', ['sass']);

};
<commit_msg>Grunt - reformat, build nml.min.js<commit_after>module.exports = function(grunt) {
	// load all tasks
	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		jshint: {
			options: {
				asi: true,
				browser: true,
				laxcomma: true,
				globals: {}
			},
			gruntfile: {
				src: 'Gruntfile.js'
			},
			dist: {
				src: ['js/*.js', '!js/*.min.js', 'js/ga.js', '!js/*.pack.js']
			}
		},
		sass: {
			dist: {
				files: {
					'css/styles.css': 'css/styles.scss',
					'css/styles_s6.css': 'css/styles_s6.scss'
				},
				options: {
					sourcemap: 'none',
					style: 'compressed',
					trace: true,
					update: true
				}
			}
		},
		uglify: {
			options: {
				compress: {
					drop_console: true
				}
			},
			dist: {
				files: {
					'js/videosearch.min.js': 'js/videosearch.js',
					'js/thesis.min.js': 'js/thesis.js',
					'js/nml-adv.min.js': 'js/nml-adv.js',
					'js/nml.min.js': ['js/nml-images.js', 'js/note.js', 'js/ga.js']
				}
			}
		},
		watch: {
			sass: {
				files: 'css/*.scss',
				tasks: ['sass']
			},
			jshint: {
				files: [
					'js/*.js', '!js/jquery.*.js'
				],
				tasks: ['jshint']
			}
		}
	});

	// shortcuts, multi-tasks
	grunt.registerTask('test', ['jshint']); // @todo scss-lint
	grunt.registerTask('build', ['sass', 'uglify']);
	grunt.registerTask('default', ['sass']);
};
<|endoftext|>


<commit_before>import {
  invokeCallback,
  subscribe,
  FULFILLED,
  REJECTED,
  noop
} from './-internal';

import { asap } from './asap';

export default function then(onFulfillment, onRejection) {
  var parent = this;
  var state = parent._state;

  if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
    return this;
  }

  var child = new this.constructor(noop);
  var result = parent._result;

  if (state) {
    var callback = arguments[state - 1];
    asap(function(){
      invokeCallback(state, child, callback, result);
    });
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}
<commit_msg>remove spec incompatible fast-path<commit_after>import {
  invokeCallback,
  subscribe,
  FULFILLED,
  REJECTED,
  noop
} from './-internal';

import { asap } from './asap';

export default function then(onFulfillment, onRejection) {
  var parent = this;
  var state = parent._state;

  var child = new this.constructor(noop);
  var result = parent._result;

  if (state) {
    var callback = arguments[state - 1];
    asap(function(){
      invokeCallback(state, child, callback, result);
    });
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}
<|endoftext|>


<commit_before>
module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
    });

    require('load-grunt-tasks')(grunt, { scope: 'devDependencies' });
    require('time-grunt')(grunt);
};
<commit_msg>Added file head to Gruntfile.js<commit_after>/*
 * tetris
 *
 * Personal site built on top of node.js, express and backbone.js
 * https://github.com/waltzofpearls/tetris
 *
 * Copyright (c) 2014 Topbass Labs (topbasslabs.com)
 * Author Waltz.of.Pearls <rollie@topbasslabs.com, rollie.ma@gmail.com>
 */

module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
    });

    require('load-grunt-tasks')(grunt, { scope: 'devDependencies' });
    require('time-grunt')(grunt);
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    concat: {
      dist: {
        src: [
          'lib/melonJS.js',
          'lib/plugins/*.js',
          'js/game.js',
          'build/js/resources.js',
          'js/**/*.js',
        ],
        dest: 'build/js/app.js'
      }
    },

    copy: {
      dist: {
        files: [{
          src: 'index.css',
          dest: 'build/index.css'
        },{
          src: 'main.js',
          dest: 'build/main.js'
        },{
          src: 'manifest.json',
          dest: 'build/manifest.json'
        },{
          src: 'package.json',
          dest: 'build/package.json'
        },{
          src: 'data/**/*',
          dest: 'build/',
          expand: true
        },{
          src: 'icons/*',
          dest: 'build/',
          expand: true
        }]
      }
    },

    clean: {
      app: ['build/js/app.js'],
      dist: ['build/','bin/'],
    },

    processhtml: {
      dist: {
        options: {
          process: true,
          data: {
            title: '<%= pkg.name %>',
          }
        },
        files: {
          'build/index.html': ['index.html']
        }
      }
    },

    replace : {
      dist : {
        options : {
          usePrefix : false,
          force : true,
          patterns : [
            {
              match : /this\._super\(\s*([\w\.]+)\s*,\s*["'](\w+)["']\s*(,\s*)?/g,
              replacement : '$1.prototype.$2.apply(this$3'
            },
          ],
        },
        files : [
          {
            src : [ 'build/js/app.js' ],
            dest : 'build/js/app.js'
          }
        ]
      },
    },

    uglify: {
      options: {
        report: 'min',
        preserveComments: 'some'
      },
      dist: {
        files: {
          'build/js/app.min.js': [
            'build/js/app.js'
          ]
        }
      }
    },

    connect: {
      server: {
        options: {
          port: 8000,
          keepalive: false
        }
      }
    },

    'download-electron': {
      version: '1.4.6',
      outputDir: 'bin',
      rebuild: false,
    },

    asar: {
      dist: {
        cwd: 'build',
        src: ['**/*', '!js/app.js'],
        expand: true,
        dest: 'bin/' + (
          process.platform === 'darwin'
            ? 'Electron.app/Contents/Resources/'
            : 'resources/'
        ) + 'app.asar'
      },
    },

    resources: {
      dist: {
        options: {
          dest: 'build/js/resources.js',
          varname: 'game.resources',
        },
        files: [{
          src: ['data/bgm/**/*', 'data/sfx/**/*'],
          type: 'audio'
        },{
          src: ['data/img/**/*.png'],
          type: 'image'
        },{
          src: ['data/img/**/*.json'],
          type: 'json'
        },{
          src: ['data/map/**/*.tmx', 'data/map/**/*.json'],
          type: 'tmx'
        },{
          src: ['data/map/**/*.tsx'],
          type: 'tsx'
        }]
      }
    },

    watch: {
      resources: {
        files: ['data/**/*'],
        tasks: ['resources'],
        options: {
          spawn: false,
        },
      },
    },

  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks("grunt-replace");
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-download-electron');
  grunt.loadNpmTasks('grunt-asar');

  // Custom Tasks
  grunt.loadTasks('tasks');

  grunt.registerTask('default', [
    'resources',
    'concat',
    'replace',
    'uglify',
    'copy',
    'processhtml',
    'clean:app',
  ]);
  grunt.registerTask('dist', ['default', 'download-electron', 'asar']);
  grunt.registerTask('serve', ['resources', 'connect', 'watch']);
}
<commit_msg>Update Gruntfile.js<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    concat: {
      dist: {
        src: [
          'lib/melonJS.js',
          'lib/plugins/**/*.js',
          'js/game.js',
          'build/js/resources.js',
          'js/**/*.js',
        ],
        dest: 'build/js/app.js'
      }
    },

    copy: {
      dist: {
        files: [{
          src: 'index.css',
          dest: 'build/index.css'
        },{
          src: 'main.js',
          dest: 'build/main.js'
        },{
          src: 'manifest.json',
          dest: 'build/manifest.json'
        },{
          src: 'package.json',
          dest: 'build/package.json'
        },{
          src: 'data/**/*',
          dest: 'build/',
          expand: true
        },{
          src: 'icons/*',
          dest: 'build/',
          expand: true
        }]
      }
    },

    clean: {
      app: ['build/js/app.js'],
      dist: ['build/','bin/'],
    },

    processhtml: {
      dist: {
        options: {
          process: true,
          data: {
            title: '<%= pkg.name %>',
          }
        },
        files: {
          'build/index.html': ['index.html']
        }
      }
    },

    replace : {
      dist : {
        options : {
          usePrefix : false,
          force : true,
          patterns : [
            {
              match : /this\._super\(\s*([\w\.]+)\s*,\s*["'](\w+)["']\s*(,\s*)?/g,
              replacement : '$1.prototype.$2.apply(this$3'
            },
          ],
        },
        files : [
          {
            src : [ 'build/js/app.js' ],
            dest : 'build/js/app.js'
          }
        ]
      },
    },

    uglify: {
      options: {
        report: 'min',
        preserveComments: 'some'
      },
      dist: {
        files: {
          'build/js/app.min.js': [
            'build/js/app.js'
          ]
        }
      }
    },

    connect: {
      server: {
        options: {
          port: 8000,
          keepalive: false
        }
      }
    },

    'download-electron': {
      version: '1.4.6',
      outputDir: 'bin',
      rebuild: false,
    },

    asar: {
      dist: {
        cwd: 'build',
        src: ['**/*', '!js/app.js'],
        expand: true,
        dest: 'bin/' + (
          process.platform === 'darwin'
            ? 'Electron.app/Contents/Resources/'
            : 'resources/'
        ) + 'app.asar'
      },
    },

    resources: {
      dist: {
        options: {
          dest: 'build/js/resources.js',
          varname: 'game.resources',
        },
        files: [{
          src: ['data/bgm/**/*', 'data/sfx/**/*'],
          type: 'audio'
        },{
          src: ['data/img/**/*.png'],
          type: 'image'
        },{
          src: ['data/img/**/*.json'],
          type: 'json'
        },{
          src: ['data/map/**/*.tmx', 'data/map/**/*.json'],
          type: 'tmx'
        },{
          src: ['data/map/**/*.tsx'],
          type: 'tsx'
        }]
      }
    },

    watch: {
      resources: {
        files: ['data/**/*'],
        tasks: ['resources'],
        options: {
          spawn: false,
        },
      },
    },

  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-processhtml');
  grunt.loadNpmTasks("grunt-replace");
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-download-electron');
  grunt.loadNpmTasks('grunt-asar');

  // Custom Tasks
  grunt.loadTasks('tasks');

  grunt.registerTask('default', [
    'resources',
    'concat',
    'replace',
    'uglify',
    'copy',
    'processhtml',
    'clean:app',
  ]);
  grunt.registerTask('dist', ['default', 'download-electron', 'asar']);
  grunt.registerTask('serve', ['resources', 'connect', 'watch']);
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  var fs = require('fs'),
      path = require('path');

  function loadS3Config(){
    if(fs.existsSync(s3PrivatePath)){
      return JSON.parse(fs.readFileSync(s3PrivatePath));
    } else {
      console.log("You need to create a " + s3PrivatePath + " file to run `grunt s3deploy`");
      return null;
    }
  }

  var s3PrivatePath = path.join(__dirname, '.s3private.json');
  var s3Config = loadS3Config();
  var info = JSON.parse(grunt.file.read('package.json'));

  // List all source files that might be include.
  var sources = [
    'lib/expression-api/namespace.js',
    'lib/expression-api/uuid.js',
    'lib/expression-api/compat.js',
    'lib/expression-api/Collection.js',
    'lib/expression-api/CollectionStore.js',
    'lib/expression-api/PublicCollection.js',
    'lib/expression-api/Expression.js',
    'lib/expression-api/User.js',
    'lib/expression-api/Post.js',
    'lib/expression-api/Image.js',
    'lib/expression-api/Video.js',
    'lib/expression-api/Sound.js',
    'lib/expression-api/events.js',
    'components/fastclick/lib/fastclick.js',
    'lib/expression-api/init.js'
  ];

  var config = {};
  // Lint
  config.jshint = {
    options: {
      browser: true
    },
    all: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
  };

  // Minify JS
  config.uglify = {
    minimifiedIframe: {
      src: 'dist/iframe.js',
      dest: 'dist/iframe.min.js'
    },
    minimifiedSandbox: {
      src: 'dist/sandbox.js',
      dest: 'dist/sandbox.min.js'
    }
  };

  // Minify CSS
  config.cssmin = {
    csscompress: {
      src: 'dist/iframe.css',
      dest: 'dist/iframe.min.css'
    }
  };

  config.filecheck = {
    sources: sources
  };

  // Concatenation
  config.concat = {
    sandbox: {
      src: [
        'lib/expression-api/namespace.js',
        'lib/expression-api/uuid.js',
        'lib/expression-api/compat.js',
        'lib/expression-api/Collection.js',
        'lib/expression-api/PublicCollection.js',
        'lib/expression-api/CollectionStore.js'
      ],
      dest: 'dist/sandbox.js'
    },
    iframe: {
      src: sources,
      dest: 'dist/iframe.js'
    },
    iframecss: {
      src: ['lib/iframe.css'],
      dest: 'dist/iframe.css'
    }
  };

  // Tests
  config.buster = {
    test: {
      config: 'test/buster.js',
      'config-group': 'compiled'
    },
    server: {
      port: 1111
    }
  };

  if(s3Config){
    var genS3Config = function(configs){
      return {
        apiKey: configs.apiKey,
        secretKey: configs.secretKey,
        bucket: configs.bucket,
        distribution: configs.distribution,
        files: {
          'dist/sandbox.js': '/expression/lib/urturn-expression-api/' + info.version + '/sandbox.js',
          'dist/iframe.js': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.js',
          'dist/sandbox.min.js': '/expression/lib/urturn-expression-api/' + info.version + '/sandbox.min.js',
          'dist/iframe.min.js': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.min.js',
          'dist/iframe.css': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.css',
          'dist/iframe.min.css': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.min.css'
        }
      };
    };
    config.s3deploy = {};
    for(var target in s3Config){
      config.s3deploy[target] = genS3Config(s3Config[target]);
    }
  }

  grunt.initConfig(config);

  // Load external grunt Task
  grunt.loadNpmTasks('grunt-buster');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerMultiTask('filecheck', "Ensure sources file are here", function(){
    for(var i in this.data){
      if(!fs.existsSync(this.data[i])){
        grunt.warn("Missing " + this.data[i]);
      }
    }
  });

  // Declare the S3 grunt Task
  grunt.registerMultiTask('s3deploy', 'Deploying built file on AWS s3', function() {
    var done = this.async();
    var knox = require('knox');
    var cloudfront = require('cloudfront');
    var client = knox.createClient({
      key: this.data.apiKey,
      secret: this.data.secretKey,
      bucket: this.data.bucket
    });
    var cf = cloudfront.createClient(this.data.apiKey, this.data.secretKey);
    var counter = 0;
    var bucket = this.data.bucket;
    var distribution = this.data.distribution;
    var files = this.data.files;

    var syncPoint = function(src, dest, bucket, callback){
      return function(err){
        counter --;
        if(err){
          console.log("Error " + err);
        } else {
          console.log("Uploaded " + src + " to " + bucket + dest);
        }
        if(counter === 0){
          callback();
        }
      };
    };

    var headers = {'x-amz-acl': 'public-read'};
    // Define cache controle policy (no-cache if -beta, -alpha or -rc)
    if(info.version.match(/^[0-9]+\.[0-9]+\.[0-9]+$/)){
      headers['Cache-Control'] = "public, max-age=" + 60*60*24*365;
    } else {
      headers['Cache-Control'] = "no-cache";
    }

    function doUpload(src, dest, headers, retry, callback){
      client.putFile(src, dest, headers, function(err){
        if(err){
          if(retry > 2){
            callback(err);
          } else {
            console.log(err, "Retrying...");
            doUpload(src, dest, headers, retry + 1, callback);
          }
        } else {
          callback();
        }
      });
    }

    var invalidate = function(){
      var reqID = "grunt_api_deploy_" + parseInt(Math.random()*1000000000, 10);
      var paths = [];
      for(var k in files){
        paths.push(files[k]);
      }
      cf.createInvalidation(distribution, reqID, paths, function(err, invalidation){
        if (err){
          console.log(err);
        } else {
          console.log("Invalidation request " + reqID + " sent to CloudFront, this may take as long as 15 minutes to complete.");
        }
        done();
      });
    };

    for(var key in files){
      var src = key;
      var dest = files[src];
      counter ++;
      doUpload(src, dest, headers, 0, syncPoint(src, dest, bucket, invalidate));
    }
  });

  // Default task.
  grunt.registerTask('default', ['jshint', 'filecheck', 'concat', 'uglify', 'buster', 'cssmin']);
  grunt.registerTask('all', ['default', 's3deploy']);
  grunt.registerTask('local', ['concat', 'uglify', 'cssmin']);
  grunt.registerTask('l', 'jshint');
};
<commit_msg>busterjs<commit_after>module.exports = function(grunt) {

  var fs = require('fs'),
      path = require('path');

  function loadS3Config(){
    if(fs.existsSync(s3PrivatePath)){
      return JSON.parse(fs.readFileSync(s3PrivatePath));
    } else {
      console.log("You need to create a " + s3PrivatePath + " file to run `grunt s3deploy`");
      return null;
    }
  }

  var s3PrivatePath = path.join(__dirname, '.s3private.json');
  var s3Config = loadS3Config();
  var info = JSON.parse(grunt.file.read('package.json'));

  // List all source files that might be include.
  var sources = [
    'lib/expression-api/namespace.js',
    'lib/expression-api/uuid.js',
    'lib/expression-api/compat.js',
    'lib/expression-api/Collection.js',
    'lib/expression-api/CollectionStore.js',
    'lib/expression-api/PublicCollection.js',
    'lib/expression-api/Expression.js',
    'lib/expression-api/User.js',
    'lib/expression-api/Post.js',
    'lib/expression-api/Image.js',
    'lib/expression-api/Video.js',
    'lib/expression-api/Sound.js',
    'lib/expression-api/events.js',
    'components/fastclick/lib/fastclick.js',
    'lib/expression-api/init.js'
  ];

  var config = {};
  // Lint
  config.jshint = {
    options: {
      browser: true
    },
    all: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
  };

  // Minify JS
  config.uglify = {
    minimifiedIframe: {
      src: 'dist/iframe.js',
      dest: 'dist/iframe.min.js'
    },
    minimifiedSandbox: {
      src: 'dist/sandbox.js',
      dest: 'dist/sandbox.min.js'
    }
  };

  // Minify CSS
  config.cssmin = {
    csscompress: {
      src: 'dist/iframe.css',
      dest: 'dist/iframe.min.css'
    }
  };

  config.filecheck = {
    sources: sources
  };

  // Concatenation
  config.concat = {
    sandbox: {
      src: [
        'lib/expression-api/namespace.js',
        'lib/expression-api/uuid.js',
        'lib/expression-api/compat.js',
        'lib/expression-api/Collection.js',
        'lib/expression-api/PublicCollection.js',
        'lib/expression-api/CollectionStore.js'
      ],
      dest: 'dist/sandbox.js'
    },
    iframe: {
      src: sources,
      dest: 'dist/iframe.js'
    },
    iframecss: {
      src: ['lib/iframe.css'],
      dest: 'dist/iframe.css'
    }
  };

  // Tests
  config.buster = {
    test: {
      'config-group': 'compiled'
    },
    server: {
      port: 1111
    }
  };

  if(s3Config){
    var genS3Config = function(configs){
      return {
        apiKey: configs.apiKey,
        secretKey: configs.secretKey,
        bucket: configs.bucket,
        distribution: configs.distribution,
        files: {
          'dist/sandbox.js': '/expression/lib/urturn-expression-api/' + info.version + '/sandbox.js',
          'dist/iframe.js': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.js',
          'dist/sandbox.min.js': '/expression/lib/urturn-expression-api/' + info.version + '/sandbox.min.js',
          'dist/iframe.min.js': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.min.js',
          'dist/iframe.css': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.css',
          'dist/iframe.min.css': '/expression/lib/urturn-expression-api/' + info.version + '/iframe.min.css'
        }
      };
    };
    config.s3deploy = {};
    for(var target in s3Config){
      config.s3deploy[target] = genS3Config(s3Config[target]);
    }
  }

  grunt.initConfig(config);

  // Load external grunt Task
  grunt.loadNpmTasks('grunt-buster');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerMultiTask('filecheck', "Ensure sources file are here", function(){
    for(var i in this.data){
      if(!fs.existsSync(this.data[i])){
        grunt.warn("Missing " + this.data[i]);
      }
    }
  });

  // Declare the S3 grunt Task
  grunt.registerMultiTask('s3deploy', 'Deploying built file on AWS s3', function() {
    var done = this.async();
    var knox = require('knox');
    var cloudfront = require('cloudfront');
    var client = knox.createClient({
      key: this.data.apiKey,
      secret: this.data.secretKey,
      bucket: this.data.bucket
    });
    var cf = cloudfront.createClient(this.data.apiKey, this.data.secretKey);
    var counter = 0;
    var bucket = this.data.bucket;
    var distribution = this.data.distribution;
    var files = this.data.files;

    var syncPoint = function(src, dest, bucket, callback){
      return function(err){
        counter --;
        if(err){
          console.log("Error " + err);
        } else {
          console.log("Uploaded " + src + " to " + bucket + dest);
        }
        if(counter === 0){
          callback();
        }
      };
    };

    var headers = {'x-amz-acl': 'public-read'};
    // Define cache controle policy (no-cache if -beta, -alpha or -rc)
    if(info.version.match(/^[0-9]+\.[0-9]+\.[0-9]+$/)){
      headers['Cache-Control'] = "public, max-age=" + 60*60*24*365;
    } else {
      headers['Cache-Control'] = "no-cache";
    }

    function doUpload(src, dest, headers, retry, callback){
      client.putFile(src, dest, headers, function(err){
        if(err){
          if(retry > 2){
            callback(err);
          } else {
            console.log(err, "Retrying...");
            doUpload(src, dest, headers, retry + 1, callback);
          }
        } else {
          callback();
        }
      });
    }

    var invalidate = function(){
      var reqID = "grunt_api_deploy_" + parseInt(Math.random()*1000000000, 10);
      var paths = [];
      for(var k in files){
        paths.push(files[k]);
      }
      cf.createInvalidation(distribution, reqID, paths, function(err, invalidation){
        if (err){
          console.log(err);
        } else {
          console.log("Invalidation request " + reqID + " sent to CloudFront, this may take as long as 15 minutes to complete.");
        }
        done();
      });
    };

    for(var key in files){
      var src = key;
      var dest = files[src];
      counter ++;
      doUpload(src, dest, headers, 0, syncPoint(src, dest, bucket, invalidate));
    }
  });

  // Default task.
  grunt.registerTask('default', ['jshint', 'filecheck', 'concat', 'uglify', 'buster', 'cssmin']);
  grunt.registerTask('all', ['default', 's3deploy']);
  grunt.registerTask('local', ['concat', 'uglify', 'cssmin']);
  grunt.registerTask('l', 'jshint');
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({ pkg: grunt.file.readJSON('package.json') });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.config('jshint', {
    all: ['src/js/**.js'],
    gruntfile: ['Gruntfile.js']
  });

  grunt.loadNpmTasks('grunt-contrib-csslint');
  grunt.config('csslint', {
    all: {
      options: {
        import: false
      },
      src: ['src/css/*.css']
    }
  });

  grunt.loadNpmTasks('grunt-html-angular-validate');
  grunt.config('htmlangular', {
    all: {
      options: {
        tmplext: 'partial.htm',
        customtags: [
          'alert'
        ],
        customattrs: [
          'key-enter',
          'key-escape',
          'click-focus'
        ]
      },
      files: {
        src: ['src/default.htm', 'src/partials/*.partial.htm']
      },
    }
  });

  grunt.loadNpmTasks('grunt-processhtml');
  grunt.config('processhtml', {
    dist: {
      files: {
        'dist/default.htm': ['src/default.htm']
      }
    },
    dev: {
      files: {
        'dev/default.htm': ['src/default.htm']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-htmlmin');
  grunt.config('htmlmin', {
    dist: {
      options: {
        removeComments: true,
        collapseWhitespace: true
      },
      files: {
        'dist/default.htm': 'dist/default.htm',
        'dist/partials/start.partial.htm': 'src/partials/start.partial.htm'
      }
    },
    dev: {
      options: {
        removeComments: true,
        collapseWhitespace: true
      },
      files: {
        'dev/default.htm': 'dev/default.htm',
        'dev/partials/start.partial.htm': 'src/partials/start.partial.htm'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.config('uglify', {
    dist: {
      files: {
        'dist/app.min.js': 'src/js/**.js'
      }
    },
    dev: {
      files: {
        'dev/app.min.js': 'src/js/**.js'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.config('copy', {
    dist: {
      files: [
        { expand: true, flatten: true, cwd: 'bower_components/', src: [
          'angular/angular.min.js',
          'angular-bootstrap/ui-bootstrap-tpls.min.js',
          'angular-cookies/angular-cookies.min.js',
          'bower_components/angular-resource/angular-resource.min.js',
          'angular-route/angular-route.min.js',
          'angular-sanitize/angular-sanitize.min.js'
          ],
          dest: 'dist/external'
        },
        { src: 'src/favicon.ico', dest: 'dist/favicon.ico' },
        { expand: true, flatten: true, src: 'src/assets/*', dest: 'dist/assets' }
      ]
    },
    dev: {
      files: [
        { expand: true, flatten: true, cwd: 'bower_components/', src: [
          'angular/angular.min.js',
          'angular-bootstrap/ui-bootstrap-tpls.min.js',
          'angular-cookies/angular-cookies.min.js',
          'bower_components/angular-resource/angular-resource.min.js',
          'angular-route/angular-route.min.js',
          'angular-sanitize/angular-sanitize.min.js'
          ],
          dest: 'dev/external'
        },
        { src: 'src/favicon.ico', dest: 'dev/favicon.ico' },
        { expand: true, flatten: true, src: 'src/assets/*', dest: 'dev/assets' }
      ]
    },
  });

  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.config('cssmin', {
    dist: {
      files: {
        'dist/style.min.css': 'src/css/*.css'
      }
    },
    dev: {
      files: {
        'dev/style.min.css': 'src/css/*.css'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.config('clean', {
    all: ["html-angular-validate-report.json"]
  });

  grunt.loadNpmTasks('grunt-contrib-connect');
  var modRewrite = require('connect-modrewrite');
  var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); };
  grunt.config('connect', {
    server: {
      options: {
        port: 8181,
        livereload: 35729,
        hostname: 'localhost',
        base: {
          path: 'dev',
          options: {
            index: 'default.htm'
          }
        },
        middleware: function (connect) {
          return [
            modRewrite (['!\\.htm|\\.js|\\.svg|\\.css|\\.png|\\.jpg$ /default.htm [L]']),
            mountFolder(connect, 'dev')
          ];
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.config('watch', {
    options: {
      livereload: true
    },
    gruntfile: {
      files: 'Gruntfile.js',
      tasks: ['jshint:gruntfile'],
      options: {
        reload: true
      }
    },
    js: {
      files: 'src/js/*.js',
      tasks: ['jshint', 'uglify:dev']
    },
    css: {
      files: 'src/css/*.css',
      tasks: ['csslint', 'cssmin:dev']
    },
    html: {
      files: ['src/default.htm', 'src/partials/start.partial.htm'],
      tasks: ['processhtml:dev', 'htmlmin:dev']
    }
  });

  grunt.registerTask('dev', ['uglify:dev', 'copy:dev', 'processhtml:dev', 'htmlmin:dev', 'cssmin:dev']);
  grunt.registerTask('dist', ['uglify:dist', 'copy:dist', 'processhtml:dist', 'htmlmin:dist', 'cssmin:dist']);
  grunt.registerTask('check', ['jshint', 'csslint', 'htmlangular', 'clean']);
  grunt.registerTask('serve', ['connect', 'watch']);
};
<commit_msg>Error in copy task, superfluous directory<commit_after>module.exports = function(grunt) {
  grunt.initConfig({ pkg: grunt.file.readJSON('package.json') });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.config('jshint', {
    all: ['src/js/**.js'],
    gruntfile: ['Gruntfile.js']
  });

  grunt.loadNpmTasks('grunt-contrib-csslint');
  grunt.config('csslint', {
    all: {
      options: {
        import: false
      },
      src: ['src/css/*.css']
    }
  });

  grunt.loadNpmTasks('grunt-html-angular-validate');
  grunt.config('htmlangular', {
    all: {
      options: {
        tmplext: 'partial.htm',
        customtags: [
          'alert'
        ],
        customattrs: [
          'key-enter',
          'key-escape',
          'click-focus'
        ]
      },
      files: {
        src: ['src/default.htm', 'src/partials/*.partial.htm']
      },
    }
  });

  grunt.loadNpmTasks('grunt-processhtml');
  grunt.config('processhtml', {
    dist: {
      files: {
        'dist/default.htm': ['src/default.htm']
      }
    },
    dev: {
      files: {
        'dev/default.htm': ['src/default.htm']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-htmlmin');
  grunt.config('htmlmin', {
    dist: {
      options: {
        removeComments: true,
        collapseWhitespace: true
      },
      files: {
        'dist/default.htm': 'dist/default.htm',
        'dist/partials/start.partial.htm': 'src/partials/start.partial.htm'
      }
    },
    dev: {
      options: {
        removeComments: true,
        collapseWhitespace: true
      },
      files: {
        'dev/default.htm': 'dev/default.htm',
        'dev/partials/start.partial.htm': 'src/partials/start.partial.htm'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.config('uglify', {
    dist: {
      files: {
        'dist/app.min.js': 'src/js/**.js'
      }
    },
    dev: {
      files: {
        'dev/app.min.js': 'src/js/**.js'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.config('copy', {
    dist: {
      files: [
        { expand: true, flatten: true, cwd: 'bower_components/', src: [
          'angular/angular.min.js',
          'angular-bootstrap/ui-bootstrap-tpls.min.js',
          'angular-cookies/angular-cookies.min.js',
          'angular-resource/angular-resource.min.js',
          'angular-route/angular-route.min.js',
          'angular-sanitize/angular-sanitize.min.js'
          ],
          dest: 'dist/external'
        },
        { src: 'src/favicon.ico', dest: 'dist/favicon.ico' },
        { expand: true, flatten: true, src: 'src/assets/*', dest: 'dist/assets' }
      ]
    },
    dev: {
      files: [
        { expand: true, flatten: true, cwd: 'bower_components/', src: [
          'angular/angular.min.js',
          'angular-bootstrap/ui-bootstrap-tpls.min.js',
          'angular-cookies/angular-cookies.min.js',
          'angular-resource/angular-resource.min.js',
          'angular-route/angular-route.min.js',
          'angular-sanitize/angular-sanitize.min.js'
          ],
          dest: 'dev/external'
        },
        { src: 'src/favicon.ico', dest: 'dev/favicon.ico' },
        { expand: true, flatten: true, src: 'src/assets/*', dest: 'dev/assets' }
      ]
    },
  });

  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.config('cssmin', {
    dist: {
      files: {
        'dist/style.min.css': 'src/css/*.css'
      }
    },
    dev: {
      files: {
        'dev/style.min.css': 'src/css/*.css'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.config('clean', {
    all: ["html-angular-validate-report.json"]
  });

  grunt.loadNpmTasks('grunt-contrib-connect');
  var modRewrite = require('connect-modrewrite');
  var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); };
  grunt.config('connect', {
    server: {
      options: {
        port: 8181,
        livereload: 35729,
        hostname: 'localhost',
        base: {
          path: 'dev',
          options: {
            index: 'default.htm'
          }
        },
        middleware: function (connect) {
          return [
            modRewrite (['!\\.htm|\\.js|\\.svg|\\.css|\\.png|\\.jpg$ /default.htm [L]']),
            mountFolder(connect, 'dev')
          ];
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.config('watch', {
    options: {
      livereload: true
    },
    gruntfile: {
      files: 'Gruntfile.js',
      tasks: ['jshint:gruntfile'],
      options: {
        reload: true
      }
    },
    js: {
      files: 'src/js/*.js',
      tasks: ['jshint', 'uglify:dev']
    },
    css: {
      files: 'src/css/*.css',
      tasks: ['csslint', 'cssmin:dev']
    },
    html: {
      files: ['src/default.htm', 'src/partials/start.partial.htm'],
      tasks: ['processhtml:dev', 'htmlmin:dev']
    }
  });

  grunt.registerTask('dev', ['uglify:dev', 'copy:dev', 'processhtml:dev', 'htmlmin:dev', 'cssmin:dev']);
  grunt.registerTask('dist', ['uglify:dist', 'copy:dist', 'processhtml:dist', 'htmlmin:dist', 'cssmin:dist']);
  grunt.registerTask('check', ['jshint', 'csslint', 'htmlangular', 'clean']);
  grunt.registerTask('serve', ['connect', 'watch']);
};
<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('loopback:extended:compile');

var lib = require('../');
var Joi = require('joi');
var mixable = require('mixable-object');

var boot = require('loopback-boot');
var compile = boot.compile;
var ConfigLoader = boot.ConfigLoader;

module.exports = extendedCompile;

/**
 * Merge the configs from lib with that from the config files, and in case conflict the config file
 * is overridden. For all possible config files, see the "Environment-specific configuration" doc.
 * @see node_modules/loopback-boot/lib/compiler.js
 * @see https://docs.strongloop.com/display/public/LB/Environment-specific+configuration
 */
function extendedCompile(options) {
  // Code from the original compile().
  options = options || {};
  if (typeof options === 'string') {
    options = { appRootDir: options };
  }
  var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
  var env = options.env || process.env.NODE_ENV || 'development';

  // Load and mixin.
  if (!options.models) {
    var modelsRootDir = options.modelsRootDir || appRootDir;
    options.models = ConfigLoader.loadModels(modelsRootDir, env);
    mixinConfig(options, 'models');

    // The `_meta` in the `options.models` will be deleted by the original `compile()`, and because
    // `options.models` is usually cached by `require()`, this makes the app and any new app not
    // possible to be reloaded. Cloning it here.
    if (options.models) {
      options.models = Object.assign({}, options.models);
    }
    mixinMeta(options.models._meta);
    console.log(options.models._meta);
  }

  // Load and mixin.
  if (!options.dataSources) {
    var dsRootDir = options.dsRootDir || appRootDir;
    options.dataSources = ConfigLoader.loadDataSources(dsRootDir, env);
    mixinConfig(options, 'dataSources');
  }

  // Load and mixin.
  if (!options.middleware) {
    var middlewareRootDir = appRootDir;
    options.middleware = ConfigLoader.loadMiddleware(appRootDir, env);
    mixinConfig(options, 'middleware');
  }

  // Load and mixin.
  if (!options.components) {
    var componentRootDir = appRootDir;
    options.components = ConfigLoader.loadComponents(componentRootDir, env);
    mixinConfig(options, 'components');
  }

  // The original compile().
  return compile(options);
}

/**
 * Mixin.
 */
function mixinConfig(configs, key) {
  if (lib.configs && lib.configs[key]) {
    debug('loading the "%s" config files from lib.', key);
    configs[key] = mixable(configs[key]);
    configs[key].mixin(lib.configs[key]);
  }
}

var schemaMeta = Joi.object({
  sources: Joi.array().required(),
  mixins: Joi.array().required()
}).required();

var schemaArray = Joi.array().items(Joi.string()).required();

/**
 * Mixin.
 */
function mixinMeta(modelMeta) {
  // Validate.
  Joi.assert(modelMeta, schemaMeta);

  // The value need to be an array of paths. Pushing them to the top of the config.
  if (lib.models) {
    Joi.assert(lib.models, schemaArray);
    for (var i = 0, len = lib.models.length; i < len; i++) {
      var item = lib.models[i];
      if (modelMeta.sources.indexOf(item) < 0) {
        modelMeta.sources.unshift(item);
      }
    }
  }

  // The value need to be an array of paths. Pushing them to the top of the config.
  if (lib.mixins) {
    Joi.assert(lib.mixins, schemaArray);
    for (var i = 0, len = lib.mixins.length; i < len; i++) {
      var item = lib.mixins[i];
      if (modelMeta.mixins.indexOf(item) < 0) {
        modelMeta.mixins.unshift(item);
      }
    }
  }
}
<commit_msg>Removed a console.log()...<commit_after>'use strict';

var debug = require('debug')('loopback:extended:compile');

var lib = require('../');
var Joi = require('joi');
var mixable = require('mixable-object');

var boot = require('loopback-boot');
var compile = boot.compile;
var ConfigLoader = boot.ConfigLoader;

module.exports = extendedCompile;

/**
 * Merge the configs from lib with that from the config files, and in case conflict the config file
 * is overridden. For all possible config files, see the "Environment-specific configuration" doc.
 * @see node_modules/loopback-boot/lib/compiler.js
 * @see https://docs.strongloop.com/display/public/LB/Environment-specific+configuration
 */
function extendedCompile(options) {
  // Code from the original compile().
  options = options || {};
  if (typeof options === 'string') {
    options = { appRootDir: options };
  }
  var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
  var env = options.env || process.env.NODE_ENV || 'development';

  // Load and mixin.
  if (!options.models) {
    var modelsRootDir = options.modelsRootDir || appRootDir;
    options.models = ConfigLoader.loadModels(modelsRootDir, env);
    mixinConfig(options, 'models');

    // The `_meta` in the `options.models` will be deleted by the original `compile()`, and because
    // `options.models` is usually cached by `require()`, this makes the app and any new app not
    // possible to be reloaded. Cloning it here.
    if (options.models) {
      options.models = Object.assign({}, options.models);
    }
    mixinMeta(options.models._meta);
  }

  // Load and mixin.
  if (!options.dataSources) {
    var dsRootDir = options.dsRootDir || appRootDir;
    options.dataSources = ConfigLoader.loadDataSources(dsRootDir, env);
    mixinConfig(options, 'dataSources');
  }

  // Load and mixin.
  if (!options.middleware) {
    var middlewareRootDir = appRootDir;
    options.middleware = ConfigLoader.loadMiddleware(appRootDir, env);
    mixinConfig(options, 'middleware');
  }

  // Load and mixin.
  if (!options.components) {
    var componentRootDir = appRootDir;
    options.components = ConfigLoader.loadComponents(componentRootDir, env);
    mixinConfig(options, 'components');
  }

  // The original compile().
  return compile(options);
}

/**
 * Mixin.
 */
function mixinConfig(configs, key) {
  if (lib.configs && lib.configs[key]) {
    debug('loading the "%s" config files from lib.', key);
    configs[key] = mixable(configs[key]);
    configs[key].mixin(lib.configs[key]);
  }
}

var schemaMeta = Joi.object({
  sources: Joi.array().required(),
  mixins: Joi.array().required()
}).required();

var schemaArray = Joi.array().items(Joi.string()).required();

/**
 * Mixin.
 */
function mixinMeta(modelMeta) {
  // Validate.
  Joi.assert(modelMeta, schemaMeta);

  // The value need to be an array of paths. Pushing them to the top of the config.
  if (lib.models) {
    Joi.assert(lib.models, schemaArray);
    for (var i = 0, len = lib.models.length; i < len; i++) {
      var item = lib.models[i];
      if (modelMeta.sources.indexOf(item) < 0) {
        modelMeta.sources.unshift(item);
      }
    }
  }

  // The value need to be an array of paths. Pushing them to the top of the config.
  if (lib.mixins) {
    Joi.assert(lib.mixins, schemaArray);
    for (var i = 0, len = lib.mixins.length; i < len; i++) {
      var item = lib.mixins[i];
      if (modelMeta.mixins.indexOf(item) < 0) {
        modelMeta.mixins.unshift(item);
      }
    }
  }
}
<|endoftext|>