<commit_before>/*ngInject*/
export function setupRoutes($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('login', {
            url: '/login',
            template: '<mc-login></mc-login>'
        })
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

'
        })
        .state('projects.list', {
            url: '/list',
            template: '<mc-projects></mc-projects>'
        })
        .state('projects.share', {
            url: '/share',
            template: '<mc-projects-share></mc-projects-share>'
        })
        .state('user', {
            url: '/user',
            abstract: true,
            template: '

'
        })
        .state('user.apikey', {
            url: '/apikey',
            template: '<mc-user-apikey></mc-user-apikey>'
        })
        .state('user.password', {
            url: '/password',
            template: '<mc-user-password></mc-user-password>'
        })
        .state('project', {
            url: '/project/:project_id',
            abstract: true,
            template: '<ui-view flex="100" layout="column"></ui-view>',
            resolve: {
                // Set the current project in the project service so all components
                // will resolve without having to worry if a promise has resolved.
                // The resolved object is ignored.
                _project: ["$stateParams", "projectsService", "project",
                    // Inject projects so that it resolves before looking up the project.
                    function($stateParams, projectsService, project) {
                        return projectsService.getProject($stateParams.project_id)
                            .then(function(proj) {
                                project.set(proj);
                                return proj;
                            });
                    }],

                _templates: ["processTemplates", "templates", "_project",
                    function(processTemplates, templates, project) {
                        var projectTemplates = processTemplates.templates(project.process_templates, project.id);
                        templates.set(projectTemplates);
                        return projectTemplates;
                    }]
            }
        })
        .state('project.home', {
            url: '/home',
            template: '<mc-project-home></mc-project-home>',
            // hack to update project view
            resolve: {
                // Set the current project in the project service so all components
                // will resolve without having to worry if a promise has resolved.
                // The resolved object is ignored.
                _project: ["$stateParams", "projectsService", "project",
                    // Inject projects so that it resolves before looking up the project.
                    function($stateParams, projectsService, project) {
                        return projectsService.getProject($stateParams.project_id)
                            .then(function(proj) {
                                project.set(proj);
                                return proj;
                            });
                    }]
            }
        })
        .state('project.search', {
            url: '/search/:query',
            template: '<mc-project-search></mc-project-search>'
        })
        .state('project.create', {
            url: '/create',
            abstract: true,
            template: '<ui-view flex layout="column"></ui-view>'
        })
        .state('project.experiment', {
            url: '/experiment/:experiment_id',
            template: `<mc-experiment></mc-experiment>`,
            controllerAs: 'ctrl',
            controller: ['experiment', 'currentExperiment', function(experiment, currentExperiment) {
                currentExperiment.set(experiment);
            }],
            resolve: {
                experiment: ['experimentsService', 'toast', 'toUITask', '$stateParams', 'currentExperiment',
                    function(experimentsService, toast, toUITask, $stateParams, currentExperiment) {
                        return experimentsService.getForProject($stateParams.project_id, $stateParams.experiment_id)
                            .then(
                                (e) => {
                                    e.tasks.forEach((task) => toUITask(task));
                                    currentExperiment.set(e);
                                    return e;
                                },
                                () => toast.error('Failed to retrieve experiment')
                            );
                    }
                ]
            }
        })
        .state('project.experiment.details', {
            url: '/details',
            template: '<mc-experiment-details experiment="ctrl.experiment"></mc-experiment-details>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.tasks', {
            url: '/tasks',
            template: '<mc-experiment-tasks></mc-experiment-tasks>'
        })
        .state('project.experiment.forecast', {
            url: '/forecast',
            template: '<mc-experiment-forecast experiment="ctrl.experiment"></mc-experiment-forecast>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.flagged', {
            url: '/flagged',
            template: '<mc-experiment-flagged experiment="ctrl.experiment"></mc-experiment-flagged>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.samples', {
            url: '/samples',
            template: '<mc-experiment-samples experiment="ctrl.experiment"></mc-experiment-samples>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.files', {
            url: '/files',
            template: '<mc-experiment-files experiment="ctrl.experiment"></mc-experiment-files>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.notes', {
            url: '/notes',
            template: '<mc-experiment-notes experiment="ctrl.experiment"></mc-experiment-notes>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.create.process', {
            url: '/process/:template_id/:process_id',
            template: '<mc-process-create></mc-process-create>',
            resolve: {
                _template: ['templates', 'template', '$stateParams', 'projectsService',
                    function(templates, template, $stateParams, projectsService) {
                        if ($stateParams.process_id) {
                            return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                                .then(function(process) {
                                    var t = templates.loadTemplateFromProcess($stateParams.template_id, process);
                                    template.set(t);
                                    return t;
                                });
                        } else {
                            var t = templates.getTemplate($stateParams.template_id);
                            template.set(t);
                            return t;
                        }
                    }]
            }
        })
        .state('project.experiments', {
            url: '/experiments',
            template: '<mc-project-experiments experiments="ctrl.experiments"></mc-project-experiments>',
            controllerAs: 'ctrl',
            controller: ['$stateParams', 'experimentsService', 'toast', function($stateParams, experimentsService, toast) {
                let ctrl = this;
                ctrl.experiments = [];
                experimentsService.getAllForProject($stateParams.project_id).then(
                    (experiments) => {
                        ctrl.experiments = experiments;
                    },
                    () => toast.error('Unable to retrieve experiments for project')
                );
            }]
        })
        .state('project.processes', {
            url: '/processes',
            template: '<mc-project-processes processes="ctrl.processes"></mc-project-processes>',
            controllerAs: 'ctrl',
            controller: ['projectsService', '$stateParams', 'toastr',
                function(projectsService, $stateParams, toastr) {
                    var ctrl = this;
                    ctrl.processes = [];
                    projectsService.getProjectProcesses($stateParams.project_id).then(
                        (processes) => {
                            ctrl.processes = processes;
                        },
                        () => toastr.error('Unable to retrieve project processes', 'Error', {closeButton: true})
                    )
                }]
        })
        .state('project.process', {
            url: '/process/:process_id',
            template: '<mc-process></mc-process>',
            resolve: {
                _process: ['process', 'projectsService', '$stateParams',
                    function(process, projectsService, $stateParams) {
                        console.log('setting process');
                        return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                            .then(function(p) {
                                console.log('got process', p);
                                process.set(p);
                                console.log('past process.set');
                                return p;
                            });
                    }]
            }
        })
        .state('project.process.edit', {
            url: '/edit',
            template: '<mc-process-edit></mc-process-edit>',
            resolve: {
                _process: ['process', 'projectsService', '$stateParams', 'processEdit', 'templates',
                    function(process, projectsService, $stateParams, processEdit, templates) {
                        return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                            .then(function(proc) {
                                var t = templates.getTemplate(proc.process_name);
                                var p = processEdit.fillProcess(t, proc);
                                process.set(p);
                                return p;
                            });
                    }]
            }
        })
        .state('project.samples', {
            url: '/samples',
            template: '<mc-project-samples samples="ctrl.samples"></mc-project-samples>',
            controllerAs: 'ctrl',
            controller: ['samplesService', '$stateParams', 'toastr',
                function(samplesService, $stateParams, toastr) {
                    var ctrl = this;
                    ctrl.samples = [];
                    samplesService.getProjectSamples($stateParams.project_id).then(
                        (samples) => {
                            //console.dir(samples);
                            ctrl.samples = samples;
                        },
                        () => toastr.error('Error retrieving samples for project', 'Error', {closeButton: true})
                    );
                }]
        })
        .state('project.samples.sample', {
            url: '/sample/:sample_id',
            template: '<mc-sample></mc-sample>'
        })
        .state('project.files', {
            url: '/files',
            template: '<mc-file-tree flex layout-fill></mc-file-tree>'
        })
        .state('project.files.uploads', {
            url: '/uploads',
            template: '<mc-file-uploads></mc-file-uploads>'
        })
        .state('project.files.file', {
            url: '/file/:file_id',
            template: '<mc-file></mc-file>'
        })
        .state('project.files.dir', {
            url: '/dir/:dir_id',
            template: '<mc-dir></mc-dir>'
        })
        .state('project.settings', {
            url: '/settings',
            template: '<mc-project-settings></mc-project-settings>'
        });

    $urlRouterProvider.otherwise('/login');
}
<commit_msg>Move comment.<commit_after>/*ngInject*/
export function setupRoutes($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('login', {
            url: '/login',
            template: '<mc-login></mc-login>'
        })
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

'
        })
        .state('projects.list', {
            url: '/list',
            template: '<mc-projects></mc-projects>'
        })
        .state('projects.share', {
            url: '/share',
            template: '<mc-projects-share></mc-projects-share>'
        })
        .state('user', {
            url: '/user',
            abstract: true,
            template: '

'
        })
        .state('user.apikey', {
            url: '/apikey',
            template: '<mc-user-apikey></mc-user-apikey>'
        })
        .state('user.password', {
            url: '/password',
            template: '<mc-user-password></mc-user-password>'
        })
        .state('project', {
            url: '/project/:project_id',
            abstract: true,
            template: '<ui-view flex="100" layout="column"></ui-view>',
            resolve: {
                // Set the current project in the project service so all components
                // will resolve without having to worry if a promise has resolved.
                // The resolved object is ignored.
                _project: ["$stateParams", "projectsService", "project",
                    // Inject projects so that it resolves before looking up the project.
                    function($stateParams, projectsService, project) {
                        return projectsService.getProject($stateParams.project_id)
                            .then(function(proj) {
                                project.set(proj);
                                return proj;
                            });
                    }],

                _templates: ["processTemplates", "templates", "_project",
                    function(processTemplates, templates, project) {
                        var projectTemplates = processTemplates.templates(project.process_templates, project.id);
                        templates.set(projectTemplates);
                        return projectTemplates;
                    }]
            }
        })
        .state('project.home', {
            url: '/home',
            template: '<mc-project-home></mc-project-home>',
            resolve: {
                // hack to update project view
                // Set the current project in the project service so all components
                // will resolve without having to worry if a promise has resolved.
                // The resolved object is ignored.
                _project: ["$stateParams", "projectsService", "project",
                    // Inject projects so that it resolves before looking up the project.
                    function($stateParams, projectsService, project) {
                        return projectsService.getProject($stateParams.project_id)
                            .then(function(proj) {
                                project.set(proj);
                                return proj;
                            });
                    }]
            }
        })
        .state('project.search', {
            url: '/search/:query',
            template: '<mc-project-search></mc-project-search>'
        })
        .state('project.create', {
            url: '/create',
            abstract: true,
            template: '<ui-view flex layout="column"></ui-view>'
        })
        .state('project.experiment', {
            url: '/experiment/:experiment_id',
            template: `<mc-experiment></mc-experiment>`,
            controllerAs: 'ctrl',
            controller: ['experiment', 'currentExperiment', function(experiment, currentExperiment) {
                currentExperiment.set(experiment);
            }],
            resolve: {
                experiment: ['experimentsService', 'toast', 'toUITask', '$stateParams', 'currentExperiment',
                    function(experimentsService, toast, toUITask, $stateParams, currentExperiment) {
                        return experimentsService.getForProject($stateParams.project_id, $stateParams.experiment_id)
                            .then(
                                (e) => {
                                    e.tasks.forEach((task) => toUITask(task));
                                    currentExperiment.set(e);
                                    return e;
                                },
                                () => toast.error('Failed to retrieve experiment')
                            );
                    }
                ]
            }
        })
        .state('project.experiment.details', {
            url: '/details',
            template: '<mc-experiment-details experiment="ctrl.experiment"></mc-experiment-details>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.tasks', {
            url: '/tasks',
            template: '<mc-experiment-tasks></mc-experiment-tasks>'
        })
        .state('project.experiment.forecast', {
            url: '/forecast',
            template: '<mc-experiment-forecast experiment="ctrl.experiment"></mc-experiment-forecast>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.flagged', {
            url: '/flagged',
            template: '<mc-experiment-flagged experiment="ctrl.experiment"></mc-experiment-flagged>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.samples', {
            url: '/samples',
            template: '<mc-experiment-samples experiment="ctrl.experiment"></mc-experiment-samples>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.files', {
            url: '/files',
            template: '<mc-experiment-files experiment="ctrl.experiment"></mc-experiment-files>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.experiment.notes', {
            url: '/notes',
            template: '<mc-experiment-notes experiment="ctrl.experiment"></mc-experiment-notes>',
            controllerAs: 'ctrl',
            controller: ['experiment', function(experiment) {
                this.experiment = experiment;
            }]
        })
        .state('project.create.process', {
            url: '/process/:template_id/:process_id',
            template: '<mc-process-create></mc-process-create>',
            resolve: {
                _template: ['templates', 'template', '$stateParams', 'projectsService',
                    function(templates, template, $stateParams, projectsService) {
                        if ($stateParams.process_id) {
                            return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                                .then(function(process) {
                                    var t = templates.loadTemplateFromProcess($stateParams.template_id, process);
                                    template.set(t);
                                    return t;
                                });
                        } else {
                            var t = templates.getTemplate($stateParams.template_id);
                            template.set(t);
                            return t;
                        }
                    }]
            }
        })
        .state('project.experiments', {
            url: '/experiments',
            template: '<mc-project-experiments experiments="ctrl.experiments"></mc-project-experiments>',
            controllerAs: 'ctrl',
            controller: ['$stateParams', 'experimentsService', 'toast', function($stateParams, experimentsService, toast) {
                let ctrl = this;
                ctrl.experiments = [];
                experimentsService.getAllForProject($stateParams.project_id).then(
                    (experiments) => {
                        ctrl.experiments = experiments;
                    },
                    () => toast.error('Unable to retrieve experiments for project')
                );
            }]
        })
        .state('project.processes', {
            url: '/processes',
            template: '<mc-project-processes processes="ctrl.processes"></mc-project-processes>',
            controllerAs: 'ctrl',
            controller: ['projectsService', '$stateParams', 'toastr',
                function(projectsService, $stateParams, toastr) {
                    var ctrl = this;
                    ctrl.processes = [];
                    projectsService.getProjectProcesses($stateParams.project_id).then(
                        (processes) => {
                            ctrl.processes = processes;
                        },
                        () => toastr.error('Unable to retrieve project processes', 'Error', {closeButton: true})
                    )
                }]
        })
        .state('project.process', {
            url: '/process/:process_id',
            template: '<mc-process></mc-process>',
            resolve: {
                _process: ['process', 'projectsService', '$stateParams',
                    function(process, projectsService, $stateParams) {
                        console.log('setting process');
                        return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                            .then(function(p) {
                                console.log('got process', p);
                                process.set(p);
                                console.log('past process.set');
                                return p;
                            });
                    }]
            }
        })
        .state('project.process.edit', {
            url: '/edit',
            template: '<mc-process-edit></mc-process-edit>',
            resolve: {
                _process: ['process', 'projectsService', '$stateParams', 'processEdit', 'templates',
                    function(process, projectsService, $stateParams, processEdit, templates) {
                        return projectsService.getProjectProcess($stateParams.project_id, $stateParams.process_id)
                            .then(function(proc) {
                                var t = templates.getTemplate(proc.process_name);
                                var p = processEdit.fillProcess(t, proc);
                                process.set(p);
                                return p;
                            });
                    }]
            }
        })
        .state('project.samples', {
            url: '/samples',
            template: '<mc-project-samples samples="ctrl.samples"></mc-project-samples>',
            controllerAs: 'ctrl',
            controller: ['samplesService', '$stateParams', 'toastr',
                function(samplesService, $stateParams, toastr) {
                    var ctrl = this;
                    ctrl.samples = [];
                    samplesService.getProjectSamples($stateParams.project_id).then(
                        (samples) => {
                            //console.dir(samples);
                            ctrl.samples = samples;
                        },
                        () => toastr.error('Error retrieving samples for project', 'Error', {closeButton: true})
                    );
                }]
        })
        .state('project.samples.sample', {
            url: '/sample/:sample_id',
            template: '<mc-sample></mc-sample>'
        })
        .state('project.files', {
            url: '/files',
            template: '<mc-file-tree flex layout-fill></mc-file-tree>'
        })
        .state('project.files.uploads', {
            url: '/uploads',
            template: '<mc-file-uploads></mc-file-uploads>'
        })
        .state('project.files.file', {
            url: '/file/:file_id',
            template: '<mc-file></mc-file>'
        })
        .state('project.files.dir', {
            url: '/dir/:dir_id',
            template: '<mc-dir></mc-dir>'
        })
        .state('project.settings', {
            url: '/settings',
            template: '<mc-project-settings></mc-project-settings>'
        });

    $urlRouterProvider.otherwise('/login');
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013 Continuuity, Inc.
 */

var util = require("util"),
  fs = require('fs'),
  xml2js = require('xml2js'),
  promise = require('q'),
  sys = require('sys'),
  argv = require('optimist').argv,
  nock = require('nock');

var WebAppServer = require('../common/server');

// Default port for the Dashboard.
var DEFAULT_BIND_PORT = 9999;

/**
 * Set environment.
 */
process.env.NODE_ENV = 'development';

/**
 * Log level.
 */
var logLevel = 'INFO';

var DevServer = function() {
  this.getConfig()
      .then(this.setAttrs.bind(this));
};
util.inherits(DevServer, WebAppServer);

DevServer.prototype.setAttrs = function(version) {
  if (this.config['dashboard.https.enabled'] === "true") {
    DevServer.super_.call(this, __dirname, logLevel, true);
  } else {
    DevServer.super_.call(this, __dirname, logLevel, false);
  }
  this.cookieName = 'continuuity-local-edition';
  this.secret = 'local-edition-secret';
  this.logger = this.getLogger();
  this.setCookieSession(this.cookieName, this.secret);
  this.configureExpress();
}

/**
 * Sets config data for application server.
 * @param {Function} opt_callback Callback function to start sever start process.
 */
DevServer.prototype.getConfig = function() {
  var deferredObj = promise.defer();
//      promises = [],
//      readfile;

//  readfile = function (path, format) {
//    var deferred = promise.defer();
//    if (format) {
//      fs.readFile(path, format, function(err, result) {
//        deferred.resolve(result);
//      });
//    } else {
//      fs.readFile(path, function(err, result) {
//        deferred.resolve(result);
//      });
//    }
//    return deferred.promise;
//  };
//  //There should definitely be better way to do this.
//  readfile(__dirname + '/continuuity-local.xml')
//    .then( function(result, error) {
//      var parser = new xml2js.Parser();
//      parser.parseString(result, function(err, result) {
//        result = result.configuration.property;
//        for (var item in result) {
//          item = result[item];
//          this.config[item.name] = item.value[0];
//        }
//      }.bind(this));
//      return readfile(__dirname + '/../../../VERSION', 'utf-8');
//    }.bind(this))
//    .then( function(version) {
//      return readfile(__dirname + '/.credential', 'utf-8');
//    })
//    .then( function(error, apiKey) {
//      this.Api.configure(this.config, apiKey || null);
//      this.configSet = true;
//      deferredObj.resolve(version);
//    }.bind(this));

    var self = this;
    fs.readFile(__dirname + '/continuuity-local.xml', function(error, result) {
      var parser = new xml2js.Parser();
      parser.parseString(result, function(err, result) {
        result = result.configuration.property;
        var localhost = self.getLocalHost();
        for (var item in result) {
          item = result[item];
          self.config[item.name] = item.value[0];
        }
      });

      fs.readFile(__dirname + '/../../../VERSION', "utf-8", function(error, version) {

        fs.readFile(__dirname + '/.credential', "utf-8", function(error, apiKey) {
          self.Api.configure(self.config, apiKey || null);
          self.configSet = true;
          deferredObj.resolve(version);
        });
      });
    });

  return deferredObj.promise;
};

/**
 * Starts the server after getting config, sets up socket io, configures route handlers.
 */
DevServer.prototype.start = function() {
  this.getConfig()
      .then(this.launchServer.bind(this));
};

DevServer.prototype.launchServer = function(version) {
   var key,
       cert,
       options = {};
   options = this.configureSSL();
   this.server = this.getServerInstance(options, this.app);
   this.setEnvironment('local', 'Development Kit', version, this.startServer.bind(this));
}

DevServer.prototype.configureSSL = function () {
  var options = {};
  if (this.config['dashboard.https.enabled'] === "true") {
    key = this.config['dashboard.ssl.key'];
    cert = this.config['dashboard.ssl.cert'];
    options = {
      key: fs.readFileSync(key),
      cert: fs.readFileSync(cert),
      requestCert: false,
      rejectUnauthorized: false
    };
    this.config['dashboard.bind.port'] = this.config['dashboard.bind.port.ssl'];
  }
  return options;
}

DevServer.prototype.startServer = function () {
  this.bindRoutes();

  if (!('dashboard.bind.port' in this.config)) {
    this.config['dashboard.bind.port'] = this.config['dashboard.bind.port.nonssl'];
  }

  this.server.listen(this.config['dashboard.bind.port']);

  this.logger.info('Listening on port', this.config['dashboard.bind.port']);
  this.logger.info(this.config);

  /**
  * If mocks are enabled, use mock injector to simulate some responses.
  */
  var enableMocks = !!(argv.enableMocks === 'true');
  if (enableMocks) {
    this.logger.info('Webapp running with mocks enabled.');
    HttpMockInjector = require('../../test/httpMockInjector');
    new HttpMockInjector(nock, this.config['gateway.server.address'], this.config['gateway.server.port']);
  }

}
/**
 * Catch anything uncaught.
 */
process.on('uncaughtException', function (err) {
  debugger;
  devServer.logger.info('Uncaught Exception', err);
});

var devServer = new DevServer();
devServer.start();

/**
 * Export app.
 */
module.exports = devServer;<commit_msg>Promisify callbacks in local server<commit_after>/**
 * Copyright (c) 2013 Continuuity, Inc.
 */

var util = require("util"),
  fs = require('fs'),
  xml2js = require('xml2js'),
  promise = require('q'),
  sys = require('sys'),
  argv = require('optimist').argv,
  nock = require('nock');

var WebAppServer = require('../common/server');

// Default port for the Dashboard.
var DEFAULT_BIND_PORT = 9999;

/**
 * Set environment.
 */
process.env.NODE_ENV = 'development';

/**
 * Log level.
 */
var logLevel = 'INFO';
var devServer;

var DevServer = function() {
  this.getConfig()
      .then(function(version) {
        this.setAttrs(version);
        this.start();
      }.bind(this))
};
util.inherits(DevServer, WebAppServer);

DevServer.prototype.setAttrs = function(version) {
  if (this.config['dashboard.https.enabled'] === "true") {
    DevServer.super_.call(this, __dirname, logLevel, true);
  } else {
    DevServer.super_.call(this, __dirname, logLevel, false);
  }
  this.cookieName = 'continuuity-local-edition';
  this.version = version;
  this.secret = 'local-edition-secret';
  this.logger = this.getLogger();
  this.setCookieSession(this.cookieName, this.secret);
  this.configureExpress();
}

/**
 * Sets config data for application server.
 * @param {Function} opt_callback Callback function to start sever start process.
 */
DevServer.prototype.getConfig = function() {
  var deferredObj = promise.defer(),
      promises = [],
      version,
      readfile;

  readfile = function (path, format) {
    var deferred = promise.defer();
    if (format) {
      fs.readFile(path, format, function(err, result) {
        deferred.resolve(result);
      });
    } else {
      fs.readFile(path, function(err, result) {
        deferred.resolve(result);
      });
    }
    return deferred.promise;
  };
  //There should definitely be better way to do this.
  readfile(__dirname + '/continuuity-local.xml')
    .then( function(result, error) {
      var parser = new xml2js.Parser();
      parser.parseString(result, function(err, result) {
        result = result.configuration.property;
        for (var item in result) {
          item = result[item];
          this.config[item.name] = item.value[0];
        }
      }.bind(this));
      return  readfile(__dirname + '/../../../VERSION', 'utf-8');

    }.bind(this))
    .then( function(v) {
      version = v;
      return readfile(__dirname + '/.credential', 'utf-8');
    })
    .then( function(error, apiKey) {
      this.Api.configure(this.config, apiKey || null);
      this.configSet = true;
      deferredObj.resolve(version);
    }.bind(this));
  return deferredObj.promise;
};

/**
 * Starts the server after getting config, sets up socket io, configures route handlers.
 */
DevServer.prototype.start = function() {
  this.launchServer();
};

DevServer.prototype.launchServer = function() {
   var key,
       cert,
       options = {};
   options = this.configureSSL();
   this.server = this.getServerInstance(options, this.app);
   this.setEnvironment('local', 'Development Kit', this.version, this.startServer.bind(this));
}

DevServer.prototype.configureSSL = function () {
  var options = {};
  if (this.config['dashboard.https.enabled'] === "true") {
    key = this.config['dashboard.ssl.key'];
    cert = this.config['dashboard.ssl.cert'];
    options = {
      key: fs.readFileSync(key),
      cert: fs.readFileSync(cert),
      requestCert: false,
      rejectUnauthorized: false
    };
    this.config['dashboard.bind.port'] = this.config['dashboard.bind.port.ssl'];
  }
  return options;
}

DevServer.prototype.startServer = function () {
  this.bindRoutes();

  if (!('dashboard.bind.port' in this.config)) {
    this.config['dashboard.bind.port'] = this.config['dashboard.bind.port.nonssl'];
  }

  this.server.listen(this.config['dashboard.bind.port']);

  this.logger.info('Listening on port', this.config['dashboard.bind.port']);
  this.logger.info(this.config);

  /**
  * If mocks are enabled, use mock injector to simulate some responses.
  */
  var enableMocks = !!(argv.enableMocks === 'true');
  if (enableMocks) {
    this.logger.info('Webapp running with mocks enabled.');
    HttpMockInjector = require('../../test/httpMockInjector');
    new HttpMockInjector(nock, this.config['gateway.server.address'], this.config['gateway.server.port']);
  }

}
/**
 * Catch anything uncaught.
 */
process.on('uncaughtException', function (err) {
  debugger;
  devServer.logger.info('Uncaught Exception', err);
});

devServer = new DevServer();
/**
 * Export app.
 */
module.exports = devServer;<|endoftext|>


<commit_before>/**
 * Test dependencies
 */

var util = require('util');
var assert = require('assert');
var socketHelper = require('./helpers/socketHelper.js');
var appHelper = require('./helpers/appHelper');
var httpHelper = require('./helpers/httpHelper');

/**
 * Errors
 */
var Err = {
  badResponse: function(response) {
    return 'Wrong server response!  Response :::\n' + util.inspect(response);
  }
};

describe('pubsub :: ', function() {

  var sailsprocess;
  var socket1;
  var socket2;
  var appName = 'testApp';

  describe('Model events', function() {

    before(function(done) {
      appHelper.build(appName, function(err) {
        if (err) {
          throw new Error(err);
        }
        socketHelper.writeModelConfig();
        appHelper.liftWithTwoSockets({
          silly: false
        }, function(err, sails, _socket1, _socket2) {
          if (err) {
            throw new Error(err);
          }
          sailsprocess = sails;
          socket1 = _socket1;
          socket2 = _socket2;

          httpHelper.testRoute('get', 'user/create?name=joe', function(err) {
            if (err) {
              return done(err);
            }
            httpHelper.testRoute('get', 'user/create?name=abby', function(err) {
              if (err) {
                return done(err);
              }
              done();
            });
          });

        });
      });
    });

    after(function(done) {

      process.chdir('../');
      appHelper.teardown();
      if (sailsprocess) {
        return sailsprocess.lower(function() {
          setTimeout(done, 100);
        });
      }
      return done();
    });

    describe('when a model no default autosubscribe contexts ', function() {

      after(function(done) {
        socket1.disconnect();
        socket2.disconnect();
        done();
      });

      afterEach(function(done) {
        socket1.removeAllListeners();
        socket2.removeAllListeners();
        done();
      });

      it('updating an instance via put should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.put('/user/1', {
          name: 'scott'
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the update context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=update', done);
        });
        it('updating an instance via put should result in the correct socket messages being received', function(done) {
          var TIME_TO_WAIT = 1500;
          var timer = setTimeout(function() {
            done(new Error('`update` event was not fired in a timely manner (probably was never going to happen.)  Waited ' + TIME_TO_WAIT + 'ms.'));
          }, TIME_TO_WAIT);
          socket2.on('user', function(message) {
            clearTimeout(timer);
            assert(message.id == 1 && message.verb == 'updated' && message.data.name === 'bob', Err.badResponse(message));
            done();
          });
          socket1.put('/user/1', {
            name: 'bob'
          });
        });
      });

      it('sending a message should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.get('/user/message');
        setTimeout(done, 1000);

      });

      describe('after subscribing to the message context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=message', function() {
            done();
          });
        });
        it('sending a message should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'messaged' && message.data.greeting == 'hello', Err.badResponse(message));
            done();
          });
          socket1.get('/user/message');
        });
      });

      it('adding a pet to the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.post('/pet', {
          name: 'rex',
          owner: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the add:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=add:pets', function() {
            done();
          });
        });
        it('adding a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'addedTo' && message.attribute == 'pets' && message.addedId == 2, Err.badResponse(message));
            done();
          });
          socket1.post('/pet', {
            name: 'alice',
            owner: 1
          });
        });
      });

      it('removing a pet from the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/pet', {
          id: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the remove:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=remove:pets', function() {
            done();
          });
        });
        it('removing a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'removedFrom' && message.attribute == 'pets' && message.removedId == 2, Err.badResponse(message));
            done();
          });
          socket1.delete('/pet', {
            id: 2
          });
        });
      });

      it('deleting a user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/user', {
          id: 2
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the destroy context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=destroy', function() {
            done();
          });
        });
        it('deleting a user should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'destroyed', Err.badResponse(message));
            done();
          });
          socket1.delete('/user', {
            id: 1
          });
        });
      });
    });

  });
});
<commit_msg>Improve robustness of pubsub/context test to explicitly call out race conditions and identify issues w/ tests on Travis.<commit_after>/**
 * Test dependencies
 */

