<commit_before>({
  appDir: '.',
  baseUrl: '.',
  dir: './build',
  skipDirOptimize: false, //TODO: change to false if you have a pretty comprehensive build modules defined in this file, and want to speed up the build - only files recuirsively referenced in build modules will be optimized
  generateSourceMaps: false, //TODO: change to true if you need source maps generated for easier debugging in production
  mainConfigFile: 'common.js',
  optimize: 'uglify2',
  optimizeCss: 'standard',
  pragmasOnSave: {
    excludeRequireCss: false //TODO: if dynamic CSS loading in production will not happen (e.g. load from a CDN), change this to true
  },
  modules: [
    {
      name: 'common',
      include: [
        'app/shared/root-bindings',
        'framework/router',
        'framework/page'
        /* TODO: add other common modules */
      ]
    },
    {
      name: 'app/error/error',
      exclude: ['common']
    },
    {
      name: 'app/files/files',
      exclude: ['common']
    },
    {
      name: 'app/files/dependencies/dependencies',
      exclude: ['common']
    },
    {
      name: 'app/home/home',
      exclude: ['common']
    },
    {
      name: 'app/resources/resources',
      exclude: ['common']
    }
    /* TODO: add other page modules */
  ],
  paths: {
    materialize: 'empty:'
    /* TODO: add any modules you don't want r.js to optimize here with path set to 'empty:',
             mainly for third party modules that would fail r.js optimization */
  }
})
<commit_msg>build.js: add more common modules; add components to build modules.<commit_after>({
  appDir: '.',
  baseUrl: '.',
  dir: './build',
  skipDirOptimize: false, //TODO: change to false if you have a pretty comprehensive build modules defined in this file, and want to speed up the build - only files recuirsively referenced in build modules will be optimized
  generateSourceMaps: false, //TODO: change to true if you need source maps generated for easier debugging in production
  mainConfigFile: 'common.js',
  optimize: 'uglify2',
  optimizeCss: 'standard',
  pragmasOnSave: {
    excludeRequireCss: false //TODO: if dynamic CSS loading in production will not happen (e.g. load from a CDN), change this to true
  },
  modules: [
    {
      name: 'common',
      include: [
        'app/shared/root-bindings',
        'framework/router',
        'framework/page',
        'text',
        'css',
        'jsface'
        /* TODO: add other common modules */
      ]
    },
    {
      name: 'app/error/error',
      exclude: ['common']
    },
    {
      name: 'app/files/files',
      exclude: ['common']
    },
    {
      name: 'app/files/dependencies/dependencies',
      exclude: ['common']
    },
    {
      name: 'app/home/home',
      exclude: ['common']
    },
    {
      name: 'app/resources/resources',
      exclude: ['common']
    },
    {
      name: 'component/file-display/file-display',
      exclude: ['common']
    },
    {
      name: 'component/page-source-display/page-source-display',
      exclude: ['common']
    }
    /* TODO: add other page modules and component modules */
  ],
  paths: {
    materialize: 'empty:'
    /* TODO: add any modules you don't want r.js to optimize here with path set to 'empty:',
             mainly for third party modules that would fail r.js optimization */
  }
})
<|endoftext|>


<commit_before>// https://github.com/less/less-plugin-clean-css
// lessc --clean-css=" --advanced" monitoring.less monitoring.css

//r.js -o build.js
//node node_modules/requirejs/bin/r.js -o build.js
//
// as example t ouse rjs in node
// https://gist.githubusercontent.com/millermedeiros/2640928/raw/dba1bbc4476dace769cdad7bc063e9bcabc453d8/build.js
var _requirejs = require('requirejs');
var fs = require('fs-extra');
var ncp = require('ncp');

function mixIn(target, objects){
    var i = 1,
        key, cur;
    while(cur = arguments[i++]){
        for(key in cur){
            if(Object.prototype.hasOwnProperty.call(cur, key)){
                target[key] = cur[key];
            }
        }
    }
    return target;
}

function rjs(opts, callback){
    var buildConfig = mixIn( opts, BASE_JS_SETTINGS);
    console.info('buildConfig:',buildConfig.out)
    _requirejs.optimize( buildConfig, function(){
        console.info('build completed for:',buildConfig.out)
        _nOptimizedModules += 1;
        if (typeof callback === 'function') {
            callback.apply(null, Array.prototype.slice.call(arguments));
        }
    });
}

var libDir =  '';
if (fs.existsSync('node_modules')) {
    libDir += 'node_modules/';
}

var BASE_JS_SETTINGS = {
	logLevel: 0,
	baseUrl: './',

	paths:{
		knockout : require.resolve('knockout').replace(/\.js/,''),

        css :	    require.resolve('require-css/css.min.js').replace(/\.js/,''),
		'css-builder' :	    require.resolve('require-css/css-builder.js').replace(/\.js/,''),
        normalize :	    require.resolve('require-css/normalize.js').replace(/\.js/,''),

        page: require.resolve('page/page.js').replace(/\.js/,''),
        'page/query': require.resolve('qs/dist/qs.js').replace(/\.js/,''),

        'HTML5-History-API': require.resolve('html5-history-api/history').replace(/\.js/,''),

		less : 		'magpie/dom/less'
	},

    // fileExclusionRegExp:	/(^\.|lib|build.js|server|page|.*\.md)/,

	findNestedDependencies: true,

	mainConfigFile: 'magpie/config.js',

    // optimize: "none",
	optimize: "uglify2",
	generateSourceMaps: true,

	preserveLicenseComments: false,

    uglify2: {
		// outSourceMap: 'dist/magpie.js.map',
        output: {
			// indent_start  : 0,     // start indentation on every line (only when `beautify`)
			// indent_level  : 4,     // indentation level (only when `beautify`)
			// quote_keys    : false, // quote all keys in object literals?
			// space_colon   : true,  // add a space after colon signs?
			// ascii_only    : false, // output ASCII-safe? (encodes Unicode characters as ASCII)
			// inline_script : false, // escape "</script"?
			// width         : 80,    // informative maximum line width (for beautified output)
			// max_line_len  : 32000, // maximum line length (for non-beautified output)
			// ie_proof      : true,  // output IE-safe code?
			// beautify      : true, // beautify output?
			// source_map    : null,  // output a source map
			// bracketize    : false, // use brackets every time?
			// comments      : false, // output comments?
			// semicolons    : true,  // use semicolons to separate statements? (otherwise, newlines)
        },
		compress:{
			// sequences     : true,  // join consecutive statemets with the “comma operator”
			// properties    : true,  // optimize property access: a["foo"] → a.foo
			// dead_code     : true,  // discard unreachable code
			// drop_debugger : true,  // discard “debugger” statements
			// unsafe        : false, // some unsafe optimizations (see below)
			// conditionals  : true,  // optimize if-s and conditional expressions
			// comparisons   : true,  // optimize comparisons
			// evaluate      : true,  // evaluate constant expressions
			// booleans      : true,  // optimize boolean expressions
			// loops         : true,  // optimize loops
			// unused        : true,  // drop unused variables/functions
			// hoist_funs    : true,  // hoist function declarations
			// hoist_vars    : false, // hoist variable declarations
			// if_return     : true,  // optimize if-s followed by return/continue
			// join_vars     : true,  // join var declarations
			// cascade       : true,  // try to cascade `right` into `left` in sequences
			// side_effects  : true,  // drop side-effect-free statements
			// warnings      : true,  // warn about potentially dangerous optimizations/code
			//
			// This is a feature you can use in order to conditionally drop code. For example if you pass:
			// global_defs: {
			//     DEBUG: false
			// }
			// the compressor will assume that's a constant defintion and will discard code like this as being unreachable:
			//
			// if (DEBUG) {
			//     ...
			// }
			// This is useful in order to discard stuff that you need only in the development version from production builds.
		}
        // warnings: true,
        // mangle: false  //reduce names of local variables and functions usually to single-letters
    },
}

// BASE_JS_SETTINGS.paths

var MagpieModules = {
        Core: [
            'magpie',
            'magpie/crypt/base64',
            'magpie/dom/grid',
            'magpie/dom/inject',
            'magpie/dom/less',
            'magpie/dom/mediaQueries',
            "magpie/html5/customElement",
            'magpie/html5/widget/select',
            "magpie/html5/router",
            'magpie/log',
            'magpie/resource/properties',
            "magpie/util/config",
            "magpie/util/idgenerator"
        ],
        Extend: [
            //
            // bundles that extends 3th party library functions:
            //
            'magpie/extend/knockout',
        ],

        VendorMap:{
            'magpie/extend/knockout':[
                'knockout'
            ],
            "magpie/html5/router":[
                'page',
                'page/query',
                'HTML5-History-API'
            ]
        }

}
MagpieModules.vendors = [];

for (var module in MagpieModules.VendorMap){
    MagpieModules.vendors = MagpieModules.vendors.concat(MagpieModules.VendorMap[module]);
}

fs.removeSync('dist');

rjs({
    out: "dist/magpie.min.js",
	include: MagpieModules.Core,
	exclude: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.min.js",
	include: MagpieModules.Core.concat(MagpieModules.Extend),
	exclude: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.vendors.min.js",
	include: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.include.vendors.min.js",
	include: MagpieModules.Core.concat(MagpieModules.Extend)
});