var util = require('util');
var assert = require('assert');
var socketHelper = require('./helpers/socketHelper.js');
var appHelper = require('./helpers/appHelper');
var httpHelper = require('./helpers/httpHelper');

/**
 * Errors
 */
var Err = {
  badResponse: function(response) {
    return 'Wrong server response!  Response :::\n' + util.inspect(response);
  }
};

describe('pubsub :: ', function() {

  var sailsprocess;
  var socket1;
  var socket2;
  var appName = 'testApp';

  describe('Model events', function() {

    before(function(done) {
      appHelper.build(appName, function(err) {
        if (err) {
          throw new Error(err);
        }
        socketHelper.writeModelConfig();
        appHelper.liftWithTwoSockets({
          silly: false
        }, function(err, sails, _socket1, _socket2) {
          if (err) {
            throw new Error(err);
          }
          sailsprocess = sails;
          socket1 = _socket1;
          socket2 = _socket2;

          httpHelper.testRoute('get', 'user/create?name=joe', function(err) {
            if (err) {
              return done(err);
            }
            httpHelper.testRoute('get', 'user/create?name=abby', function(err) {
              if (err) {
                return done(err);
              }
              done();
            });
          });

        });
      });
    });

    after(function(done) {

      process.chdir('../');
      appHelper.teardown();
      if (sailsprocess) {
        return sailsprocess.lower(function() {
          setTimeout(done, 100);
        });
      }
      return done();
    });

    describe('when a model no default autosubscribe contexts ', function() {

      after(function(done) {
        socket1.disconnect();
        socket2.disconnect();
        done();
      });

      afterEach(function(done) {
        socket1.removeAllListeners();
        socket2.removeAllListeners();
        done();
      });

      it('updating an instance via put should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.put('/user/1', {
          name: 'scott'
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the update context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=update', done);
        });
        it('updating an record via put should result in the correct socket messages being received', function(done) {
          var tookTooLong;
          var triggeredSocketEvent;

          var TIME_TO_WAIT = 1500;
          var timer = setTimeout(function() {
            tookTooLong = true;
            done(new Error('`update` event was not fired in a timely manner (probably was never going to happen.)  Waited ' + TIME_TO_WAIT + 'ms.'));
          }, TIME_TO_WAIT);
          socket2.on('user', function(message) {
            clearTimeout(timer);
            try {
              assert(message.id === 1 && message.verb === 'updated' && message.data.name === 'bob', Err.badResponse(message));
            }
            catch (e) { return done(e); }

            if (tookTooLong) { return; }
            if (triggeredSocketEvent) {
              return done(new Error('Socket event should not fire more than once!'));
            }
            else {
              triggeredSocketEvent = true;
              return done();
            }
          });
          socket1.put('/user/1', {
            name: 'bob'
          });
        });
      });

      it('sending a message should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.get('/user/message');
        setTimeout(done, 1000);

      });

      describe('after subscribing to the message context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=message', function() {
            done();
          });
        });
        it('sending a message should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'messaged' && message.data.greeting == 'hello', Err.badResponse(message));
            done();
          });
          socket1.get('/user/message');
        });
      });

      it('adding a pet to the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.post('/pet', {
          name: 'rex',
          owner: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the add:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=add:pets', function() {
            done();
          });
        });
        it('adding a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'addedTo' && message.attribute == 'pets' && message.addedId == 2, Err.badResponse(message));
            done();
          });
          socket1.post('/pet', {
            name: 'alice',
            owner: 1
          });
        });
      });

      it('removing a pet from the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/pet', {
          id: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the remove:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=remove:pets', function() {
            done();
          });
        });
        it('removing a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'removedFrom' && message.attribute == 'pets' && message.removedId == 2, Err.badResponse(message));
            done();
          });
          socket1.delete('/pet', {
            id: 2
          });
        });
      });

      it('deleting a user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/user', {
          id: 2
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the destroy context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=destroy', function() {
            done();
          });
        });
        it('deleting a user should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'destroyed', Err.badResponse(message));
            done();
          });
          socket1.delete('/user', {
            id: 1
          });
        });
      });
    });

  });
});
<|endoftext|>


<commit_before>angular.module('locationDetector' , [])

//This module gets user ip addresses using stun if available or simply use the navigator object
//To ask for the users location

.factory('GeoLocation' , function($q , $timeout , $http , $window){
    var location = {
       detectionMode:'', // STUN or GEO
       info:{}, // country name in lower case
       lat:'', // latitude from GEO
       long:'' // longitude from GEO
    };

    //get the IP addresses associated with an account using STUN method
    function getCountryIp(callback){

       //Function to get an rtc connection
       //compatibility for firefox and chrome
       function rtcGetPeerConnection(){
            // Based on work by https://github.com/diafygi/webrtc-ips

            var RTCPeerConnection = window.RTCPeerConnection
                          || window.mozRTCPeerConnection
                          || window.webkitRTCPeerConnection;

            //bypass naive webrtc blocking
            if (!RTCPeerConnection) {
                var iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                document.body.appendChild(iframe);
                var win = iframe.contentWindow;
                window.RTCPeerConnection = win.RTCPeerConnection;
                window.mozRTCPeerConnection = win.mozRTCPeerConnection;
                window.webkitRTCPeerConnection = win.webkitRTCPeerConnection;
                RTCPeerConnection = window.RTCPeerConnection
                    || window.mozRTCPeerConnection
                    || window.webkitRTCPeerConnection;
            }

            return RTCPeerConnection;
        }

        var ip_dups = {};
        var RTCPeerConnection = rtcGetPeerConnection();

        //minimal requirements for data connection
        var mediaConstraints = {
            optional: [{RtpDataChannels: true}]
        };

        var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

        //construct a new RTCPeerConnection
        //@TODO check to see if pc is online
        var pc = new RTCPeerConnection(servers, mediaConstraints);

        function handleCandidate(candidate){
            //match just the IP address
            var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
            var ip_addr = ip_regex.exec(candidate)[1];

            //remove duplicates
            if(ip_dups[ip_addr] === undefined){
                return ip_addr;
            }

            ip_dups[ip_addr] = true;
        }

        //listen for candidate events
        pc.onicecandidate = function(ice){
            //skip non-candidate events
            if(ice.candidate)
                handleCandidate(ice.candidate.candidate);
        };

        //create a bogus data channel
        pc.createDataChannel("");

        //create an offer sdp
        pc.createOffer(function(result){

            //trigger the stun server request
            pc.setLocalDescription(result, function(){}, function(){});

        }, function(){});

        //wait for a while to let everything done
        $timeout(function(){
            //read candidate info from local description
            var lines = pc.localDescription.sdp.split('\n');
            var ips = [];

            lines.forEach(function(line){
                if(line.indexOf('a=candidate:') === 0){
                    ips.push(handleCandidate(line));
                }
            });

            //Return array of ip addresses to calling function
            callback(ips[ips.length-1]);

        }, 3000);
    }

    //Gets location information from ip address
    function getLocationInfo(ip , callback){
        console.log(ip);
        $http({
          method:'GET',
          url:'http://freegeoip.net/json/'+ip
        })
        .success(function(data){
             callback(null , data);
        })
        .error(function(err){
             callback(err , null);
        });
    }

    //public function to get location
    function getLocation(){
         var promise = $q.defer();

         //check if user is online
         if($window.navigator.onLine){
             //Get clients ip addresses using STUN server
             getCountryIp(function(ip){
                 if(ip){
                     getLocationInfo(ip , function(err , info){
                          if(err){
                              console.log('could not get location info');
                              //@TODO use alternative mode like asking user for location
                          }
                          else{
                             location.detectionMode = 'STUN';
                             location.info = info;
                             console.log(location);
                          }
                     });
                 }
                 else{
                    //@TODO use GeoLocation method instead
                 }
             });
         }
         else{
            alert('You are currently offline');
         }

         return promise.promise;
    }

     //
     return {
         getLocation:getLocation
     }
});
<commit_msg>Signed-off-by: codemuhammed <codemuhammed@gmail.com><commit_after>angular.module('locationDetector' , [])