for (var module in MagpieModules.VendorMap){
    rjs({
        out: "dist/" + module.replace(/\//g,'.') +".vendor.min.js",
    	include: MagpieModules.VendorMap[module]
    });
}
fs.removeSync('dist/magpie');
fs.mkdirsSync('dist/magpie/html5/customElement/provider');

ncp('magpie/html5/customElement/provider', 'dist/magpie/html5/customElement/provider',function (err) {
 if (err) {
   return console.error(err);
 }
 console.log('copy magpie/html5/customElement/provider to "dist" folder done');
});

console.log('put requirejs in lib folder')
if (!fs.existsSync('lib/requirejs')) {
    fs.removeSync('lib/requirejs');
}
fs.mkdirsSync('lib/requirejs');
ncp(''+require.resolve('requirejs/require.js'), 'lib/requirejs/require.js', function(err){

})
<commit_msg>!clean<commit_after>var _requirejs = require('requirejs');
var fs = require('fs-extra');
var ncp = require('ncp');

function mixIn(target, objects){
    var i = 1,
        key, cur;
    while(cur = arguments[i++]){
        for(key in cur){
            if(Object.prototype.hasOwnProperty.call(cur, key)){
                target[key] = cur[key];
            }
        }
    }
    return target;
}

function rjs(opts, callback){
    var buildConfig = mixIn( opts, BASE_JS_SETTINGS);
    console.info('buildConfig:',buildConfig.out)
    _requirejs.optimize( buildConfig, function(){
        console.info('build completed for:',buildConfig.out)
        _nOptimizedModules += 1;
        if (typeof callback === 'function') {
            callback.apply(null, Array.prototype.slice.call(arguments));
        }
    });
}

var libDir =  '';
if (fs.existsSync('node_modules')) {
    libDir += 'node_modules/';
}

var BASE_JS_SETTINGS = {
	logLevel: 0,
	baseUrl: './',

	paths:{
		knockout : require.resolve('knockout').replace(/\.js/,''),

        css :	    require.resolve('require-css/css.min.js').replace(/\.js/,''),
		'css-builder' :	    require.resolve('require-css/css-builder.js').replace(/\.js/,''),
        normalize :	    require.resolve('require-css/normalize.js').replace(/\.js/,''),

        page: require.resolve('page/page.js').replace(/\.js/,''),
        'page/query': require.resolve('qs/dist/qs.js').replace(/\.js/,''),

        'HTML5-History-API': require.resolve('html5-history-api/history').replace(/\.js/,''),

		less : 		'magpie/dom/less'
	},

    // fileExclusionRegExp:	/(^\.|lib|build.js|server|page|.*\.md)/,

	findNestedDependencies: true,

	mainConfigFile: 'magpie/config.js',

    // optimize: "none",
	optimize: "uglify2",
	generateSourceMaps: true,

	preserveLicenseComments: false,

    uglify2: {
		// outSourceMap: 'dist/magpie.js.map',
        output: {
			// indent_start  : 0,     // start indentation on every line (only when `beautify`)
			// indent_level  : 4,     // indentation level (only when `beautify`)
			// quote_keys    : false, // quote all keys in object literals?
			// space_colon   : true,  // add a space after colon signs?
			// ascii_only    : false, // output ASCII-safe? (encodes Unicode characters as ASCII)
			// inline_script : false, // escape "</script"?
			// width         : 80,    // informative maximum line width (for beautified output)
			// max_line_len  : 32000, // maximum line length (for non-beautified output)
			// ie_proof      : true,  // output IE-safe code?
			// beautify      : true, // beautify output?
			// source_map    : null,  // output a source map
			// bracketize    : false, // use brackets every time?
			// comments      : false, // output comments?
			// semicolons    : true,  // use semicolons to separate statements? (otherwise, newlines)
        },
		compress:{
			// sequences     : true,  // join consecutive statemets with the “comma operator”
			// properties    : true,  // optimize property access: a["foo"] → a.foo
			// dead_code     : true,  // discard unreachable code
			// drop_debugger : true,  // discard “debugger” statements
			// unsafe        : false, // some unsafe optimizations (see below)
			// conditionals  : true,  // optimize if-s and conditional expressions
			// comparisons   : true,  // optimize comparisons
			// evaluate      : true,  // evaluate constant expressions
			// booleans      : true,  // optimize boolean expressions
			// loops         : true,  // optimize loops
			// unused        : true,  // drop unused variables/functions
			// hoist_funs    : true,  // hoist function declarations
			// hoist_vars    : false, // hoist variable declarations
			// if_return     : true,  // optimize if-s followed by return/continue
			// join_vars     : true,  // join var declarations
			// cascade       : true,  // try to cascade `right` into `left` in sequences
			// side_effects  : true,  // drop side-effect-free statements
			// warnings      : true,  // warn about potentially dangerous optimizations/code
			//
			// This is a feature you can use in order to conditionally drop code. For example if you pass:
			// global_defs: {
			//     DEBUG: false
			// }
			// the compressor will assume that's a constant defintion and will discard code like this as being unreachable:
			//
			// if (DEBUG) {
			//     ...
			// }
			// This is useful in order to discard stuff that you need only in the development version from production builds.
		}
        // warnings: true,
        // mangle: false  //reduce names of local variables and functions usually to single-letters
    },
}

// BASE_JS_SETTINGS.paths

var MagpieModules = {
        Core: [
            'magpie',
            'magpie/crypt/base64',
            'magpie/dom/grid',
            'magpie/dom/inject',
            'magpie/dom/less',
            'magpie/dom/mediaQueries',
            "magpie/html5/customElement",
            'magpie/html5/widget/select',
            "magpie/html5/router",
            'magpie/log',
            'magpie/resource/properties',
            "magpie/util/config",
            "magpie/util/idgenerator"
        ],
        Extend: [
            //
            // bundles that extends 3th party library functions:
            //
            'magpie/extend/knockout',
        ],

        VendorMap:{
            'magpie/extend/knockout':[
                'knockout'
            ],
            "magpie/html5/router":[
                'page',
                'page/query',
                'HTML5-History-API'
            ]
        }

}
MagpieModules.vendors = [];

for (var module in MagpieModules.VendorMap){
    MagpieModules.vendors = MagpieModules.vendors.concat(MagpieModules.VendorMap[module]);
}

fs.removeSync('dist');

rjs({
    out: "dist/magpie.min.js",
	include: MagpieModules.Core,
	exclude: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.min.js",
	include: MagpieModules.Core.concat(MagpieModules.Extend),
	exclude: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.vendors.min.js",
	include: MagpieModules.vendors
});

rjs({
    out: "dist/magpie.full.include.vendors.min.js",
	include: MagpieModules.Core.concat(MagpieModules.Extend)
});

for (var module in MagpieModules.VendorMap){
    rjs({
        out: "dist/" + module.replace(/\//g,'.') +".vendor.min.js",
    	include: MagpieModules.VendorMap[module]
    });
}
fs.removeSync('dist/magpie');
fs.mkdirsSync('dist/magpie/html5/customElement/provider');

ncp('magpie/html5/customElement/provider', 'dist/magpie/html5/customElement/provider',function (err) {
 if (err) {
   return console.error(err);
 }
 console.log('copy magpie/html5/customElement/provider to "dist" folder done');
});

console.log('put requirejs in lib folder')
if (!fs.existsSync('lib/requirejs')) {
    fs.removeSync('lib/requirejs');
}
fs.mkdirsSync('lib/requirejs');
ncp(''+require.resolve('requirejs/require.js'), 'lib/requirejs/require.js', function(err){

})
<|endoftext|>


<commit_before>'use strict';

let exec = require('child_process').exec;
let path = require('path');

let cmdLine = path.join('.', 'node_modules', '.bin', 'webpack');
cmdLine += ' -p --bail --progress --colors';

let env = !!process.argv[2] ? process.argv[2].toLowerCase() : 'production';

if (process.platform === 'win32') {
  cmdLine = 'set NODE_ENV=' + env + '&& ' + cmdLine;
} else {
  cmdLine = 'NODE_ENV=' + env + ' ' + cmdLine;
}

let command = exec(cmdLine, error => process.exit(error === null ? 0 : error.code));

command.stdout.on('data', data => process.stdout.write(data));
command.stderr.on('data', data => process.stderr.write(data));
command.on('error', err => process.stderr.write(err));
<commit_msg>build.js passes ESLint checks<commit_after>/* eslint strict: "off" */
'use strict';

const exec = require('child_process').exec;
const path = require('path');

let cmdLine = path.join('.', 'node_modules', '.bin', 'webpack');
cmdLine += ' -p --bail --progress --colors';

const env = !!process.argv[2] ? process.argv[2].toLowerCase() : 'production';

if (process.platform === 'win32') {
  cmdLine = `set NODE_ENV=${env}&& ${cmdLine}`;
} else {
  cmdLine = `NODE_ENV=${env} ${cmdLine}`;
}

const command = exec(cmdLine, error => process.exit(error === null ? 0 : error.code));

command.stdout.on('data', data => process.stdout.write(data));
command.stderr.on('data', data => process.stderr.write(data));
command.on('error', err => process.stderr.write(err));
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require('fs-extra')
const path = require('path')
const spawnSync = require('child_process').spawnSync
const glob = require('glob')
const asyncMod = require('async')
const ramda = require('ramda')

const program = require('commander')

// Make the "build" directory to hold build artifacts
try {
  fs.mkdirSync('build')
} catch (err) {
  if (err.code !== 'EEXIST') throw err
}
program
  .option('-c, --no-compile', 'Do not compile Emscripten modules')
  .option('-s, --no-copy-sources', 'Do not copy JavaScript sources')
  .option('-p, --no-build-pipelines', 'Do not build the test pipelines')
  .parse(process.argv)

if (program.compile) {
  // Make the "build" directory to hold build artifacts
  try {
    fs.mkdirSync('build')
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }

  const dockerVersion = spawnSync('docker', ['--version'], {
    env: process.env,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
  })
  if (dockerVersion.status !== 0) {
    console.error("Could not run the 'docker' command.")
    console.error('This package requires Docker to build.')
    console.error('')
    console.error('Please find installation instructions at:')
    console.error('')
    console.error('  https://docs.docker.com/install/')
    console.error('')
    process.exit(dockerVersion.status)
  }

  // Ensure we have the 'dockcross' Docker build environment driver script
  const dockcross = path.join('build', 'dockcross')
  try {
    fs.statSync(dockcross)
  } catch (err) {
    if (err.code === 'ENOENT') {
      const output = fs.openSync(dockcross, 'w')
      const dockerCall = spawnSync('docker', ['run', '--rm', 'insighttoolkit/itk-js-base:latest'], {
        env: process.env,
        stdio: [ 'ignore', output, null ]
      })
      if (dockerCall.status !== 0) {
        process.exit(dockerCall.status)
      }
      fs.closeSync(output)
      fs.chmodSync(dockcross, '755')
    } else {
      throw err
    }
  }

  // Perform initial CMake configuration if required
  try {
    fs.statSync(path.join('build', 'build.ninja'))
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('Running CMake configuration...')
      const cmakeCall = spawnSync(dockcross, ['cmake', '-DRapidJSON_INCLUDE_DIR=/rapidjson/include', '-DCMAKE_BUILD_TYPE=Release', '-Bbuild', '-H.', '-GNinja', '-DITK_DIR=/ITK-build', '-DBUILD_ITK_JS_IO_MODULES=ON'], {
        env: process.env,
        stdio: 'inherit'
      })
      if (cmakeCall.status !== 0) {
        process.exit(cmakeCall.status)
      }
    } else {
      throw err
    }
  }

  // Build the Emscripten mobules with ninja
  console.log('\nRunning ninja...')
  const ninjaCall = spawnSync(dockcross, ['ninja', '-j8', '-Cbuild'], {
    env: process.env,
    stdio: 'inherit'
  })
  if (ninjaCall.status !== 0) {
    process.exit(ninjaCall.status)
  }
  console.log('')
} // program.compile

if (program.copySources) {
  try {
    fs.mkdirSync('dist')
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'ImageIOs'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'MeshIOs'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'WebWorkers'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  let imageIOFiles = glob.sync(path.join('build', 'ImageIOs', '*.js'))
  const copyImageIOModules = function (imageIOFile, callback) {
    let io = path.basename(imageIOFile)
    let output = path.join('dist', 'ImageIOs', io)
    fs.copySync(imageIOFile, output)
    callback(null, io)
  }
  const buildImageIOsParallel = function (callback) {
    console.log('Copying ImageIO modules...')
    const result = asyncMod.map(imageIOFiles, copyImageIOModules)
    callback(null, result)
  }
  let meshIOFiles = glob.sync(path.join('build', 'MeshIOs', '*.js'))
  const copyMeshIOModules = function (meshIOFile, callback) {
    let io = path.basename(meshIOFile)
    let output = path.join('dist', 'MeshIOs', io)
    fs.copySync(meshIOFile, output)
    callback(null, io)
  }
  const buildMeshIOsParallel = function (callback) {
    console.log('Copying MeshIO modules...')
    const result = asyncMod.map(meshIOFiles, copyMeshIOModules)
    callback(null, result)
  }

  const browserify = require('browserify')
  const browserifyBuild = ramda.curry(function (uglify, outputDir, es6File, callback) {
    let basename = path.basename(es6File)
    let output = path.join(outputDir, basename)
    const bundler = browserify(es6File)
    if (uglify) {
      bundler.transform({ global: true }, 'uglifyify')
      bundler
        .transform('babelify', { presets: ['@babel/preset-env'] })
        .bundle()
        .pipe(fs.createWriteStream(output))
    } else {
      bundler
        .transform('babelify', { presets: ['@babel/preset-env'] })
        .bundle()
        .pipe(fs.createWriteStream(output))
    }
    callback(null, basename)
  })
  const browserifyWebWorkerBuildParallel = function (callback) {
    console.log('Converting WebWorker sources...')
    const es6Files = glob.sync(path.join('src', 'WebWorkers', '*.js'))
    const outputDir = path.join('dist', 'WebWorkers')
    const builder = browserifyBuild(true, outputDir)
    const result = asyncMod.map(es6Files, builder)
    callback(null, result)
  }

  const babelOptions = {
    presets: [
      ['@babel/preset-env', { 'modules': false }]
    ]
  }
  const babel = require('@babel/core')
  const babelBuild = ramda.curry(function (outputDir, es6File, callback) {
    let basename = path.basename(es6File)
    let output = path.join(outputDir, basename)
    babel.transformFile(es6File, babelOptions, function (err, result) {
      if (err) {
        console.error(err)
        process.exit(1)
      }
      const outputFD = fs.openSync(output, 'w')
      fs.writeSync(outputFD, result.code)
      fs.closeSync(outputFD)
    })
    callback(null, basename)
  })
  const babelBuildParallel = function (callback) {
    console.log('Converting main sources...')
    const es6Files = glob.sync(path.join('src', '*.js'))
    const outputDir = 'dist'
    const builder = babelBuild(outputDir)
    const result = asyncMod.map(es6Files, builder)
    callback(null, result)
  }

  asyncMod.parallel([
    buildImageIOsParallel,
    buildMeshIOsParallel,
    babelBuildParallel,
    browserifyWebWorkerBuildParallel
  ])
} // program.copySources

if (program.buildPipelines) {
  const buildPipeline = (pipelinePath) => {
    console.log('Building ' + pipelinePath + ' ...')
    const buildPipelineCall = spawnSync(path.join(__dirname, 'src', 'itk-js-cli.js'), ['build', pipelinePath], {
      env: process.env,
      stdio: 'inherit'
    })
    if (buildPipelineCall.status !== 0) {
      process.exit(buildPipelineCall.status)
    }
    const pipelineFiles = glob.sync(path.join(pipelinePath, 'web-build', '*.js'))
    pipelineFiles.forEach((file) => {
      let filename = path.basename(file)
      let output = path.join(__dirname, 'dist', 'Pipelines', filename)
      fs.copySync(file, output)
    })
  }

  const pipelines = [
    path.join(__dirname, 'test', 'StdoutStderrPipeline'),
    path.join(__dirname, 'test', 'BinShrinkPipeline'),
    path.join(__dirname, 'test', 'InputOutputFilesPipeline')
  ]
  try {
    fs.mkdirSync(path.join(__dirname, 'dist', 'Pipelines'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  asyncMod.map(pipelines, buildPipeline)
} // progrem
<commit_msg>feat(build.js): Add --debug flag to build Emscripten modules in debug<commit_after>#!/usr/bin/env node

const fs = require('fs-extra')
const path = require('path')
const spawnSync = require('child_process').spawnSync
const glob = require('glob')
const asyncMod = require('async')
const ramda = require('ramda')

const program = require('commander')

// Make the "build" directory to hold build artifacts
try {
  fs.mkdirSync('build')
} catch (err) {
  if (err.code !== 'EEXIST') throw err
}
program
  .option('-c, --no-compile', 'Do not compile Emscripten modules')
  .option('-s, --no-copy-sources', 'Do not copy JavaScript sources')
  .option('-p, --no-build-pipelines', 'Do not build the test pipelines')
  .option('-d, --debug', 'Create a debug build of the Emscripten modules')
  .parse(process.argv)

if (program.compile) {
  // Make the "build" directory to hold build artifacts
  try {
    fs.mkdirSync('build')
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }

  const dockerVersion = spawnSync('docker', ['--version'], {
    env: process.env,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
  })
  if (dockerVersion.status !== 0) {
    console.error("Could not run the 'docker' command.")
    console.error('This package requires Docker to build.')
    console.error('')
    console.error('Please find installation instructions at:')
    console.error('')
    console.error('  https://docs.docker.com/install/')
    console.error('')
    process.exit(dockerVersion.status)
  }

  // Ensure we have the 'dockcross' Docker build environment driver script
  const dockcross = path.join('build', 'dockcross')
  try {
    fs.statSync(dockcross)
  } catch (err) {
    if (err.code === 'ENOENT') {
      const output = fs.openSync(dockcross, 'w')
      const dockerCall = spawnSync('docker', ['run', '--rm', 'insighttoolkit/itk-js-base:latest'], {
        env: process.env,
        stdio: [ 'ignore', output, null ]
      })
      if (dockerCall.status !== 0) {
        process.exit(dockerCall.status)
      }
      fs.closeSync(output)
      fs.chmodSync(dockcross, '755')
    } else {
      throw err
    }
  }

  // Perform initial CMake configuration if required
  try {
    fs.statSync(path.join('build', 'build.ninja'))
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.log('Running CMake configuration...')
      let buildType = '-DCMAKE_BUILD_TYPE:STRING=Release'
      if (program.debug) {
        buildType = '-DCMAKE_BUILD_TYPE:STRING=Debug'
      }
      const cmakeCall = spawnSync(dockcross, ['cmake', '-DRapidJSON_INCLUDE_DIR=/rapidjson/include', buildType, '-Bbuild', '-H.', '-GNinja', '-DITK_DIR=/ITK-build', '-DBUILD_ITK_JS_IO_MODULES=ON'], {
        env: process.env,
        stdio: 'inherit'
      })
      if (cmakeCall.status !== 0) {
        process.exit(cmakeCall.status)
      }
    } else {
      throw err
    }
  }

  // Build the Emscripten mobules with ninja
  console.log('\nRunning ninja...')
  const ninjaCall = spawnSync(dockcross, ['ninja', '-j8', '-Cbuild'], {
    env: process.env,
    stdio: 'inherit'
  })
  if (ninjaCall.status !== 0) {
    process.exit(ninjaCall.status)
  }
  console.log('')
} // program.compile

if (program.copySources) {
  try {
    fs.mkdirSync('dist')
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'ImageIOs'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'MeshIOs'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  try {
    fs.mkdirSync(path.join('dist', 'WebWorkers'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  let imageIOFiles = glob.sync(path.join('build', 'ImageIOs', '*.js'))
  const copyImageIOModules = function (imageIOFile, callback) {
    let io = path.basename(imageIOFile)
    let output = path.join('dist', 'ImageIOs', io)
    fs.copySync(imageIOFile, output)
    callback(null, io)
  }
  const buildImageIOsParallel = function (callback) {
    console.log('Copying ImageIO modules...')
    const result = asyncMod.map(imageIOFiles, copyImageIOModules)
    callback(null, result)
  }
  let meshIOFiles = glob.sync(path.join('build', 'MeshIOs', '*.js'))
  const copyMeshIOModules = function (meshIOFile, callback) {
    let io = path.basename(meshIOFile)
    let output = path.join('dist', 'MeshIOs', io)
    fs.copySync(meshIOFile, output)
    callback(null, io)
  }
  const buildMeshIOsParallel = function (callback) {
    console.log('Copying MeshIO modules...')
    const result = asyncMod.map(meshIOFiles, copyMeshIOModules)
    callback(null, result)
  }

  const browserify = require('browserify')
  const browserifyBuild = ramda.curry(function (uglify, outputDir, es6File, callback) {
    let basename = path.basename(es6File)
    let output = path.join(outputDir, basename)
    const bundler = browserify(es6File)
    if (uglify) {
      bundler.transform({ global: true }, 'uglifyify')
      bundler
        .transform('babelify', { presets: ['@babel/preset-env'] })
        .bundle()
        .pipe(fs.createWriteStream(output))
    } else {
      bundler
        .transform('babelify', { presets: ['@babel/preset-env'] })
        .bundle()
        .pipe(fs.createWriteStream(output))
    }
    callback(null, basename)
  })
  const browserifyWebWorkerBuildParallel = function (callback) {
    console.log('Converting WebWorker sources...')
    const es6Files = glob.sync(path.join('src', 'WebWorkers', '*.js'))
    const outputDir = path.join('dist', 'WebWorkers')
    const builder = browserifyBuild(true, outputDir)
    const result = asyncMod.map(es6Files, builder)
    callback(null, result)
  }

  const babelOptions = {
    presets: [
      ['@babel/preset-env', { 'modules': false }]
    ]
  }
  const babel = require('@babel/core')
  const babelBuild = ramda.curry(function (outputDir, es6File, callback) {
    let basename = path.basename(es6File)
    let output = path.join(outputDir, basename)
    babel.transformFile(es6File, babelOptions, function (err, result) {
      if (err) {
        console.error(err)
        process.exit(1)
      }
      const outputFD = fs.openSync(output, 'w')
      fs.writeSync(outputFD, result.code)
      fs.closeSync(outputFD)
    })
    callback(null, basename)
  })
  const babelBuildParallel = function (callback) {
    console.log('Converting main sources...')
    const es6Files = glob.sync(path.join('src', '*.js'))
    const outputDir = 'dist'
    const builder = babelBuild(outputDir)
    const result = asyncMod.map(es6Files, builder)
    callback(null, result)
  }

  asyncMod.parallel([
    buildImageIOsParallel,
    buildMeshIOsParallel,
    babelBuildParallel,
    browserifyWebWorkerBuildParallel
  ])
} // program.copySources

if (program.buildPipelines) {
  const buildPipeline = (pipelinePath) => {
    console.log('Building ' + pipelinePath + ' ...')
    let debugFlags = []
    if (program.debug) {
      debugFlags = ['-DCMAKE_BUILD_TYPE:STRING=Debug']
    }
    const buildPipelineCall = spawnSync(path.join(__dirname, 'src', 'itk-js-cli.js'), ['build', pipelinePath, '--'].concat(debugFlags), {
      env: process.env,
      stdio: 'inherit'
    })
    if (buildPipelineCall.status !== 0) {
      process.exit(buildPipelineCall.status)
    }
    const pipelineFiles = glob.sync(path.join(pipelinePath, 'web-build', '*.js'))
    pipelineFiles.forEach((file) => {
      let filename = path.basename(file)
      let output = path.join(__dirname, 'dist', 'Pipelines', filename)
      fs.copySync(file, output)
    })
  }

  const pipelines = [
    path.join(__dirname, 'test', 'StdoutStderrPipeline'),
    path.join(__dirname, 'test', 'BinShrinkPipeline'),
    path.join(__dirname, 'test', 'InputOutputFilesPipeline')
  ]
  try {
    fs.mkdirSync(path.join(__dirname, 'dist', 'Pipelines'))
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
  asyncMod.map(pipelines, buildPipeline)
} // progrem
<|endoftext|>


<commit_before><commit_msg>add 'prefixes' option<commit_after><|endoftext|>


<commit_before>var TVMaze = (function tvMaze() {
	'use strict';

	var rootURL = "http://api.tvmaze.com";

	function getJSON(url) {
		return new Promise(function(resolve, reject){
			var req = new XMLHttpRequest();
			req.open("GET", url);
			req.responseType = 'json';
			req.onload = function() {
				if (req.status == 200) {
					resolve(req.response);
				}
				else {
					reject(Error(req.statusText));
				}
			};

			req.onerror = function() {
				reject(Error("Network Error"));
			};

			req.send();
		});
	}

	function showSearch(query) {
		return getJSON(rootURL + "/search/shows?q=" + query);
	}

	function singleSearch(query) {
		return getJSON(rootURL + "/singlesearch/shows?q=" + query);
	}

	function showLookup(id, option) {
		return getJSON(rootURL + "/lookup/shows?" + option + "=" + id);
	}

	function peopleSearch(query) {
		return getJSON(rootURL + "/search/people?q=" + query);
	}

	function schedule(countryCode, date){
		var schedURL = "/schedule";
		if(countryCode && date) {
			schedURL += "?country=" + countryCode + "&date=" + date;
		}
		else if (countryCode && !date) {
			schedURL += "?country=" + countryCode;
		}
		else if (!countryCode && date) {
			schedURL += "?date=" + date;
		}

		return getJSON(rootURL + schedURL);
	}

	var publicAPI = {
		showSearch: showSearch,
		singleSearch: singleSearch,
		showLookup: showLookup,
		peopleSearch: peopleSearch,
		schedule: schedule
	};

	return publicAPI;
})();<commit_msg>added some functions<commit_after>var TVMaze = (function tvMaze() {
  'use strict';

  var rootURL = "http://api.tvmaze.com";

  function getJSON(url) {
    return new Promise(function(resolve, reject){
      var req = new XMLHttpRequest();
      req.open("GET", url);
      req.responseType = 'json';
      req.onload = function() {
        if (req.status == 200) {
          resolve(req.response);
        }
        else {
          reject(Error(req.statusText));
        }
      };

      req.onerror = function() {
        reject(Error("Network Error"));
      };

      req.send();
    });
  }

  function showSearch(query) {
    return getJSON(rootURL + "/search/shows?q=" + query);
  }

  function singleSearch(query) {
    return getJSON(rootURL + "/singlesearch/shows?q=" + query);
  }

  function showLookup(id, option) {
    return getJSON(rootURL + "/lookup/shows?" + option + "=" + id);
  }

  function peopleSearch(query) {
    return getJSON(rootURL + "/search/people?q=" + query);
  }

  function schedule(countryCode, date){
    var schedURL = "/schedule";
    if(countryCode && date) {
      schedURL += "?country=" + countryCode + "&date=" + date;
    }
    else if (countryCode && !date) {
      schedURL += "?country=" + countryCode;
    }
    else if (!countryCode && date) {
      schedURL += "?date=" + date;
    }

    return getJSON(rootURL + schedURL);
  }

  var publicAPI = {
    showSearch: showSearch,
    singleSearch: singleSearch,
    showLookup: showLookup,
    peopleSearch: peopleSearch,
    schedule: schedule
  };

  return publicAPI;
})();<|endoftext|>


<commit_before>var fs = require('fs');
var os = require('os');
var sh = require('child_process').execSync;
var path = require('path');

var ROOT = process.cwd();
var NODEJS = '.';
var SYNC = false;

if (process.env['SKIP_SYNC'] == 1 || process.env['SKIP_SYNC'] == 0) {
  SYNC = (process.env['SKIP_SYNC'] == 1) ? false : true;
}

if (os.platform() == 'win32') {
  process.chdir(path.resolve(ROOT, '..'));
  ROOT = process.cwd();
  NODEJS = path.resolve(process.env['USERPROFILE'], '.node-gyp', process.version.substring(1));
} else {
  NODEJS = path.resolve(process.env['HOME'], '.node-gyp', process.version.substring(1));
}

if (fs.existsSync(ROOT + path.sep + 'nodejs.gypi')) {
  fs.unlinkSync(ROOT + path.sep + 'nodejs.gypi');
}

fs.linkSync(NODEJS + path.sep + 'common.gypi', ROOT + path.sep + 'nodejs.gypi');

var CONFIG = 'Release';

if (fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'Debug')) {
  CONFIG = 'Debug';
}

var THIRD_PARTY = path.resolve(ROOT, 'third_party');
var DEPOT_TOOLS_REPO = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git';
var DEPOT_TOOLS = path.resolve(THIRD_PARTY, 'depot_tools');
var WEBRTC = path.resolve(THIRD_PARTY, 'webrtc');
var WEBRTC_SRC = path.resolve(WEBRTC, 'src');
var WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG);

if (os.platform() == 'win32' && process.arch == 'x64') {
  WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG + '_x64');
}

if (!SYNC) {
  if (fs.existsSync(THIRD_PARTY + path.sep + 'webrtc_sync')) {
    var stat = fs.statSync(THIRD_PARTY + path.sep + 'webrtc_sync');

    if ((stat.mtime.getTime() - (new Date().getTime())) > 86400000) {
      SYNC = true;
    }
  } else {
    SYNC = true;
  }
}

process.env['GYP_DEFINES'] = process.env['GYP_DEFINES'] ? process.env['GYP_DEFINES'] : '';

if (process.env['GYP_DEFINES'] !== '') {
  console.log('GYP_DEFINES =', process.env['GYP_DEFINES']);
}

if (!fs.existsSync(THIRD_PARTY)) {
  fs.mkdirSync(THIRD_PARTY);
}

if (!fs.existsSync(DEPOT_TOOLS)) {
  sh('git clone ' + DEPOT_TOOLS_REPO, {
    cwd: THIRD_PARTY,
    env: process.env,
    stdio: 'inherit',
  });
}

process.env['PATH'] = process.env['PATH'] + path.delimiter + DEPOT_TOOLS;

if (!fs.existsSync(WEBRTC) || !fs.existsSync(WEBRTC_SRC)) {
  fs.mkdirSync(WEBRTC);

  sh('fetch webrtc', {
    cwd: WEBRTC,
    env: process.env,
    stdio: 'inherit',
  });

  if (os.platform() == 'linux') {
    sh('./build/install-build-deps.sh', {
      cwd: WEBRTC_SRC,
      env: process.env,
      stdio: 'inherit',
    });
  }
}

process.env['GYP_DEFINES'] += ' target_arch=' + process.arch;
process.env['GYP_DEFINES'] += ' host_arch=' + process.arch;
process.env['GYP_DEFINES'] += ' nodedir=' + NODEJS;

switch (os.platform()) {
  case 'darwin':
    process.env['GYP_DEFINES'] += ' clang=1';

    break;
  case 'win32':
    process.env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = 0;

    break;
  case 'linux':
    if (!process.env['JAVA_HOME']) {
      process.env['JAVA_HOME'] = '/usr/lib/jvm/java';
    }

    break;
  default:
    break;
}

console.log('target_arch =', process.arch);
console.log('host_arch =', process.arch);
console.log('configuration =', CONFIG);
console.log('SKIP_SYNC =', SYNC ? false : true);
console.log('Enable / Disable Sync: ');

if (os.platform() == 'win32') {
  console.log('set SKIP_SYNC=1');
  console.log('set SKIP_SYNC=0');
} else {
  console.log('export SKIP_SYNC=1');
  console.log('export SKIP_SYNC=0');
}

if (SYNC) {
  try {
    sh('gclient sync', {
      cwd: WEBRTC,
      env: process.env,
      stdio: 'inherit',
    });
  } catch (error) {
    // TODO(): src/build/landmines.py in third_party\webrtc\src\chromium is causing error on win32?

    if (os.platform() == 'win32') {
      sh('gclient sync', {
        cwd: WEBRTC,
        env: process.env,
        stdio: 'inherit',
      });
    } else {
      throw error;
    }
  }

  fs.closeSync(fs.openSync(THIRD_PARTY + path.sep + 'webrtc_sync', 'w'));
}

if (fs.existsSync(WEBRTC_SRC)) {
  console.log('Building WebRTC Node Module');

  sh('python ' + WEBRTC_SRC + path.sep + 'webrtc' + path.sep + 'build' + path.sep + 'gyp_webrtc webrtc.gyp', {
    cwd: ROOT,
    env: process.env,
    stdio: 'inherit',
  });

  sh('ninja -C ' + WEBRTC_OUT, {
    cwd: WEBRTC_SRC,
    env: process.env,
    stdio: 'inherit',
  });

  fs.linkSync(WEBRTC_OUT + path.sep + 'webrtc-native.node', ROOT + path.sep + 'build' + path.sep + CONFIG + path.sep + 'webrtc-native.node');
}
<commit_msg>Update<commit_after>var fs = require('fs');
var os = require('os');
var sh = require('child_process').execSync;
var path = require('path');

var ROOT = process.cwd();
var NODEJS = '.';
var SYNC = false;

if (process.env['SKIP_SYNC'] == 1 || process.env['SKIP_SYNC'] == 0) {
  SYNC = (process.env['SKIP_SYNC'] == 1) ? false : true;
}

if (os.platform() == 'win32') {
  process.chdir(path.resolve(ROOT, '..'));
  ROOT = process.cwd();
  NODEJS = path.resolve(process.env['USERPROFILE'], '.node-gyp', process.version.substring(1));
} else {
  NODEJS = path.resolve(process.env['HOME'], '.node-gyp', process.version.substring(1));
}

if (fs.existsSync(ROOT + path.sep + 'nodejs.gypi')) {
  fs.unlinkSync(ROOT + path.sep + 'nodejs.gypi');
}

if (!fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'config.gypi')) {
  throw new Error('Run node-gyp rebuild instead of node build.js');
}

fs.linkSync(NODEJS + path.sep + 'common.gypi', ROOT + path.sep + 'nodejs.gypi');

var CONFIG = 'Release';

if (fs.existsSync(ROOT + path.sep + 'build' + path.sep + 'Debug')) {
  CONFIG = 'Debug';
}

var THIRD_PARTY = path.resolve(ROOT, 'third_party');
var DEPOT_TOOLS_REPO = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git';
var DEPOT_TOOLS = path.resolve(THIRD_PARTY, 'depot_tools');
var WEBRTC = path.resolve(THIRD_PARTY, 'webrtc');
var WEBRTC_SRC = path.resolve(WEBRTC, 'src');
var WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG);

if (os.platform() == 'win32' && process.arch == 'x64') {
  WEBRTC_OUT = path.resolve(WEBRTC_SRC, 'out', CONFIG + '_x64');
}

if (!SYNC) {
  if (fs.existsSync(THIRD_PARTY + path.sep + 'webrtc_sync')) {
    var stat = fs.statSync(THIRD_PARTY + path.sep + 'webrtc_sync');

    if ((stat.mtime.getTime() - (new Date().getTime())) > 86400000) {
      SYNC = true;
    }
  } else {
    SYNC = true;
  }
}

process.env['GYP_DEFINES'] = process.env['GYP_DEFINES'] ? process.env['GYP_DEFINES'] : '';

if (process.env['GYP_DEFINES'] !== '') {
  console.log('GYP_DEFINES =', process.env['GYP_DEFINES']);
}

if (!fs.existsSync(THIRD_PARTY)) {
  fs.mkdirSync(THIRD_PARTY);
}

if (!fs.existsSync(DEPOT_TOOLS)) {
  sh('git clone ' + DEPOT_TOOLS_REPO, {
    cwd: THIRD_PARTY,
    env: process.env,
    stdio: 'inherit',
  });
}

process.env['PATH'] = process.env['PATH'] + path.delimiter + DEPOT_TOOLS;

if (!fs.existsSync(WEBRTC) || !fs.existsSync(WEBRTC_SRC)) {
  fs.mkdirSync(WEBRTC);

  sh('fetch webrtc', {
    cwd: WEBRTC,
    env: process.env,
    stdio: 'inherit',
  });

  if (os.platform() == 'linux') {
    sh('./build/install-build-deps.sh', {
      cwd: WEBRTC_SRC,
      env: process.env,
      stdio: 'inherit',
    });
  }
}

process.env['GYP_DEFINES'] += ' target_arch=' + process.arch;
process.env['GYP_DEFINES'] += ' host_arch=' + process.arch;
process.env['GYP_DEFINES'] += ' nodedir=' + NODEJS;

switch (os.platform()) {
  case 'darwin':
    process.env['GYP_DEFINES'] += ' clang=1';

    break;
  case 'win32':
    process.env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = 0;

    break;
  case 'linux':
    if (!process.env['JAVA_HOME']) {
      process.env['JAVA_HOME'] = '/usr/lib/jvm/java';
    }

    break;
  default:
    break;
}

console.log('target_arch =', process.arch);
console.log('host_arch =', process.arch);
console.log('configuration =', CONFIG);
console.log('SKIP_SYNC =', SYNC ? false : true);
console.log('Enable / Disable Sync: ');

if (os.platform() == 'win32') {
  console.log('set SKIP_SYNC=1');
  console.log('set SKIP_SYNC=0');
} else {
  console.log('export SKIP_SYNC=1');
  console.log('export SKIP_SYNC=0');
}

if (SYNC) {
  try {
    sh('gclient sync', {
      cwd: WEBRTC,
      env: process.env,
      stdio: 'inherit',
    });
  } catch (error) {
    // TODO(): src/build/landmines.py in third_party\webrtc\src\chromium is causing error on win32?

    if (os.platform() == 'win32') {
      sh('gclient sync', {
        cwd: WEBRTC,
        env: process.env,
        stdio: 'inherit',
      });
    } else {
      throw error;
    }
  }

  fs.closeSync(fs.openSync(THIRD_PARTY + path.sep + 'webrtc_sync', 'w'));
}

if (fs.existsSync(WEBRTC_SRC)) {
  console.log('Building WebRTC Node Module');

  sh('python ' + WEBRTC_SRC + path.sep + 'webrtc' + path.sep + 'build' + path.sep + 'gyp_webrtc webrtc.gyp', {
    cwd: ROOT,
    env: process.env,
    stdio: 'inherit',
  });

  sh('ninja -C ' + WEBRTC_OUT, {
    cwd: WEBRTC_SRC,
    env: process.env,
    stdio: 'inherit',
  });

  fs.linkSync(WEBRTC_OUT + path.sep + 'webrtc-native.node', ROOT + path.sep + 'build' + path.sep + CONFIG + path.sep + 'webrtc-native.node');
}
<|endoftext|>


<commit_before><commit_msg>Add additional tests around datagrids, containers and nesting.<commit_after><|endoftext|>


<commit_before>/**
 * This is the module to be used in Node.js, NW.js or Electron
 * @module twitch-sdk
 */

/**
 * This is the main class of the SDK. Methods marked as `public` are exposed
 * to your app.
 * @class Twitch
 */

const util = require('./lib/twitch.util');
const core = require('./lib/twitch.core');
const init = require('./lib/twitch.init');
const auth = require('./lib/twitch.auth');

// Init
exports.init = init.init;

// Core
exports.api = core.api;

// Events
exports.events = {
  on: core.events.on,
  addListener: core.events.on,
  once: core.events.once,
  removeListener: core.events.removeListener,
  getMaxListeners: core.events.getMaxListeners,
  listenerCount: core.events.listenerCount
};
exports.on = core.events.on;
exports.addListener = core.events.on;
exports.once = core.events.once;
exports.removeListener = core.events.removeListener;
exports.getMaxListeners = core.events.getMaxListeners;
exports.listenerCount = core.events.listenerCount;

// Auth
exports.getToken = auth.getToken;
exports.getStatus = auth.getStatus;
exports.login = auth.login;
exports.logout = auth.logout;
<commit_msg>get core.events to operate<commit_after>/**
 * This is the module to be used in Node.js, NW.js or Electron
 * @module twitch-sdk
 */

/**
 * This is the main class of the SDK. Methods marked as `public` are exposed
 * to your app.
 * @class Twitch
 */

const util = require('./lib/twitch.util');
const core = require('./lib/twitch.core');
const init = require('./lib/twitch.init');
const auth = require('./lib/twitch.auth');

// Init
exports.init = init.init;

// Core
exports.api = core.api;

// Events
exports.events = core.events;

// Auth
exports.getToken = auth.getToken;
exports.getStatus = auth.getStatus;
exports.login = auth.login;
exports.logout = auth.logout;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var browserify = require('browserify');

browserify()
  .add('./index.js')
  .bundle({
    standalone: 'rtc',
    insertGlobalVars: {
      process: function() {
        return {
          id: 'process',
          source: 'return {}'
        };
      },

      global: function() {
        return {
          id: 'global',
          source: 'return {}'
        };
      }
    }
  }).pipe(process.stdout);<commit_msg>Removed build.js helper<commit_after><|endoftext|>


<commit_before>var Stremio = require("stremio-addons");
var needle = require("needle");
var _ = require("lodash");

var twitch_chans = [];

var stremioCentral = "http://api9.strem.io";

var pkg = require("./package");
var manifest = {
    "id": "org.stremio.twitch",
    "types": ["tv"],
    "filter": { "query.twitch_id": { "$exists": true }, "query.type": { "$in":["tv"] } },
    icon: "http://s.jtvnw.net/jtv_user_pictures/hosted_images/GlitchIcon_purple.png",
    logo: "https://rack1.chipmeup.com/assets/twitch/logo-cd148048b88ce417a0c815548e7e4681.png",
    repository: "http://github.com/jaruba/stremio-twitch",
    endpoint: "http://twitch.strem.io/stremioget/stremio/v1",
    name: pkg.displayName, version: pkg.version, description: pkg.description,
    isFree: true,
    sorts: [{prop: "popularities.twitch", name: "Twitch.tv", types:["tv"]}],
    boardShowControls: true
};

var expire = [];

// Get all channels
function twitchStreams(cb, limit, offset) {

    if (expire[offset] && expire[offset] > Date.now()) {
        if (twitch_chans[offset] && twitch_chans[offset].length && cb) {
            cb(null, twitch_chans[offset]);
            return;
        }
    }

    needle.get('https://api.twitch.tv/kraken/streams?limit=' + (limit || 75) + '\u0026offset=' + (offset || 0), function(err, res) {
        if (err) {
            cb && cb(err);
            return;
        }
        twitch_chans[offset] = [];
        if (res && res.body && res.body.streams && res.body.streams.length) {
            var channel = res.body.streams[0].channel.name;
            res.body.streams.forEach( function(el, ij) {
                twitch_chans[offset].push({
                    id: 'twitch_id:' + el.channel.name,
                    name: el.channel.status,
                    poster: el.preview.medium,
                    posterShape: 'landscape',
                    logoShape: 'hidden',
                    banner: el.channel.video_banner || el.preview.template.replace('{width}', '1920').replace('{height}', '1080'),
                    genre: [ 'Entertainment' ],
                    isFree: 1,
                    popularity: el.viewers,
                    popularities: { twitch: el.viewers },
                    type: 'tv'
                });
            });
            expire[offset] = Date.now() + 1800000; // expire in 30 mins
            cb && cb(null, twitch_chans[offset]);
        } else if (cb)
            cb(new Error('Network Error'));
    });
}

function searchMeta(args, cb) {

    var searcher = encodeURIComponent(args.query).split('%20').join('+');

    needle.get('https://api.twitch.tv/kraken/search/streams?limit=' + (args.limit || 75) + '&offset=' + (args.skip || 0) + '&q=' + searcher, function(err, res) {
        if (err) {
            cb && cb(err);
            return;
        }
        var results = [];
        if (res && res.body && res.body.streams && res.body.streams.length) {
            var channel = res.body.streams[0].channel.name;
            res.body.streams.forEach( function(el, ij) {
                results.push({
                    id: 'twitch_id:' + el.channel.name,
                    name: el.channel.status,
                    poster: el.preview.medium,
                    posterShape: 'landscape',
                    backgroundShape: 'contain',
                    logoShape: 'hidden',
                    banner: el.preview.template.replace('{width}', '1920').replace('{height}', '1080'),
                    genre: [ 'Entertainment' ],
                    isFree: 1,
                    popularity: el.viewers,
                    popularities: { twitch: el.viewers },
                    type: 'tv'
                });
            });
            cb && cb(null, { results: results, query: args.query });
        } else if (cb)
            cb(new Error('Network Error'));
    });
}

function getStream(args, callback) {
    var channel = args.query.twitch_id;
    if (channel) {
        needle.get('http://api.twitch.tv/api/channels/' + channel + '/access_token', function(err, res) {
            if (err) {
                callback(err);
                return;
            }
            if (res && res.body && res.body.sig && res.body.token) {
                var title = res.body.status;
                var token = res.body.token;
                var sig = res.body.sig;
                var rand = Math.floor((Math.random() * 999999) + 1);
                var mrl = 'http://usher.twitch.tv/api/channel/hls/' + channel + '.m3u8?player=twitchweb&token=' + token + '&sig=' + sig + '&allow_audio_only=true&allow_source=true&type=any&p=' + rand;
                callback(null, [{
                    availability: 1,
                    url: mrl,
                    title: 'HD',
                    tag: ['hls'],
                    isFree: 1,
                    twitch_id: args.query.twitch_id
                }]);
            } else if (callback)
                callback(new Error('Network Error'));
        });
    } else
        callback(new Error('Stream Missing'))
}

function getMeta(args, callback) {
    var offset = args.skip || 0;
    var limit = args.limit || 75;
    if (args.query.twitch_id) {
        var found = twitch_chans.some( function(chans) {
            return chans.some( function(el) {
                if (el.id == 'twitch_id:' + args.query.twitch_id) {
                    callback(null, el);
                    return true;
                }
            });
        });
        if (!found) {
            needle.get('http://api.twitch.tv/api/channels/' + args.query.twitch_id, function(err, res) {
                if (err) {
                    callback(err);
                    return;
                }
                if (res && res.body) {
                    callback(null, {
                        id: 'twitch_id:' + args.query.twitch_id,
                        name: res.body.status,
                        poster: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_' + args.query.twitch_id + '-320x180.jpg',
                        posterShape: 'landscape',
                        backgroundShape: 'contain',
                        logoShape: 'hidden',
                        banner: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_' + args.query.twitch_id + '-1920x1080.jpg',
                        genre: [ 'Entertainment' ],
                        isFree: 1,
                        type: 'tv'
                    });
                } else if (callback)
                    callback(new Error('No Results'));
            });
        }
    } else {
        twitchStreams(function(err, chans) {
            if (err) callback(err);
            else {
                callback(null, args.limit ? chans.slice(0, args.limit) : chans);
            }
        }, limit, offset);
    }
}
var addon = new Stremio.Server({
    "stream.find": getStream,
    "meta.get": getMeta,
    "meta.search": searchMeta,
    "meta.find": getMeta
}, { stremioget: true, cacheTTL: { "meta.find": 30*60, "stream.find": 19*60, "meta.get": 4*60*60 }, allow: ["http://api8.herokuapp.com","http://api9.strem.io"] /* secret: mySecret */ }, manifest);

var server = require("http").createServer(function (req, res) {
    addon.middleware(req, res, function() { res.end() }); // wire the middleware - also compatible with connect / express
}).on("listening", function()
{
    console.log("Twitch.tv Stremio Addon listening on "+server.address().port);
})
if (module.parent) module.exports = server;
else server.listen(process.env.PORT || 9028);

var catchMyExceptions = require('catch-my-exceptions');
if (process.env.SLACK_HOOK) catchMyExceptions(process.env.SLACK_HOOK, { slackUsername: "twitch" });
<commit_msg>ability to include as a module<commit_after>var Stremio = require("stremio-addons");
var needle = require("needle");
var _ = require("lodash");

var twitch_chans = [];

var stremioCentral = "http://api9.strem.io";

var pkg = require("./package");
var manifest = {
    "id": "org.stremio.twitch",
    "types": ["tv"],
    "filter": { "query.twitch_id": { "$exists": true }, "query.type": { "$in":["tv"] } },
    icon: "http://s.jtvnw.net/jtv_user_pictures/hosted_images/GlitchIcon_purple.png",
    logo: "https://rack1.chipmeup.com/assets/twitch/logo-cd148048b88ce417a0c815548e7e4681.png",
    repository: "http://github.com/jaruba/stremio-twitch",
    endpoint: "http://twitch.strem.io/stremioget/stremio/v1",
    name: pkg.displayName, version: pkg.version, description: pkg.description,
    isFree: true,
    sorts: [{prop: "popularities.twitch", name: "Twitch.tv", types:["tv"]}],
    boardShowControls: true
};

var expire = [];

// Get all channels
function twitchStreams(cb, limit, offset) {

    if (expire[offset] && expire[offset] > Date.now()) {
        if (twitch_chans[offset] && twitch_chans[offset].length && cb) {
            cb(null, twitch_chans[offset]);
            return;
        }
    }

    needle.get('https://api.twitch.tv/kraken/streams?limit=' + (limit || 75) + '\u0026offset=' + (offset || 0), function(err, res) {
        if (err) {
            cb && cb(err);
            return;
        }
        twitch_chans[offset] = [];
        if (res && res.body && res.body.streams && res.body.streams.length) {
            var channel = res.body.streams[0].channel.name;
            res.body.streams.forEach( function(el, ij) {
                twitch_chans[offset].push({
                    id: 'twitch_id:' + el.channel.name,
                    name: el.channel.status,
                    poster: el.preview.medium,
                    posterShape: 'landscape',
                    logoShape: 'hidden',
                    banner: el.channel.video_banner || el.preview.template.replace('{width}', '1920').replace('{height}', '1080'),
                    genre: [ 'Entertainment' ],
                    isFree: 1,
                    popularity: el.viewers,
                    popularities: { twitch: el.viewers },
                    type: 'tv'
                });
            });
            expire[offset] = Date.now() + 1800000; // expire in 30 mins
            cb && cb(null, twitch_chans[offset]);
        } else if (cb)
            cb(new Error('Network Error'));
    });
}

function searchMeta(args, cb) {

    var searcher = encodeURIComponent(args.query).split('%20').join('+');

    needle.get('https://api.twitch.tv/kraken/search/streams?limit=' + (args.limit || 75) + '&offset=' + (args.skip || 0) + '&q=' + searcher, function(err, res) {
        if (err) {
            cb && cb(err);
            return;
        }
        var results = [];
        if (res && res.body && res.body.streams && res.body.streams.length) {
            var channel = res.body.streams[0].channel.name;
            res.body.streams.forEach( function(el, ij) {
                results.push({
                    id: 'twitch_id:' + el.channel.name,
                    name: el.channel.status,
                    poster: el.preview.medium,
                    posterShape: 'landscape',
                    backgroundShape: 'contain',
                    logoShape: 'hidden',
                    banner: el.preview.template.replace('{width}', '1920').replace('{height}', '1080'),
                    genre: [ 'Entertainment' ],
                    isFree: 1,
                    popularity: el.viewers,
                    popularities: { twitch: el.viewers },
                    type: 'tv'
                });
            });
            cb && cb(null, { results: results, query: args.query });
        } else if (cb)
            cb(new Error('Network Error'));
    });
}

function getStream(args, callback) {
    var channel = args.query.twitch_id;
    if (channel) {
        needle.get('http://api.twitch.tv/api/channels/' + channel + '/access_token', function(err, res) {
            if (err) {
                callback(err);
                return;
            }
            if (res && res.body && res.body.sig && res.body.token) {
                var title = res.body.status;
                var token = res.body.token;
                var sig = res.body.sig;
                var rand = Math.floor((Math.random() * 999999) + 1);
                var mrl = 'http://usher.twitch.tv/api/channel/hls/' + channel + '.m3u8?player=twitchweb&token=' + token + '&sig=' + sig + '&allow_audio_only=true&allow_source=true&type=any&p=' + rand;
                callback(null, [{
                    availability: 1,
                    url: mrl,
                    title: 'HD',
                    tag: ['hls'],
                    isFree: 1,
                    twitch_id: args.query.twitch_id
                }]);
            } else if (callback)
                callback(new Error('Network Error'));
        });
    } else
        callback(new Error('Stream Missing'))
}

function getMeta(args, callback) {
    var offset = args.skip || 0;
    var limit = args.limit || 75;
    if (args.query.twitch_id) {
        var found = twitch_chans.some( function(chans) {
            return chans.some( function(el) {
                if (el.id == 'twitch_id:' + args.query.twitch_id) {
                    callback(null, el);
                    return true;
                }
            });
        });
        if (!found) {
            needle.get('http://api.twitch.tv/api/channels/' + args.query.twitch_id, function(err, res) {
                if (err) {
                    callback(err);
                    return;
                }
                if (res && res.body) {
                    callback(null, {
                        id: 'twitch_id:' + args.query.twitch_id,
                        name: res.body.status,
                        poster: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_' + args.query.twitch_id + '-320x180.jpg',
                        posterShape: 'landscape',
                        backgroundShape: 'contain',
                        logoShape: 'hidden',
                        banner: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_' + args.query.twitch_id + '-1920x1080.jpg',
                        genre: [ 'Entertainment' ],
                        isFree: 1,
                        type: 'tv'
                    });
                } else if (callback)
                    callback(new Error('No Results'));
            });
        }
    } else {
        twitchStreams(function(err, chans) {
            if (err) callback(err);
            else {
                callback(null, args.limit ? chans.slice(0, args.limit) : chans);
            }
        }, limit, offset);
    }
}
var addon = new Stremio.Server({
    "stream.find": getStream,
    "meta.get": getMeta,
    "meta.search": searchMeta,
    "meta.find": getMeta
}, { stremioget: true, cacheTTL: { "meta.find": 30*60, "stream.find": 19*60, "meta.get": 4*60*60 }, allow: ["http://api8.herokuapp.com","http://api9.strem.io"] /* secret: mySecret */ }, manifest);

if (module.parent) { module.exports = addon; } else {
var server = require("http").createServer(function (req, res) {
    addon.middleware(req, res, function() { res.end() }); // wire the middleware - also compatible with connect / express
}).on("listening", function()
{
    console.log("Twitch.tv Stremio Addon listening on "+server.address().port);
})
server.listen(process.env.PORT || 9028);

var catchMyExceptions = require('catch-my-exceptions');
if (process.env.SLACK_HOOK) catchMyExceptions(process.env.SLACK_HOOK, { slackUsername: "twitch" });
}
<|endoftext|>


<commit_before><commit_msg>fix module attribute ref<commit_after><|endoftext|>


<commit_before>var _ = require('underscore');
var utils = require('./controllerUtils.js');
var events = require('../../events');
var msg = require('./msg');
var model = require('./model');

function passback(id, result, nextFunction){
  // filter out results here
  events.Emitter.emit(id, result);
}

function subRegister(dataModel, method, params, data, ip, id) {
  // Provide some basic sanity checks
  if(!data.email) return passback(id, msg.missingEmail());
  if(utils.invalidEmail(data.email)) return passback(id, msg.badEmail(data.email));
  if(!data.password) return passback(id, msg.missingPwd());
  if(utils.invalidPassword(data.password) ) return passback(id, msg.badPwd());

  dataModel.subscriber.create(data.email, data.password, ip, function(result){
      passback(id, result);
  });
}

function subVerify(dataModel, method, params, data, ip, id) {

  var token = params[1];
  // Ensure a verification token is present and valid
  if(!token) return passback(id, msg.missingVerificationToken());
  if(utils.invalidToken(token)) return passback(id, msg.badVerificationToken());

  dataModel.subscriber.verify(token, function(result){
      passback(id, result);
  });

}

function subReset(dataModel, method, params, data, ip, id) {
  // Ensure email is present and valid
  if(!data.email) return msg.missingEmail();
  //if(badEmail(data.email)) return msg.badEmail(data.email);
  // Return the result of password reset
  dataModel.subscriber.reset(data.email, function(result){
    passback(id, result);
  })
}

function subLogin(dataModel, method, params, data, ip, id) {
  if(!data.email) return msg.missingEmail();
 // if(badEmail(data.email)) return msg.badEmail(data.email);
  dataModel.session.authenticate(data.email, data.password,
  function(result){
    passback(id, result);
  });
}

function subLogout(dataModel, method, params, data, ip, id) {
  return msg.success(); // TODO: implement this..
}

function sessAuthenticate(dataModel, headers, cb) {
  if(headers['x-access-token']) {
    dataModel.session.getByAccessToken(headers['x-access-token'],
    function(result){ cb(result); });
  } else cb(null);
}

module.exports = function(testAdapter) {
  var dataModel;
	if(testAdapter){
		dataModel = model(testAdapter);
  } else {
		dataModel = model();
	}
  return {
    authenticate: _.bind(sessAuthenticate, null, dataModel),
    module: {
      noauth: {
        register: _.bind(subRegister, null, dataModel),
        verify: _.bind(subVerify, null, dataModel),
        reset: _.bind(subRegister, null, dataModel),
        login: _.bind(subLogin, null, dataModel)
      },
      auth: {
        logout: _.bind(subLogout, null, dataModel)
      }
    }
  }
}

<commit_msg>Update controller.js<commit_after>var _ = require('underscore');
var utils = require('./controllerUtils.js');
var events = require('../../events');
var msg = require('./msg');
var model = require('./model');

function passback(id, result, nextFunction){
  // filter out results here
  events.Emitter.emit(id, result);
}

function subRegister(dataModel, method, params, data, ip, id) {
  // Provide some basic sanity checks
  if(!data.email) return passback(id, msg.missingEmail());
  if(utils.invalidEmail(data.email)) return passback(id, msg.badEmail(data.email));
  if(!data.password) return passback(id, msg.missingPwd());
  if(utils.invalidPassword(data.password) ) return passback(id, msg.badPwd());

  dataModel.subscriber.create(data.email, data.password, ip, function(result){
      passback(id, result);
  });
}

function subVerify(dataModel, method, params, data, ip, id) {

  var token = params[1];
  // Ensure a verification token is present and valid
  if(!token) return passback(id, msg.missingVerificationToken());
  if(utils.invalidToken(token)) return passback(id, msg.badVerificationToken());

  dataModel.subscriber.verify(token, function(result){
      passback(id, result);
  });

}

function subReset(dataModel, method, params, data, ip, id) {
  // Ensure email is present and valid
  if(!data.email) return msg.missingEmail();
  //if(badEmail(data.email)) return msg.badEmail(data.email);
  // Return the result of password reset
  dataModel.subscriber.reset(data.email, function(result){
    passback(id, result);
  })
}

function subLogin(dataModel, method, params, data, ip, id) {
  if(!data.email) return msg.missingEmail();
  if(badEmail(data.email)) return msg.badEmail(data.email);
  dataModel.session.authenticate(data.email, data.password,
  function(result){
    passback(id, result);
  });
}

function subLogout(dataModel, method, params, data, ip, id) {
  return msg.success(); // TODO: implement this..
}

function sessAuthenticate(dataModel, headers, cb) {
  if(headers['x-access-token']) {
    dataModel.session.getByAccessToken(headers['x-access-token'],
    function(result){ cb(result); });
  } else cb(null);
}

module.exports = function(testAdapter) {
  var dataModel;
	if(testAdapter){
		dataModel = model(testAdapter);
  } else {
		dataModel = model();
	}
  return {
    authenticate: _.bind(sessAuthenticate, null, dataModel),
    module: {
      noauth: {
        register: _.bind(subRegister, null, dataModel),
        verify: _.bind(subVerify, null, dataModel),
        reset: _.bind(subRegister, null, dataModel),
        login: _.bind(subLogin, null, dataModel)
      },
      auth: {
        logout: _.bind(subLogout, null, dataModel)
      }
    }
  }
}

<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Add API route to application<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/api', api)
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/Cartesian3',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/DeveloperError',
        '../Core/Ellipsoid',
        '../Core/Math',
        '../Core/Matrix3',
        '../Core/Transforms',
        '../Scene/SceneMode'
    ], function(
        Cartesian3,
        defaultValue,
        defined,
        DeveloperError,
        Ellipsoid,
        CesiumMath,
        Matrix3,
        Transforms,
        SceneMode) {
    "use strict";

    var updateTransformMatrix3Scratch1 = new Matrix3();
    var updateTransformMatrix3Scratch2 = new Matrix3();
    var updateTransformMatrix3Scratch3 = new Matrix3();
    var updateTransformCartesian3Scratch1 = new Cartesian3();
    var updateTransformCartesian3Scratch2 = new Cartesian3();
    var updateTransformCartesian3Scratch3 = new Cartesian3();

    var northUpRadiusFactor = 1.2;                  // times ellipsoid's maximum radius
    var northUpMinimumVelocity = 8000.0;            // meters/sec
    var vvlhMinimumVelocity = CesiumMath.EPSILON4;  // meters/sec

    function updateTransform(that, camera, objectChanged, positionProperty, time, ellipsoid) {
        var cartesian = positionProperty.getValue(time, that._lastCartesian);
        if (defined(cartesian)) {
            var hasBasis = false;
            var xBasis;
            var yBasis;
            var zBasis;

            // The time delta was determined based on how fast satellites move compared to vehicles near the surface.
            // Slower moving vehicles will most likely default to east-north-up, while faster ones will be LVLH.
            var deltaTime = time.addSeconds(0.01);
            var deltaCartesian = positionProperty.getValue(deltaTime, updateTransformCartesian3Scratch1);
            var positionRadiusFactor = Cartesian3.magnitude(cartesian) / ellipsoid.maximumRadius;
            var velocityMagnitude = 0;
            if (defined(deltaCartesian)) {
                Cartesian3.subtract(cartesian, deltaCartesian, updateTransformCartesian3Scratch2);
                velocityMagnitude = Cartesian3.magnitude(updateTransformCartesian3Scratch2) * 100.0;  // meters/sec
            }

            if (positionRadiusFactor > northUpRadiusFactor || velocityMagnitude > northUpMinimumVelocity) {
                // North-up viewing from deep space.

                // X along the nadir
                xBasis = updateTransformCartesian3Scratch2;
                Cartesian3.normalize(cartesian, xBasis);
                Cartesian3.negate(xBasis, xBasis);

                // Z is North
                zBasis = Cartesian3.clone(Cartesian3.UNIT_Z, updateTransformCartesian3Scratch3);

                // Y is along the cross of z and x (right handed basis / in the direction of motion)
                yBasis = Cartesian3.cross(zBasis, xBasis, updateTransformCartesian3Scratch1);

                Cartesian3.normalize(xBasis, xBasis);
                Cartesian3.normalize(yBasis, yBasis);

                zBasis = Cartesian3.cross(xBasis, yBasis, updateTransformCartesian3Scratch3);
                Cartesian3.normalize(zBasis, zBasis);
                hasBasis = true;

            } else if (velocityMagnitude > vvlhMinimumVelocity) {
                // Approximation of VVLH (Vehicle Velocity Local Horizontal)

                var toInertial = Transforms.computeFixedToIcrfMatrix(time, updateTransformMatrix3Scratch1);
                var toInertialDelta = Transforms.computeFixedToIcrfMatrix(deltaTime, updateTransformMatrix3Scratch2);
                var toFixed;

                if (!defined(toInertial) || !defined(toInertialDelta)) {
                    toFixed = Transforms.computeTemeToPseudoFixedMatrix(time, updateTransformMatrix3Scratch3);
                    toInertial = Matrix3.transpose(toFixed, updateTransformMatrix3Scratch1);
                    toInertialDelta = Transforms.computeTemeToPseudoFixedMatrix(deltaTime, updateTransformMatrix3Scratch2);
                    Matrix3.transpose(toInertialDelta, toInertialDelta);
                } else {
                    toFixed = Matrix3.transpose(toInertial, updateTransformMatrix3Scratch3);
                }

                // Z along the position
                zBasis = updateTransformCartesian3Scratch2;
                Cartesian3.normalize(cartesian, zBasis);
                Cartesian3.normalize(deltaCartesian, deltaCartesian);

                Matrix3.multiplyByVector(toInertial, zBasis, zBasis);
                Matrix3.multiplyByVector(toInertialDelta, deltaCartesian, deltaCartesian);

                // Y is along the angular momentum vector (e.g. "orbit normal")
                yBasis = Cartesian3.cross(zBasis, deltaCartesian, updateTransformCartesian3Scratch3);
                if (!Cartesian3.equalsEpsilon(yBasis, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
                    // X is along the cross of y and z (right handed basis / in the direction of motion)
                    xBasis = Cartesian3.cross(yBasis, zBasis, updateTransformCartesian3Scratch1);

                    Matrix3.multiplyByVector(toFixed, xBasis, xBasis);
                    Matrix3.multiplyByVector(toFixed, yBasis, yBasis);
                    Matrix3.multiplyByVector(toFixed, zBasis, zBasis);

                    Cartesian3.normalize(xBasis, xBasis);
                    Cartesian3.normalize(yBasis, yBasis);
                    Cartesian3.normalize(zBasis, zBasis);

                    hasBasis = true;
                }
            }

            if (hasBasis) {
                var transform = camera.transform;
                transform[0]  = xBasis.x;
                transform[1]  = xBasis.y;
                transform[2]  = xBasis.z;
                transform[3]  = 0.0;
                transform[4]  = yBasis.x;
                transform[5]  = yBasis.y;
                transform[6]  = yBasis.z;
                transform[7]  = 0.0;
                transform[8]  = zBasis.x;
                transform[9]  = zBasis.y;
                transform[10] = zBasis.z;
                transform[11] = 0.0;
                transform[12]  = cartesian.x;
                transform[13]  = cartesian.y;
                transform[14] = cartesian.z;
                transform[15] = 0.0;
            } else {
                // Stationary or slow-moving, low-altitude objects use East-North-Up.
                Transforms.eastNorthUpToFixedFrame(cartesian, ellipsoid, camera.transform);
            }

            that._screenSpaceCameraController.ellipsoid = Ellipsoid.UNIT_SPHERE;
        }

        updateController(that, camera, objectChanged);
    }

    function updateController(that, camera, objectChanged) {
        var scene = that.scene;

        if (objectChanged || scene.mode !== that._mode) {
            that._mode = scene.mode;
            if (scene.mode === SceneMode.SCENE2D) {
                camera.lookAt(that._offset2D, Cartesian3.ZERO, that._up2D);
            } else {
                camera.lookAt(that._offset3D, Cartesian3.ZERO, that._up3D);
            }
        }

        if (scene.mode === SceneMode.SCENE2D) {
            Cartesian3.fromElements(0.0, 0.0, camera.getMagnitude(), that._offset2D);
            Cartesian3.clone(camera.up, that._up2D);
        } else {
            Cartesian3.clone(camera.position, that._offset3D);
            Cartesian3.clone(camera.up, that._up3D);
        }
    }

    /**
     * A utility object for tracking an object with the camera.
     * @alias DynamicObjectView
     * @constructor
     *
     * @param {DynamicObject} dynamicObject The object to track with the camera.
     * @param {Scene} scene The scene to use.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use for orienting the camera.
     */
    var DynamicObjectView = function(dynamicObject, scene, ellipsoid) {
        /**
         * The object to track with the camera.
         * @type {DynamicObject}
         */
        this.dynamicObject = dynamicObject;

        /**
         * The scene in which to track the object.
         * @type {Scene}
         */
        this.scene = scene;
        this._lastScene = undefined;

        /**
         * The ellipsoid to use for orienting the camera.
         * @type {Ellipsoid}
         */
        this.ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

        //Shadow copies of the objects so we can detect changes.
        this._lastDynamicObject = undefined;
        this._mode = undefined;

        //Re-usable objects to be used for retrieving position.
        this._lastCartesian = new Cartesian3();

        this._offset3D = new Cartesian3(-10000, 2500, 2500);
        this._up3D = Cartesian3.cross(this._offset3D, Cartesian3.cross(Cartesian3.UNIT_Z, this._offset3D));
        Cartesian3.normalize(this._up3D, this._up3D);

        this._offset2D = new Cartesian3(0.0, 0.0, Cartesian3.magnitude(this._offset3D));
        this._up2D = Cartesian3.clone(Cartesian3.UNIT_Y);
    };

    /**
    * Should be called each animation frame to update the camera
    * to the latest settings.
    * @param {JulianDate} time The current animation time.
    *
    */
    DynamicObjectView.prototype.update = function(time) {
        var scene = this.scene;
        var dynamicObject = this.dynamicObject;
        var ellipsoid = this.ellipsoid;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        if (!defined(scene)) {
            throw new DeveloperError('DynamicObjectView.scene is required.');
        }
        if (!defined(dynamicObject)) {
            throw new DeveloperError('DynamicObjectView.dynamicObject is required.');
        }
        if (!defined(ellipsoid)) {
            throw new DeveloperError('DynamicObjectView.ellipsoid is required.');
        }
        if (!defined(dynamicObject.position)) {
            throw new DeveloperError('dynamicObject.position is required.');
        }
        //>>includeEnd('debug');

        if (scene !== this._lastScene) {
            this._lastScene = scene;
            this._screenSpaceCameraController = scene.screenSpaceCameraController;
        }

        var positionProperty = dynamicObject.position;
        var objectChanged = dynamicObject !== this._lastDynamicObject;
        this._lastDynamicObject = dynamicObject;

        if (scene.mode !== SceneMode.MORPHING) {
            updateTransform(this, scene.camera, objectChanged, positionProperty, time, ellipsoid);
        }
    };

    return DynamicObjectView;
});
<commit_msg>Switch to using semiMajorAxis for the North-Up decision.<commit_after>/*global define*/
define([
        '../Core/Cartesian3',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/DeveloperError',
        '../Core/Ellipsoid',
        '../Core/Math',
        '../Core/Matrix3',
        '../Core/Transforms',
        '../Scene/SceneMode'
    ], function(
        Cartesian3,
        defaultValue,
        defined,
        DeveloperError,
        Ellipsoid,
        CesiumMath,
        Matrix3,
        Transforms,
        SceneMode) {
    "use strict";

    var updateTransformMatrix3Scratch1 = new Matrix3();
    var updateTransformMatrix3Scratch2 = new Matrix3();
    var updateTransformMatrix3Scratch3 = new Matrix3();
    var updateTransformCartesian3Scratch1 = new Cartesian3();
    var updateTransformCartesian3Scratch2 = new Cartesian3();
    var updateTransformCartesian3Scratch3 = new Cartesian3();
    var updateTransformCartesian3Scratch4 = new Cartesian3();
    var updateTransformCartesian3Scratch5 = new Cartesian3();
    var updateTransformCartesian3Scratch6 = new Cartesian3();

    var northUpAxisFactor = 1.25;  // times ellipsoid's maximum radius

    function updateTransform(that, camera, objectChanged, positionProperty, time, ellipsoid) {
        var cartesian = positionProperty.getValue(time, that._lastCartesian);
        if (defined(cartesian)) {
            var hasBasis = false;
            var xBasis;
            var yBasis;
            var zBasis;

            // The time delta was determined based on how fast satellites move compared to vehicles near the surface.
            // Slower moving vehicles will most likely default to east-north-up, while faster ones will be LVLH.
            var deltaTime = time.addSeconds(0.001);
            var deltaCartesian = positionProperty.getValue(deltaTime, updateTransformCartesian3Scratch1);
            if (defined(deltaCartesian)) {
                var toInertial = Transforms.computeFixedToIcrfMatrix(time, updateTransformMatrix3Scratch1);
                var toInertialDelta = Transforms.computeFixedToIcrfMatrix(deltaTime, updateTransformMatrix3Scratch2);
                var toFixed;

                if (!defined(toInertial) || !defined(toInertialDelta)) {
                    toFixed = Transforms.computeTemeToPseudoFixedMatrix(time, updateTransformMatrix3Scratch3);
                    toInertial = Matrix3.transpose(toFixed, updateTransformMatrix3Scratch1);
                    toInertialDelta = Transforms.computeTemeToPseudoFixedMatrix(deltaTime, updateTransformMatrix3Scratch2);
                    Matrix3.transpose(toInertialDelta, toInertialDelta);
                } else {
                    toFixed = Matrix3.transpose(toInertial, updateTransformMatrix3Scratch3);
                }

                var inertialCartesian = Matrix3.multiplyByVector(toInertial, cartesian, updateTransformCartesian3Scratch5);
                var inertialDeltaCartesian = Matrix3.multiplyByVector(toInertialDelta, deltaCartesian, updateTransformCartesian3Scratch6);

                Cartesian3.subtract(inertialCartesian, inertialDeltaCartesian, updateTransformCartesian3Scratch4);
                var inertialVelocity = Cartesian3.magnitude(updateTransformCartesian3Scratch4) * 1000.0;  // meters/sec

                // http://en.wikipedia.org/wiki/Standard_gravitational_parameter
                // Consider adding this to Cesium.Ellipsoid?
                var mu = 3.986004418e14;  // m^3 / sec^2

                var semiMajorAxis = -mu / (inertialVelocity * inertialVelocity - (2 * mu / Cartesian3.magnitude(inertialCartesian)));

                if (semiMajorAxis > northUpAxisFactor * ellipsoid.maximumRadius) {
                    // North-up viewing from deep space.

                    // X along the nadir
                    xBasis = updateTransformCartesian3Scratch2;
                    Cartesian3.normalize(cartesian, xBasis);
                    Cartesian3.negate(xBasis, xBasis);

                    // Z is North
                    zBasis = Cartesian3.clone(Cartesian3.UNIT_Z, updateTransformCartesian3Scratch3);

                    // Y is along the cross of z and x (right handed basis / in the direction of motion)
                    yBasis = Cartesian3.cross(zBasis, xBasis, updateTransformCartesian3Scratch1);

                    Cartesian3.normalize(xBasis, xBasis);
                    Cartesian3.normalize(yBasis, yBasis);

                    zBasis = Cartesian3.cross(xBasis, yBasis, updateTransformCartesian3Scratch3);
                    Cartesian3.normalize(zBasis, zBasis);

                    hasBasis = true;

                } else if (!Cartesian3.equalsEpsilon(cartesian, deltaCartesian, CesiumMath.EPSILON7)) {
                    // Approximation of VVLH (Vehicle Velocity Local Horizontal)

                    // Z along the position
                    zBasis = updateTransformCartesian3Scratch2;
                    Cartesian3.normalize(cartesian, zBasis);
                    Cartesian3.normalize(deltaCartesian, deltaCartesian);

                    Matrix3.multiplyByVector(toInertial, zBasis, zBasis);
                    Matrix3.multiplyByVector(toInertialDelta, deltaCartesian, deltaCartesian);

                    // Y is along the angular momentum vector (e.g. "orbit normal")
                    yBasis = Cartesian3.cross(zBasis, deltaCartesian, updateTransformCartesian3Scratch3);
                    if (!Cartesian3.equalsEpsilon(yBasis, Cartesian3.ZERO, CesiumMath.EPSILON7)) {
                        // X is along the cross of y and z (right handed basis / in the direction of motion)
                        xBasis = Cartesian3.cross(yBasis, zBasis, updateTransformCartesian3Scratch1);

                        Matrix3.multiplyByVector(toFixed, xBasis, xBasis);
                        Matrix3.multiplyByVector(toFixed, yBasis, yBasis);
                        Matrix3.multiplyByVector(toFixed, zBasis, zBasis);

                        Cartesian3.normalize(xBasis, xBasis);
                        Cartesian3.normalize(yBasis, yBasis);
                        Cartesian3.normalize(zBasis, zBasis);

                        hasBasis = true;
                    }
                }
            }

            if (hasBasis) {
                var transform = camera.transform;
                transform[0]  = xBasis.x;
                transform[1]  = xBasis.y;
                transform[2]  = xBasis.z;
                transform[3]  = 0.0;
                transform[4]  = yBasis.x;
                transform[5]  = yBasis.y;
                transform[6]  = yBasis.z;
                transform[7]  = 0.0;
                transform[8]  = zBasis.x;
                transform[9]  = zBasis.y;
                transform[10] = zBasis.z;
                transform[11] = 0.0;
                transform[12]  = cartesian.x;
                transform[13]  = cartesian.y;
                transform[14] = cartesian.z;
                transform[15] = 0.0;
            } else {
                // Stationary or slow-moving, low-altitude objects use East-North-Up.
                Transforms.eastNorthUpToFixedFrame(cartesian, ellipsoid, camera.transform);
            }

            that._screenSpaceCameraController.ellipsoid = Ellipsoid.UNIT_SPHERE;
        }

        updateController(that, camera, objectChanged);
    }

    function updateController(that, camera, objectChanged) {
        var scene = that.scene;

        if (objectChanged || scene.mode !== that._mode) {
            that._mode = scene.mode;
            if (scene.mode === SceneMode.SCENE2D) {
                camera.lookAt(that._offset2D, Cartesian3.ZERO, that._up2D);
            } else {
                camera.lookAt(that._offset3D, Cartesian3.ZERO, that._up3D);
            }
        }

        if (scene.mode === SceneMode.SCENE2D) {
            Cartesian3.fromElements(0.0, 0.0, camera.getMagnitude(), that._offset2D);
            Cartesian3.clone(camera.up, that._up2D);
        } else {
            Cartesian3.clone(camera.position, that._offset3D);
            Cartesian3.clone(camera.up, that._up3D);
        }
    }

    /**
     * A utility object for tracking an object with the camera.
     * @alias DynamicObjectView
     * @constructor
     *
     * @param {DynamicObject} dynamicObject The object to track with the camera.
     * @param {Scene} scene The scene to use.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use for orienting the camera.
     */
    var DynamicObjectView = function(dynamicObject, scene, ellipsoid) {
        /**
         * The object to track with the camera.
         * @type {DynamicObject}
         */
        this.dynamicObject = dynamicObject;

        /**
         * The scene in which to track the object.
         * @type {Scene}
         */
        this.scene = scene;
        this._lastScene = undefined;

        /**
         * The ellipsoid to use for orienting the camera.
         * @type {Ellipsoid}
         */
        this.ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);

        //Shadow copies of the objects so we can detect changes.
        this._lastDynamicObject = undefined;
        this._mode = undefined;

        //Re-usable objects to be used for retrieving position.
        this._lastCartesian = new Cartesian3();

        this._offset3D = new Cartesian3(-10000, 2500, 2500);
        this._up3D = Cartesian3.cross(this._offset3D, Cartesian3.cross(Cartesian3.UNIT_Z, this._offset3D));
        Cartesian3.normalize(this._up3D, this._up3D);

        this._offset2D = new Cartesian3(0.0, 0.0, Cartesian3.magnitude(this._offset3D));
        this._up2D = Cartesian3.clone(Cartesian3.UNIT_Y);
    };

    /**
    * Should be called each animation frame to update the camera
    * to the latest settings.
    * @param {JulianDate} time The current animation time.
    *
    */
    DynamicObjectView.prototype.update = function(time) {
        var scene = this.scene;
        var dynamicObject = this.dynamicObject;
        var ellipsoid = this.ellipsoid;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        if (!defined(scene)) {
            throw new DeveloperError('DynamicObjectView.scene is required.');
        }
        if (!defined(dynamicObject)) {
            throw new DeveloperError('DynamicObjectView.dynamicObject is required.');
        }
        if (!defined(ellipsoid)) {
            throw new DeveloperError('DynamicObjectView.ellipsoid is required.');
        }
        if (!defined(dynamicObject.position)) {
            throw new DeveloperError('dynamicObject.position is required.');
        }
        //>>includeEnd('debug');

        if (scene !== this._lastScene) {
            this._lastScene = scene;
            this._screenSpaceCameraController = scene.screenSpaceCameraController;
        }

        var positionProperty = dynamicObject.position;
        var objectChanged = dynamicObject !== this._lastDynamicObject;
        this._lastDynamicObject = dynamicObject;

        if (scene.mode !== SceneMode.MORPHING) {
            updateTransform(this, scene.camera, objectChanged, positionProperty, time, ellipsoid);
        }
    };

    return DynamicObjectView;
});
<|endoftext|>