//This module gets user ip addresses using stun if available or simply use the navigator object
//To ask for the users location

.factory('GeoLocation' , function($q , $timeout , $http , $window){
    var location = {
       detectionMode:'', // STUN or GEO
       info:{}, // country name in lower case
       lat:'', // latitude from GEO
       long:'' // longitude from GEO
    };

    //get the IP addresses associated with an account using STUN method
    function getCountryIp(callback){

       //Function to get an rtc connection
       //compatibility for firefox and chrome
       function rtcGetPeerConnection(){
            // Based on work by https://github.com/diafygi/webrtc-ips

            var RTCPeerConnection = window.RTCPeerConnection
                          || window.mozRTCPeerConnection
                          || window.webkitRTCPeerConnection;

            //bypass naive webrtc blocking
            if (!RTCPeerConnection) {
                var iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                document.body.appendChild(iframe);
                var win = iframe.contentWindow;
                window.RTCPeerConnection = win.RTCPeerConnection;
                window.mozRTCPeerConnection = win.mozRTCPeerConnection;
                window.webkitRTCPeerConnection = win.webkitRTCPeerConnection;
                RTCPeerConnection = window.RTCPeerConnection
                    || window.mozRTCPeerConnection
                    || window.webkitRTCPeerConnection;
            }

            return RTCPeerConnection;
        }

        var ip_dups = {};
        var RTCPeerConnection = rtcGetPeerConnection();

        //minimal requirements for data connection
        var mediaConstraints = {
            optional: [{RtpDataChannels: true}]
        };

        var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

        //construct a new RTCPeerConnection
        //@TODO check to see if pc is online
        var pc = new RTCPeerConnection(servers, mediaConstraints);

        function handleCandidate(candidate){
            //match just the IP address
            var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
            var ip_addr = ip_regex.exec(candidate)[1];

            //remove duplicates
            if(ip_dups[ip_addr] === undefined){
                return ip_addr;
            }

            ip_dups[ip_addr] = true;
        }

        //listen for candidate events
        pc.onicecandidate = function(ice){
            //skip non-candidate events
            if(ice.candidate)
                handleCandidate(ice.candidate.candidate);
        };

        //create a bogus data channel
        pc.createDataChannel("");

        //create an offer sdp
        pc.createOffer(function(result){

            //trigger the stun server request
            pc.setLocalDescription(result, function(){}, function(){});

        }, function(){});

        //wait for a while to let everything done
        $timeout(function(){
            //read candidate info from local description
            var lines = pc.localDescription.sdp.split('\n');
            var ips = [];

            lines.forEach(function(line){
                if(line.indexOf('a=candidate:') === 0){
                    ips.push(handleCandidate(line));
                }
            });

            //Return array of ip addresses to calling function
            callback(ips[ips.length-1]);

        }, 3000);
    }

    //Gets location information from ip address
    function getLocationInfo(ip , callback){
        console.log(ip);
        $http({
          method:'GET',
          url:'http://freegeoip.net/json/'+ip
        })
        .success(function(data){
             callback(null , data);
        })
        .error(function(err){
             console.log(err);
             callback(err , null);
        });
    }

    //public function to get location
    function getLocation(){
         var promise = $q.defer();

         //Get clients ip addresses using STUN server
         getCountryIp(function(ip){
             if(ip){
                 getLocationInfo(ip , function(err , info){
                      if(err){
                          console.log('could not get location info');
                          //@TODO use alternative mode like asking user for location
                      }
                      else{
                         location.detectionMode = 'STUN';
                         location.info = info;
                         console.log(location);
                      }
                 });
             }
             else{
                //@TODO use GeoLocation method instead
             }
         });

         return promise.promise;
    }

     //
     return {
         getLocation:getLocation
     }
});
<|endoftext|>


<commit_before>var Checker = require('../../../lib/checker');
var assert = require('assert');

describe('rules/require-spaces-inside-array-brackets', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
    });

    describe('"all"', function() {
        beforeEach(function() {
            checker.configure({ requireSpacesInsideArrayBrackets: 'all' });
        });

        it('should report missing space after opening brace', function() {
            assert(checker.checkString('var x = [1 ];').getErrorCount() === 1);
        });

        it('should report missing space before closing brace', function() {
            assert(checker.checkString('var x = [ 1];').getErrorCount() === 1);
        });

        it('should report missing space in both cases', function() {
            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
        });

        it('should not report with spaces', function() {
            assert(checker.checkString('var x = [ 1 ];').isEmpty());
        });

        it('should not report for empty array', function() {
            assert(checker.checkString('var x = [];').isEmpty());
        });

        it('should report for nested array', function() {
            assert(checker.checkString('var x = [[ 1 ]];').getErrorCount() === 2);
        });

        it('should report anything for empty array', function() {
            assert(checker.checkString('[];').isEmpty());
        });

        it('should not report with comments before the first element', function() {
            assert(checker.checkString(
                'var x = [ /*A*/ 1, 2 ]'
            ).isEmpty());
        });

        it('should not report with comments after the last element', function() {
            assert(checker.checkString(
                'var x = [ 1, 2, /*Z*/ ]'
            ).isEmpty());
        });
    });

    describe('"allButNested"', function() {
        beforeEach(function() {
            checker.configure({ requireSpacesInsideArrayBrackets: 'allButNested' });
        });

        it('should report missing space after opening brace', function() {
            assert(checker.checkString('var x = [1 ];').getErrorCount() === 1);
        });

        it('should report missing space before closing brace', function() {
            assert(checker.checkString('var x = [ 1];').getErrorCount() === 1);
        });

        it('should report missing space in both cases', function() {
            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
        });

        it('should not report with spaces', function() {
            assert(checker.checkString('var x = [ 1 ];').isEmpty());
        });

        it('should not report for nested array', function() {
            assert(checker.checkString('var x = [[ 1 ], [ 2 ]];').isEmpty());
        });

        it('should report anything for empty array', function() {
            assert(checker.checkString('[[]];').isEmpty());
        });
    });

    describe('exceptions', function() {
        it('should not report missing space for parentheses', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['{', '}']
                }
            });

            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
            assert(checker.checkString('var x = [{ a: 1 }];').isEmpty());
        });

        it('should report missing space for the array brackets', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['[', ']']
                }
            });

            assert(checker.checkString('var x = [{}];').getErrorCount() === 2);
            assert(checker.checkString('var x = [[]];').isEmpty());
        });

        it('should not report missing space in both cases', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['(', ')']
                }
            });

            assert(checker.checkString('var x = [{ a: 1 }];').getErrorCount() === 2);
            assert(checker.checkString('var x = [(1)];').isEmpty());
        });
    });
});
<commit_msg>requireSpacesInsideArrayBrackets: comments should be also taken into account<commit_after>var Checker = require('../../../lib/checker');
var assert = require('assert');

describe('rules/require-spaces-inside-array-brackets', function() {
    var checker;

    beforeEach(function() {
        checker = new Checker();
        checker.registerDefaultRules();
    });

    describe('"all"', function() {
        beforeEach(function() {
            checker.configure({ requireSpacesInsideArrayBrackets: 'all' });
        });

        it('should report missing space after opening brace', function() {
            assert(checker.checkString('var x = [1 ];').getErrorCount() === 1);
        });

        it('should report missing space before closing brace', function() {
            assert(checker.checkString('var x = [ 1];').getErrorCount() === 1);
        });

        it('should report missing space in both cases', function() {
            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
        });

        it('should not report with spaces', function() {
            assert(checker.checkString('var x = [ 1 ];').isEmpty());
        });

        it('should not report for empty array', function() {
            assert(checker.checkString('var x = [];').isEmpty());
        });

        it('should report for nested array', function() {
            assert(checker.checkString('var x = [[ 1 ]];').getErrorCount() === 2);
        });

        it('should report anything for empty array', function() {
            assert(checker.checkString('[];').isEmpty());
        });

        it('should not report with comments before the first element', function() {
            assert(checker.checkString(
                'var x = [ /*A*/ 1, 2 ]'
            ).isEmpty());
        });

        it('should not report with comments after the last element', function() {
            assert(checker.checkString(
                'var x = [ 1, 2, /*Z*/ ]'
            ).isEmpty());
        });
    });

    describe('"allButNested"', function() {
        beforeEach(function() {
            checker.configure({ requireSpacesInsideArrayBrackets: 'allButNested' });
        });

        it('should report missing space after opening brace', function() {
            assert(checker.checkString('var x = [1 ];').getErrorCount() === 1);
        });

        it('should report missing space before closing brace', function() {
            assert(checker.checkString('var x = [ 1];').getErrorCount() === 1);
        });

        it('should report missing space in both cases', function() {
            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
        });

        it('should not report with spaces', function() {
            assert(checker.checkString('var x = [ 1 ];').isEmpty());
        });

        it('should not report for nested array', function() {
            assert(checker.checkString('var x = [[ 1 ], [ 2 ]];').isEmpty());
        });

        it('should report anything for empty array', function() {
            assert(checker.checkString('[[]];').isEmpty());
        });
    });

    describe('exceptions', function() {
        it('should not report missing space for parentheses', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['{', '}']
                }
            });

            assert(checker.checkString('var x = [1];').getErrorCount() === 2);
            assert(checker.checkString('var x = [{ a: 1 }];').isEmpty());
        });

        it('should report missing space for the array brackets', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['[', ']']
                }
            });

            assert(checker.checkString('var x = [{}];').getErrorCount() === 2);
            assert(checker.checkString('var x = [[]];').isEmpty());
        });

        it('should not report missing space in both cases', function() {
            checker.configure({
                requireSpacesInsideArrayBrackets: {
                    allExcept: ['(', ')']
                }
            });

            assert(checker.checkString('var x = [{ a: 1 }];').getErrorCount() === 2);
            assert(checker.checkString('var x = [(1)];').isEmpty());
        });
    });

    describe('comments', function() {
        beforeEach(function() {
            checker.configure({ requireSpacesInsideArrayBrackets: 'all' });
        });

        it('should report missing space after comment', function() {
            assert(checker.checkString('var x = [ 1 /*,2*/];').getErrorCount() === 1);
        });

        it('should not report with space after comment', function() {
            assert(checker.checkString('var x = [ 1 /*,2*/ ];').isEmpty());
        });

        it('should report missing space before comment', function() {
            assert(checker.checkString('var x = [/*0,*/ 1 ];').getErrorCount() === 1);
        });

        it('should not report with space before comment', function() {
            assert(checker.checkString('var x = [ /*0,*/ 1 ];').isEmpty());
        });

        it('should report missing space before and after comments', function() {
            assert(checker.checkString('var x = [/*0,*/ 1 /*,2*/];').getErrorCount() === 2);
        });

        it('should not report with space before comment', function() {
            assert(checker.checkString('var x = [ /*0,*/ 1 /*,2*/ ];;').isEmpty());
        });

    });
});
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  entry: {
    playground: "./playground/index.js"
  },
  output: {
    filename: "[name].js",
    path: __dirname + "/static/"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: ["env", "react"]
        }
      }
    ]
  },
  externals: {
    clipboard: 'ClipboardJS',
    codemirror: "CodeMirror",
    react: "React",
    "react-dom": "ReactDOM"
  }
};
<commit_msg>run prettier<commit_after>"use strict";

module.exports = {
  entry: {
    playground: "./playground/index.js"
  },
  output: {
    filename: "[name].js",
    path: __dirname + "/static/"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: ["env", "react"]
        }
      }
    ]
  },
  externals: {
    clipboard: "ClipboardJS",
    codemirror: "CodeMirror",
    react: "React",
    "react-dom": "ReactDOM"
  }
};
<|endoftext|>


<commit_before>var assert = require('assert');
var util = require('./util');
const filesFolder = './';
var path = require('path');
var chai = require('chai');
var assert = chai.assert; // Using Assert style
var expect = chai.expect; // Using Expect style
var should = chai.should(); // Using Should style

require('it-each')({ testPerIteration: true });

var folder = process.env.npm_config_folder || filesFolder;
var mainTemplateFileJSONObject = util.getMainTemplateFile(folder).jsonObject;
var mainTemplateFile = util.getMainTemplateFile(folder).file;
var mainTemplateFileName = "maintemplate.json";
var createUiDefFileJSONObject = util.getCreateUiDefFile(folder).jsonObject;
var createUiDefFile = util.getCreateUiDefFile(folder).file;
var templateFiles = util.getTemplateFiles(folder).files;
var templateFileJSONObjects = util.getTemplateFiles(folder).fileJSONObjects;

console.log('Testing template files...');
templateFiles.forEach(function (file) {
    console.log(file);
});

chai.use(function (_chai, _) {
    _chai.Assertion.addMethod('withMessage', function (msg) {
        _.flag(this, 'message', msg);
    });
});

function getErrorMessage(obj, file, message) {
    return 'json object with \'name\' at line number ' + util.getPosition(obj, file) + ' ' + message;
}

/** Tests for template files in a solution template */
describe('template files - ', () => {

    /** Tests for parameters in template files */
    describe('parameters tests - ', () => {

        var mainTemplateFileContent = JSON.stringify(mainTemplateFileJSONObject).toLowerCase();

        mainTemplateFileJSONObject = JSON.parse(mainTemplateFileContent);

        /** maintemplate.json should have a parameters property */
        it('maintemplate.json should have a "parameters" property', () => {
            mainTemplateFileJSONObject.should.have.property('parameters');
        });

        var currentDir = path.dirname(mainTemplateFile);
        // assert create ui def exists in the above directory
        util.assertCreateUiDefExists(currentDir);

        // get the corresponding create ui def
        var createUiDefJSONObject = util.getCreateUiDefFile(currentDir).jsonObject;

        var createUiDefJSONStr = JSON.stringify(createUiDefJSONObject).toLowerCase();

        createUiDefJSONObject = JSON.parse(createUiDefJSONStr);

        // get output keys in main template
        var outputsInCreateUiDef = Object.keys(createUiDefJSONObject.parameters.outputs);

        var parametersInMainTemplate = Object.keys(mainTemplateFileJSONObject.parameters);
        /** Validate each parameter that does not have a defaultValue in mainTemplate, has a value in outputs */
        it.each(parametersInMainTemplate, 'parameter %s that does not have a defaultValue in file mainTemplate.json, must have a corresponding output in createUiDefinition.json', ['element'], function(element, next){
            if (typeof(mainTemplateFileJSONObject.parameters[element].defaultvalue) === 'undefined') {
                outputsInCreateUiDef.should.withMessage('in file:mainTemplate.json, outputs in createUiDefinition is missing the parameter ' + element).contain(element);
            }
            next();
        });

        /** If securestring, the default value (if it exists) should be null*/
        it('non-null default values must not be provided for secureStrings', () => {
            templateFileJSONObjects.forEach(templateJSONObject => {
                var templateObject = templateJSONObject.value;
                Object.keys(templateObject.parameters).forEach(parameter => {
                    if (templateObject.parameters[parameter].type == 'securestring') {
                        // get default value if one exists
                        var defaultval = templateObject.parameters[parameter].defaultvalue;
                        if (defaultval && defaultval.length > 0) {
                            expect(templateObject.parameters[parameter], 'in file:' + templateJSONObject.filename + ' "' + parameter + '" should not have defaultValue').to.not.have.property('defaultvalue');
                        }
                    }
                });
            });

        });

        /** The location parameter MUST NOT have allowedValues property and if it has defaultValue property, it's value MUST be '[resourceGroup().location]' */
        it('a parameter named "location" must exist and it must have a defaultValue of resourceGroup().location', () => {
            mainTemplateFileJSONObject.should.withMessage('file:mainTemplate.json is missing parameters property').have.property('parameters');
            mainTemplateFileJSONObject.parameters.should.withMessage('file:mainTemplate.json is missing location property in parameters').have.property('location');

            /** The location parameter can have a defaultValue property, and its value must be '[resourceGroup().location]' */
            var location = mainTemplateFileJSONObject.parameters.location;
            if (location.defaultvalue) {
                location.defaultvalue.should.withMessage('in file:mainTemplate.json, the default value of location property MUST be [resourceGroup().location]').be.eql('[resourcegroup().location]');
            }
            location.should.withMessage('in file:mainTemplate.json, location property MUST NOT have allowedValues property').not.have.property('allowedvalues');
        });

        /** Validate each parameter should be used in main template */
        it.each(parametersInMainTemplate, 'parameter %s must be used in file mainTemplate.json', ['element'], function(element, next) {
            var paramString = 'parameters(\'' + element + '\')';
            assert(mainTemplateFileContent.includes(paramString) === true, 'unused parameter "' + element + '" in file mainTemplate.json');
            next();
        });
    });

    describe('resources tests - ', () => {
        templateFileJSONObjects.forEach(templateJSONObject => {
            var templateObject = templateJSONObject.value;
            templateObject.should.have.property('resources');
            var resources = Object.keys(templateObject.resources).map(function (key) {
                return templateObject.resources[key];
            });
            /** Each resource location should be an expression "location": "[*]" or "global" */
            it.each(resources, 'location value of resource %s should be an expression or "global"', ['name'], function (element, next) {
                var message = 'in file:' + templateJSONObject.filename + ' should have location set to an expression';
                if (element.location) {
                    element.location.should.withMessage(getErrorMessage(element, templateJSONObject.filepath, message)).match(/\[.+\]|global/);
                }
                next();
            });
            /** resourceGroup().location should NOT be present anywhere in template, EXCEPT as a defaultValue */
            it.each(templateObject, 'resourceGroup().location must NOT be be used in the template file ' + templateJSONObject.filename + '.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();

                // if this is mainTemplate.json, a defaultValue of resourceGroup().location is OK, so remove it before searching for it
                if (templateJSONObject.filename.toLowerCase() == (folder + '\\maintemplate.json')) {
                    templateFileContent = templateFileContent.replace(/\"defaultvalue\":\s*\"\[resourcegroup\(\)\.location\]\"/, "");
                }

                var locationString = 'resourcegroup().location';
                var message = 'in file:' + templateJSONObject.filename + ' should NOT have location set to resourceGroup().location';
                assert(templateFileContent.includes(locationString) === false, message);
                next();
            });
            /** providers().apiVersions[n] must not be present for all template files. */

            it.each(templateObject, 'apiVersions must NOT be retrieved using providers().apiVersions[n] in the template file ' + templateJSONObject.filename + '. This function is non-deterministic.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();
                var message = 'in file:' + templateJSONObject.filename + ' should NOT have api version determined by providers().';
                assert(templateFileContent.match(/providers\(.*?\)\.apiversions/) === null, message);
                next();

            });
            /** VM Image ref should not contain preview */
            // NOTE: Property names are case sensitive in the test though they are not in ARM - the test will fail if different casing is used in the template

            /** TODO: need to account for use of variables and parameters in the property value
                If the value is a simple variable we can resolve easily
                If the value is a parameter, get the defaultValue
                Note that the variable may be at the imageReference level, not the offer level... that's why we're currently checking
                templateObject.resources[resource].properties.storageProfile.imageReference.toLowerCase();
                instead of
                templateObject.resources[resource].properties.storageProfile.imageReference.offer.toLowerCase();
            */

            it('VM Image ref must not contain "-preview"', () => {
                var templateObject = templateJSONObject.value;
                Object.keys(templateObject.resources).forEach(resource => {
                    var resourceType = templateObject.resources[resource].type.toLowerCase();
                    if (resourceType === 'microsoft.compute/virtualmachines') {
                        console.log('VM');
                        var previewString = "-preview";
                        var offer = JSON.stringify(templateObject.resources[resource].properties.storageprofile.imagereference).toLowerCase();
                        var message = 'in file:' + templateJSONObject.filename + ' VM must NOT use a preview image: ' + offer;
                        assert(offer.includes(previewString) === false, message);
                    }
                    if (resourceType === 'microsoft.compute/virtualmachinescalesets') {
                        console.log('VMSS');
                        var previewString = "-preview";
                        var offer = JSON.stringify(templateObject.resources[resource].properties.virtualmachineprofile.storageprofile.imagereference).toLowerCase();
                        var message = 'in file:' + templateJSONObject.filename + ' VMSS must NOT use a preview image: ' + offer;
                        assert(offer.includes(previewString) === false, message);
                    }
                });
            });
            /** MSI extension must not be used */
            it.each(templateObject, 'ManagedIdentityExtension must not be used ' + templateJSONObject.filename + '. This extension is not necessary to use an MSI and is being deprecated.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();
                var message = 'in file:' + templateJSONObject.filename + ' should NOT use Managed Identity Extension.';
                assert(templateFileContent.match('managedidentityextension') === null, message);
                next();
            });
        });
    });
});
<commit_msg>#5843<commit_after>var assert = require('assert');
var util = require('./util');
const filesFolder = './';
var path = require('path');
var chai = require('chai');
var assert = chai.assert; // Using Assert style
var expect = chai.expect; // Using Expect style
var should = chai.should(); // Using Should style

require('it-each')({ testPerIteration: true });

var folder = process.env.npm_config_folder || filesFolder;
var mainTemplateFileJSONObject = util.getMainTemplateFile(folder).jsonObject;
var mainTemplateFile = util.getMainTemplateFile(folder).file;
var mainTemplateFileName = "maintemplate.json";
var createUiDefFileJSONObject = util.getCreateUiDefFile(folder).jsonObject;
var createUiDefFile = util.getCreateUiDefFile(folder).file;
var templateFiles = util.getTemplateFiles(folder).files;
var templateFileJSONObjects = util.getTemplateFiles(folder).fileJSONObjects;

console.log('Testing template files...');
templateFiles.forEach(function (file) {
    console.log(file);
});

chai.use(function (_chai, _) {
    _chai.Assertion.addMethod('withMessage', function (msg) {
        _.flag(this, 'message', msg);
    });
});

function getErrorMessage(obj, file, message) {
    return 'json object with \'name\' at line number ' + util.getPosition(obj, file) + ' ' + message;
}

/** Tests for template files in a solution template */
describe('template files - ', () => {

    /** Tests for parameters in template files */
    describe('parameters tests - ', () => {

        var mainTemplateFileContent = JSON.stringify(mainTemplateFileJSONObject).toLowerCase();

        mainTemplateFileJSONObject = JSON.parse(mainTemplateFileContent);

        /** maintemplate.json should have a parameters property */
        it('maintemplate.json should have a "parameters" property', () => {
            mainTemplateFileJSONObject.should.have.property('parameters');
        });

        var currentDir = path.dirname(mainTemplateFile);
        // assert create ui def exists in the above directory
        util.assertCreateUiDefExists(currentDir);

        // get the corresponding create ui def
        var createUiDefJSONObject = util.getCreateUiDefFile(currentDir).jsonObject;

        var createUiDefJSONStr = JSON.stringify(createUiDefJSONObject).toLowerCase();

        createUiDefJSONObject = JSON.parse(createUiDefJSONStr);

        // get output keys in main template
        var outputsInCreateUiDef = Object.keys(createUiDefJSONObject.parameters.outputs);

        var parametersInMainTemplate = Object.keys(mainTemplateFileJSONObject.parameters);
        /** Validate each parameter that does not have a defaultValue in mainTemplate, has a value in outputs */
        it.each(parametersInMainTemplate, 'parameter %s that does not have a defaultValue in file mainTemplate.json, must have a corresponding output in createUiDefinition.json', ['element'], function(element, next){
            if (typeof(mainTemplateFileJSONObject.parameters[element].defaultvalue) === 'undefined') {
                outputsInCreateUiDef.should.withMessage('in file:mainTemplate.json, outputs in createUiDefinition is missing the parameter ' + element).contain(element);
            }
            next();
        });

        /** If securestring, the default value (if it exists) should be null*/
        it('non-null default values must not be provided for secureStrings', () => {
            templateFileJSONObjects.forEach(templateJSONObject => {
                var templateObject = templateJSONObject.value;
                Object.keys(templateObject.parameters).forEach(parameter => {
                    if (templateObject.parameters[parameter].type == 'securestring') {
                        // get default value if one exists
                        var defaultval = templateObject.parameters[parameter].defaultvalue;
                        if (defaultval && defaultval.length > 0) {
                            expect(templateObject.parameters[parameter], 'in file:' + templateJSONObject.filename + ' "' + parameter + '" should not have defaultValue').to.not.have.property('defaultvalue');
                        }
                    }
                });
            });

        });

        /** The location parameter MUST NOT have allowedValues property and if it has defaultValue property, it's value MUST be '[resourceGroup().location]' */
        it('a parameter named "location" must exist and it must have a defaultValue of resourceGroup().location', () => {
            mainTemplateFileJSONObject.should.withMessage('file:mainTemplate.json is missing parameters property').have.property('parameters');
            mainTemplateFileJSONObject.parameters.should.withMessage('file:mainTemplate.json is missing location property in parameters').have.property('location');

            /** The location parameter can have a defaultValue property, and its value must be '[resourceGroup().location]' */
            var location = mainTemplateFileJSONObject.parameters.location;
            if (location.defaultvalue) {
                location.defaultvalue.should.withMessage('in file:mainTemplate.json, the default value of location property MUST be [resourceGroup().location]').be.eql('[resourcegroup().location]');
            }
            location.should.withMessage('in file:mainTemplate.json, location property MUST NOT have allowedValues property').not.have.property('allowedvalues');
        });

        /** Validate each parameter should be used in main template */
        it.each(parametersInMainTemplate, 'parameter %s must be used in file mainTemplate.json', ['element'], function(element, next) {
            var paramString = 'parameters(\'' + element + '\')';
            assert(mainTemplateFileContent.includes(paramString) === true, 'unused parameter "' + element + '" in file mainTemplate.json');
            next();
        });
    });

    describe('resources tests - ', () => {
        templateFileJSONObjects.forEach(templateJSONObject => {
            var templateObject = templateJSONObject.value;
            templateObject.should.have.property('resources');
            var resources = Object.keys(templateObject.resources).map(function (key) {
                return templateObject.resources[key];
            });
            /** Each resource location should be an expression "location": "[*]" or "global" */
            it.each(resources, 'location value of resource %s should be an expression or "global"', ['name'], function (element, next) {
                var message = 'in file:' + templateJSONObject.filename + ' should have location set to an expression';
                if (element.location) {
                    element.location.should.withMessage(getErrorMessage(element, templateJSONObject.filepath, message)).match(/\[.+\]|global/);
                }
                next();
            });
            /** resourceGroup().location should NOT be present anywhere in template, EXCEPT as a defaultValue */
            it.each(templateObject, 'resourceGroup().location must NOT be be used in the template file ' + templateJSONObject.filename + '.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();
                var regExp = new RegExp((folder + '.maintemplate.json').toLowerCase());

                // if this is mainTemplate.json, a defaultValue of resourceGroup().location is OK, so remove it before searching for it
                if (regExp.test(templateJSONObject.filename.toLowerCase())) {
                    console.log("debug: edburns: matched");
                    templateFileContent = templateFileContent.replace(/\"defaultvalue\":\s*\"\[resourcegroup\(\)\.location\]\"/, "");
                }

                var locationString = 'resourcegroup().location';
                var message = 'in file:' + templateJSONObject.filename + ' should NOT have location set to resourceGroup().location';
                assert(templateFileContent.includes(locationString) === false, message);
                next();
            });
            /** providers().apiVersions[n] must not be present for all template files. */

            it.each(templateObject, 'apiVersions must NOT be retrieved using providers().apiVersions[n] in the template file ' + templateJSONObject.filename + '. This function is non-deterministic.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();
                var message = 'in file:' + templateJSONObject.filename + ' should NOT have api version determined by providers().';
                assert(templateFileContent.match(/providers\(.*?\)\.apiversions/) === null, message);
                next();

            });
            /** VM Image ref should not contain preview */
            // NOTE: Property names are case sensitive in the test though they are not in ARM - the test will fail if different casing is used in the template

            /** TODO: need to account for use of variables and parameters in the property value
                If the value is a simple variable we can resolve easily
                If the value is a parameter, get the defaultValue
                Note that the variable may be at the imageReference level, not the offer level... that's why we're currently checking
                templateObject.resources[resource].properties.storageProfile.imageReference.toLowerCase();
                instead of
                templateObject.resources[resource].properties.storageProfile.imageReference.offer.toLowerCase();
            */

            it('VM Image ref must not contain "-preview"', () => {
                var templateObject = templateJSONObject.value;
                Object.keys(templateObject.resources).forEach(resource => {
                    var resourceType = templateObject.resources[resource].type.toLowerCase();
                    if (resourceType === 'microsoft.compute/virtualmachines') {
                        console.log('VM');
                        var previewString = "-preview";
                        var offer = JSON.stringify(templateObject.resources[resource].properties.storageprofile.imagereference).toLowerCase();
                        var message = 'in file:' + templateJSONObject.filename + ' VM must NOT use a preview image: ' + offer;
                        assert(offer.includes(previewString) === false, message);
                    }
                    if (resourceType === 'microsoft.compute/virtualmachinescalesets') {
                        console.log('VMSS');
                        var previewString = "-preview";
                        var offer = JSON.stringify(templateObject.resources[resource].properties.virtualmachineprofile.storageprofile.imagereference).toLowerCase();
                        var message = 'in file:' + templateJSONObject.filename + ' VMSS must NOT use a preview image: ' + offer;
                        assert(offer.includes(previewString) === false, message);
                    }
                });
            });
            /** MSI extension must not be used */
            it.each(templateObject, 'ManagedIdentityExtension must not be used ' + templateJSONObject.filename + '. This extension is not necessary to use an MSI and is being deprecated.', function (element, next) {
                var templateFileContent = JSON.stringify(templateObject).toLowerCase();
                var message = 'in file:' + templateJSONObject.filename + ' should NOT use Managed Identity Extension.';
                assert(templateFileContent.match('managedidentityextension') === null, message);
                next();
            });
        });
    });
});
<|endoftext|>