<commit_before>'use strict';

/* istanbul ignore if  */
if (process.env.NODE_ENV === 'production') {
  /* eslint-disable no-console */
  console.log('Starting newrelic application monitoring');
  /* eslint-enable */
  require('newrelic'); // eslint-disable-line global-require
}

const raven = require('raven');
const sentry = require('./lib/sentry');

const User = require('./models/User');
const Checkin = require('./models/Checkin');

const express = require('express');
const compression = require('compression');
const responseTime = require('response-time');
const bodyParser = require('body-parser');
const HttpError = require('@starefossen/http-error');

const { middleware: requireAuth } = require('./lib/auth');
const { middleware: getNtbObject } = require('./lib/ntb');

const app = module.exports = express();
const router = new express.Router();

app.set('json spaces', 2);
app.set('x-powered-by', false);

router.use(compression());
router.use(responseTime());
router.use(bodyParser.json());

// Full URL
router.use(require('./lib/express-full-url'));

// Cors Headers
router.use(require('@starefossen/express-cors').middleware);

// Health Check
const healthCheck = require('@starefossen/express-health');

router.get('/CloudHealthCheck', healthCheck({
  name: 'RethinkDB',
  check: cb => {
    cb(null, { status: 'Ok' });
  },
}));

router.get('/', (req, res) => {
  res.json({
    checkin_new: { url: `${req.fullUrl}/steder/{sted}/besok` },
    checkin_get: { url: `${req.fullUrl}/steder/{sted}/besok/{oid}` },
    checkin_log: { url: `${req.fullUrl}/steder/{sted}/logg` },
    checkin_stats: { url: `${req.fullUrl}/steder/{sted}/stats` },
    profile_view: { url: `${req.fullUrl}/brukere/{bruker}` },
    list_join: { url: `${req.fullUrl}/lister/{liste}/blimed` },
    list_leave: { url: `${req.fullUrl}/lister/{liste}/meldav` },
    list_log: { url: `${req.fullUrl}/lister/{liste}/logg` },
  });
});

const notImplementedYet = (req, res) => {
  res.status(418);
  res.json({ message: 'Not implemented yet, come back later' });
};

router.get('/steder/:sted/stats', (req, res, next) => {
  Checkin.find()
    .where('ntb_steder_id').equals(req.params.sted)
    .count()
    .then(count => res.json({ data: { count } }))
    .catch(error => next(new HttpError('Database failure', 500, error)));
});

router.get('/steder/:sted/logg', (req, res, next) => {
  Checkin.find()
    .where('ntb_steder_id').equals(req.params.sted)
    .limit(50)
    .sort({ timestamp: -1 })
    .then(checkins => checkins.map(c => c.anonymize(req.headers['x-user-id'])))
    .then(data => res.json({ data }))
    .catch(error => next(new HttpError('Database failure', 500, error)));
});

router.post('/steder/:sted/besok', requireAuth, getNtbObject, (req, res, next) => {
  const promise = Checkin.create({
    location: {
      type: 'Point',
      coordinates: [req.body.lon, req.body.lat],
    },
    public: !!req.body.public,
    ntb_steder_id: req.params.sted,
    dnt_user_id: req.user.id,
    timestamp: req.body.timestamp,
  });

  // Save new checkin to user profile
  promise.then(checkin => {
    req.user.innsjekkinger.push(checkin);
    req.user.save();
  });

  // Return new checkin object
  promise.then(checkin => {
    res.set('Location', `${req.fullUrl}${req.url}/${checkin._id}`);
    res.json({
      message: 'Ok',
      data: checkin.toJSON({
        getters: false,
        versionKey: false,
      }),
    });
  });

  promise.catch(error => {
    if (error.name === 'ValidationError') {
      res.status(400).json({
        message: 'Checkin validation failed',
        code: 400,
        errors: error.errors,
      });
    } else {
      next(new HttpError('Database connection failed', 500, error));
    }
  });
});

router.param('checkin', (req, res, next) => {
  if (/^[a-f0-9]{24}$/.test(req.params.checkin) === false) {
    res.status(400).json({ message: 'Invalid ObjectId' });
  } else {
    next();
  }
});

router.get('/steder/:sted/besok/:checkin', (req, res, next) => {
  // @TODO redirect to correct cononical URL for checkin ID
  // @TODO validate visibility

  const promise = Checkin.findOne({ _id: req.params.checkin });

  promise.then(data => {
    if (!data) {
      next(new HttpError('Checkin not found', 404));
    } else {
      res.json({ data });
    }
  });

  promise.catch(error => next(new HttpError('Database failure', 500, error)));
});

router.get('/lister/:liste/stats', notImplementedYet);

router.get('/lister/:liste/logg', (req, res) => {
  Checkin.getCheckinsForList(req.params.liste)
    .then(checkins => checkins.map(c => c.anonymize(req.headers['x-user-id'])))
    .then(checkins => res.json({ data: checkins }));
});

router.post('/lister/:liste/blimed', requireAuth, (req, res) => {
  const user = req.user;
  if (user.lister.indexOf(req.params.liste) === -1) {
    user.lister.push(req.params.liste);
  }
  user.save();
  res.json({
    message: 'Ok',
    data: user,
  });
});

router.post('/lister/:liste/meldav', requireAuth, (req, res) => {
  const user = req.user;
  if (user.lister.indexOf(req.params.liste) > -1) {
    user.lister.splice(user.lister.indexOf(req.params.liste), 1);
  }
  user.save();
  res.json({
    message: 'Ok',
    data: user,
  });
});

router.param('bruker', (req, res, next, bruker) => {
  const brukerId = parseInt(bruker, 10);

  // Assert valid user ID
  if (isNaN(brukerId)) {
    return next(new HttpError(`Invalid user id "${bruker}"`, 400));
  }

  // Get user profile from database
  return User
    .findOne({ _id: brukerId })

    // Expand user checkins
    .populate('innsjekkinger')

    // Check if user exists
    .then(user => {
      if (!user) {
        throw new HttpError(`User "${req.params.bruker}" Not Found`, 404);
      }

      return user;
    })

    // Conditionally hide private user checkins
    // @TODO authenticate X-User-ID header before use
    .then(user => user.filterCheckins(parseInt(req.headers['x-user-id'], 10)))

    // Attach user instance to request object
    .then(user => { req.user = user; })

    .then(() => next())

    .catch(error => {
      if (error instanceof HttpError) {
        next(error);
      } else {
        next(new HttpError('Database failure', 500, error));
      }
    });
});

router.get('/brukere/:bruker', (req, res) => {
  res.json({ data: req.user });
});

router.get('/brukere/:bruker/stats', notImplementedYet);
router.get('/brukere/:bruker/logg', notImplementedYet);

// Not Found
router.use((req, res, next) => next(new HttpError('Not Found', 404)));

// Sentry Error Handling
router.use(raven.middleware.express.requestHandler(sentry));
router.use(raven.middleware.express.errorHandler(sentry));

// Final Error Handling
router.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  /* eslint-disable no-console */
  if (err.code >= 500) {
    if (err.error) {
      console.error(err.error.message);
      console.error(err.error.stack);
    } else {
      console.error(err.message);
      console.error(err.stack);
    }
  }
  /* eslint-enable */

  res.status(err.code).json(err.toJSON());
});

app.use(process.env.VIRTUAL_PATH, router);

/* istanbul ignore if */
if (!module.parent) {
  const port = process.env.VIRTUAL_PORT || 8080;

  app.listen(port);
  console.log(`Server listening on port ${port}`); // eslint-disable-line no-console
}
<commit_msg>feat(api): include checkin rules<commit_after>'use strict';

/* istanbul ignore if  */
if (process.env.NODE_ENV === 'production') {
  /* eslint-disable no-console */
  console.log('Starting newrelic application monitoring');
  /* eslint-enable */
  require('newrelic'); // eslint-disable-line global-require
}

const raven = require('raven');
const sentry = require('./lib/sentry');

const User = require('./models/User');
const Checkin = require('./models/Checkin');

const express = require('express');
const compression = require('compression');
const responseTime = require('response-time');
const bodyParser = require('body-parser');
const HttpError = require('@starefossen/http-error');

const { middleware: requireAuth } = require('./lib/auth');
const { middleware: getNtbObject } = require('./lib/ntb');

const app = module.exports = express();
const router = new express.Router();

app.set('json spaces', 2);
app.set('x-powered-by', false);

router.use(compression());
router.use(responseTime());
router.use(bodyParser.json());

// Full URL
router.use(require('./lib/express-full-url'));

// Cors Headers
router.use(require('@starefossen/express-cors').middleware);

// Health Check
const healthCheck = require('@starefossen/express-health');

router.get('/CloudHealthCheck', healthCheck({
  name: 'RethinkDB',
  check: cb => {
    cb(null, { status: 'Ok' });
  },
}));

router.get('/', (req, res) => {
  res.json({
    checkin_new: {
      url: `${req.fullUrl}/steder/{sted}/besok`,
      rules: {
        max_distance: parseInt(process.env.CHECKIN_MAX_DISTANCE, 10),
        timeout: parseInt(process.env.CHECKIN_TIMEOUT, 10),
      },
    },
    checkin_get: { url: `${req.fullUrl}/steder/{sted}/besok/{oid}` },
    checkin_log: { url: `${req.fullUrl}/steder/{sted}/logg` },
    checkin_stats: { url: `${req.fullUrl}/steder/{sted}/stats` },
    profile_view: { url: `${req.fullUrl}/brukere/{bruker}` },
    list_join: { url: `${req.fullUrl}/lister/{liste}/blimed` },
    list_leave: { url: `${req.fullUrl}/lister/{liste}/meldav` },
    list_log: { url: `${req.fullUrl}/lister/{liste}/logg` },
  });
});

const notImplementedYet = (req, res) => {
  res.status(418);
  res.json({ message: 'Not implemented yet, come back later' });
};

router.get('/steder/:sted/stats', (req, res, next) => {
  Checkin.find()
    .where('ntb_steder_id').equals(req.params.sted)
    .count()
    .then(count => res.json({ data: { count } }))
    .catch(error => next(new HttpError('Database failure', 500, error)));
});

router.get('/steder/:sted/logg', (req, res, next) => {
  Checkin.find()
    .where('ntb_steder_id').equals(req.params.sted)
    .limit(50)
    .sort({ timestamp: -1 })
    .then(checkins => checkins.map(c => c.anonymize(req.headers['x-user-id'])))
    .then(data => res.json({ data }))
    .catch(error => next(new HttpError('Database failure', 500, error)));
});

router.post('/steder/:sted/besok', requireAuth, getNtbObject, (req, res, next) => {
  const promise = Checkin.create({
    location: {
      type: 'Point',
      coordinates: [req.body.lon, req.body.lat],
    },
    public: !!req.body.public,
    ntb_steder_id: req.params.sted,
    dnt_user_id: req.user.id,
    timestamp: req.body.timestamp,
  });

  // Save new checkin to user profile
  promise.then(checkin => {
    req.user.innsjekkinger.push(checkin);
    req.user.save();
  });

  // Return new checkin object
  promise.then(checkin => {
    res.set('Location', `${req.fullUrl}${req.url}/${checkin._id}`);
    res.json({
      message: 'Ok',
      data: checkin.toJSON({
        getters: false,
        versionKey: false,
      }),
    });
  });

  promise.catch(error => {
    if (error.name === 'ValidationError') {
      res.status(400).json({
        message: 'Checkin validation failed',
        code: 400,
        errors: error.errors,
      });
    } else {
      next(new HttpError('Database connection failed', 500, error));
    }
  });
});

router.param('checkin', (req, res, next) => {
  if (/^[a-f0-9]{24}$/.test(req.params.checkin) === false) {
    res.status(400).json({ message: 'Invalid ObjectId' });
  } else {
    next();
  }
});

router.get('/steder/:sted/besok/:checkin', (req, res, next) => {
  // @TODO redirect to correct cononical URL for checkin ID
  // @TODO validate visibility

  const promise = Checkin.findOne({ _id: req.params.checkin });

  promise.then(data => {
    if (!data) {
      next(new HttpError('Checkin not found', 404));
    } else {
      res.json({ data });
    }
  });

  promise.catch(error => next(new HttpError('Database failure', 500, error)));
});

router.get('/lister/:liste/stats', notImplementedYet);

router.get('/lister/:liste/logg', (req, res) => {
  Checkin.getCheckinsForList(req.params.liste)
    .then(checkins => checkins.map(c => c.anonymize(req.headers['x-user-id'])))
    .then(checkins => res.json({ data: checkins }));
});

router.post('/lister/:liste/blimed', requireAuth, (req, res) => {
  const user = req.user;
  if (user.lister.indexOf(req.params.liste) === -1) {
    user.lister.push(req.params.liste);
  }
  user.save();
  res.json({
    message: 'Ok',
    data: user,
  });
});

router.post('/lister/:liste/meldav', requireAuth, (req, res) => {
  const user = req.user;
  if (user.lister.indexOf(req.params.liste) > -1) {
    user.lister.splice(user.lister.indexOf(req.params.liste), 1);
  }
  user.save();
  res.json({
    message: 'Ok',
    data: user,
  });
});

router.param('bruker', (req, res, next, bruker) => {
  const brukerId = parseInt(bruker, 10);

  // Assert valid user ID
  if (isNaN(brukerId)) {
    return next(new HttpError(`Invalid user id "${bruker}"`, 400));
  }

  // Get user profile from database
  return User
    .findOne({ _id: brukerId })

    // Expand user checkins
    .populate('innsjekkinger')

    // Check if user exists
    .then(user => {
      if (!user) {
        throw new HttpError(`User "${req.params.bruker}" Not Found`, 404);
      }

      return user;
    })

    // Conditionally hide private user checkins
    // @TODO authenticate X-User-ID header before use
    .then(user => user.filterCheckins(parseInt(req.headers['x-user-id'], 10)))

    // Attach user instance to request object
    .then(user => { req.user = user; })

    .then(() => next())

    .catch(error => {
      if (error instanceof HttpError) {
        next(error);
      } else {
        next(new HttpError('Database failure', 500, error));
      }
    });
});

router.get('/brukere/:bruker', (req, res) => {
  res.json({ data: req.user });
});

router.get('/brukere/:bruker/stats', notImplementedYet);
router.get('/brukere/:bruker/logg', notImplementedYet);

// Not Found
router.use((req, res, next) => next(new HttpError('Not Found', 404)));

// Sentry Error Handling
router.use(raven.middleware.express.requestHandler(sentry));
router.use(raven.middleware.express.errorHandler(sentry));

// Final Error Handling
router.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  /* eslint-disable no-console */
  if (err.code >= 500) {
    if (err.error) {
      console.error(err.error.message);
      console.error(err.error.stack);
    } else {
      console.error(err.message);
      console.error(err.stack);
    }
  }
  /* eslint-enable */

  res.status(err.code).json(err.toJSON());
});

app.use(process.env.VIRTUAL_PATH, router);

/* istanbul ignore if */
if (!module.parent) {
  const port = process.env.VIRTUAL_PORT || 8080;

  app.listen(port);
  console.log(`Server listening on port ${port}`); // eslint-disable-line no-console
}
<|endoftext|>


<commit_before>// Setup Canvas
var canvas = document.body.appendChild( document.createElement( 'canvas' ) );

// Get WebGL Context
var gl = require('gl-context')( canvas, render );

// Import StackGL Webgl
var glGeometry = require('gl-geometry');
var glShader = require('gl-shader');
var clear = require('gl-clear')();
var glslify = require('glslify');

// Import Math Libraries
var mat4 = require('gl-matrix').mat4;

// Import Web Helper Libraries
var fit = require('canvas-fit');
var isMobile = require('is-mobile');

// Import YCAM GRP Libraries
var ycam = require('ycam');
var cga = require('cga');
var cam = require('nsc')( canvas, { position: [ 0.0, 0.0, -2.0 ] } );

// Set the canvas size to fill the window and its pixel density
var mobile = isMobile( navigator.userAgent );
var dpr = mobile ? 1 : ( window.devicePixelRatio || 1 );
window.addEventListener( 'resize', fit( canvas, null, dpr ), false );

//Setup Matricies
var projection = mat4.create();
var model = mat4.create();
var view = mat4.create();

//Setup Shaders
var vertexShader = glslify( './shaders/shader.vert' );
var fragmentShader = glslify( './shaders/shader.frag' );
var shader = glShader( gl, vertexShader, fragmentShader );

// Setup Sketch Parameters
var outline = glGeometry( gl );
outline.attr( 'aPosition', ycam.positions, { size: 2 } );

function update() {
  // Set Perspective Projection
  var aspectRatio = gl.drawingBufferWidth / gl.drawingBufferHeight;
  var fieldOfView = Math.PI / 4.0;
  var near = 0.01;
  var far  = 1000.0;
  mat4.perspective( projection, fieldOfView, aspectRatio, near, far );
  cam.view( view );
  cam.update();
}

function render() {
  update();

  gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  clear( gl );

  // Set Blending
  gl.disable( gl.DEPTH_TEST );
  gl.enable( gl.BLEND );
  gl.blendFunc( gl.SRC_ALPHA, gl.ONE );

  outline.bind( shader );
  if( isMobile ) { shader.uniforms.dpr = dpr * 2.0; } else { shader.uniforms.dpr = dpr; }
  shader.uniforms.uPointSize = 1.0;
  shader.uniforms.uProjection = projection;
  shader.uniforms.uView = view;
  shader.uniforms.uModel = model;
  shader.uniforms.uColor = [0, 1, 1, 1];
  outline.draw( gl.LINE_LOOP );
  outline.unbind();
}
<commit_msg>created expanded of ycam logo and refactored drawing routine<commit_after>// Setup Canvas
var canvas = document.body.appendChild( document.createElement( 'canvas' ) );

// Get WebGL Context
var gl = require('gl-context')( canvas, render );

// Import StackGL Webgl
var glGeometry = require('gl-geometry');
var glShader = require('gl-shader');
var clear = require('gl-clear')();
var glslify = require('glslify');

// Import Math Libraries
var mat4 = require('gl-matrix').mat4;

// Import Web Helper Libraries
var fit = require('canvas-fit');
var isMobile = require('is-mobile');

// Import YCAM GRP Libraries
var ycam = require('ycam');
var cga = require('cga');
var cam = require('nsc')( canvas, { position: [ 0.0, 0.0, -2.0 ] } );

// Set the canvas size to fill the window and its pixel density
var mobile = isMobile( navigator.userAgent );
var dpr = mobile ? 1 : ( window.devicePixelRatio || 1 );
window.addEventListener( 'resize', fit( canvas, null, dpr ), false );

//Setup Matricies
var projection = mat4.create();
var model = mat4.create();
var view = mat4.create();

//Setup Shaders
var vertexShader = glslify( './shaders/shader.vert' );
var fragmentShader = glslify( './shaders/shader.frag' );
var shader = glShader( gl, vertexShader, fragmentShader );

// Setup Sketch Parameters
var outline = glGeometry( gl );
outline.attr( 'aPosition', ycam.positions, { size: 2 } );

var outlineExpanded = glGeometry( gl );
var ycamExpanded = cga.expandPolygon2( ycam.positions, 0.05 );
outlineExpanded.attr( 'aPosition', ycamExpanded, { size: 2 } );

function update() {
  // Set Perspective Projection
  var aspectRatio = gl.drawingBufferWidth / gl.drawingBufferHeight;
  var fieldOfView = Math.PI / 4.0;
  var near = 0.01;
  var far  = 1000.0;
  mat4.perspective( projection, fieldOfView, aspectRatio, near, far );
  cam.view( view );
  cam.update();
}

function render() {
  update();

  gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  clear( gl );

  // Set Blending
  gl.disable( gl.DEPTH_TEST );
  gl.enable( gl.BLEND );
  gl.blendFunc( gl.SRC_ALPHA, gl.ONE );

  drawGeo( outline, gl.LINE_LOOP, [0, 1, 1, 1] );
  drawGeo( outlineExpanded, gl.LINE_LOOP, [0, 1, 1, 1] );
}

function drawGeo( geo, mode, color ) {
  geo.bind( shader );
  if( isMobile ) { shader.uniforms.dpr = dpr * 2.0; } else { shader.uniforms.dpr = dpr; }
  shader.uniforms.uPointSize = 1.0;
  shader.uniforms.uProjection = projection;
  shader.uniforms.uView = view;
  shader.uniforms.uModel = model;
  shader.uniforms.uColor = color;
  geo.draw( mode );
  geo.unbind();
}
<|endoftext|>


<commit_before>const BaseRegistrar = require('./build/contracts/BaseRegistrar')
const BaseRegistrarImplementation = require('./build/contracts/BaseRegistrarImplementation')
const BulkRenewal = require('./build/contracts/BulkRenewal')
const ENS = require('./build/contracts/ENS')
const ENSRegistry = require('./build/contracts/ENSRegistry')
const ENSRegistryWithFallback = require('./build/contracts/ENSRegistryWithFallback')
const ETHRegistrarController = require('./build/contracts/ETHRegistrarController')
const FIFSRegistrar = require('./build/contracts/FIFSRegistrar')
const LinearPremiumPriceOracle = require('./build/contracts/LinearPremiumPriceOracle')
const PriceOracle = require('./build/contracts/PriceOracle')
const PublicResolver = require('./build/contracts/PublicResolver')
const Resolver = require('./build/contracts/Resolver')
const ReverseRegistrar = require('./build/contracts/ReverseRegistrar')
const TestRegistrar = require('./build/contracts/TestRegistrar')
const StablePriceOracle  = require('./build/contracts/StablePriceOracle')
const DNSRegistrar = require('./build/contracts/DNSRegistrar')
const PublicSuffixList = require('./build/contracts/PublicSuffixList')
const SimplePublicSuffixList = require('./build/contracts/SimplePublicSuffixList')
const TLDPublicSuffixList = require('./build/contracts/TLDPublicSuffixList')

const Root = require('./build/contracts/Root')
const DNSSEC  = require('./build/contracts/DNSSEC')
const RSASHA256Algorithm = require('./build/contracts/RSASHA256Algorithm')
const RSASHA1Algorithm = require('./build/contracts/RSASHA1Algorithm')
const SHA256Digest = require('./build/contracts/SHA256Digest')
const SHA1Digest = require('./build/contracts/SHA1Digest')
const SHA1NSEC3Digest = require('./build/contracts/SHA1NSEC3Digest')

module.exports = {
  BaseRegistrar,
  BaseRegistrarImplementation,
  BulkRenewal,
  ENS,
  ENSRegistry,
  ENSRegistryWithFallback,
  ETHRegistrarController,
  FIFSRegistrar,
  LinearPremiumPriceOracle,
  PriceOracle,
  PublicResolver,
  Resolver,
  ReverseRegistrar,
  StablePriceOracle,
  TestRegistrar,
  DNSRegistrar,
  PublicSuffixList,
  SimplePublicSuffixList,
  TLDPublicSuffixList,
  Root,
  DNSSEC,
  RSASHA256Algorithm,
  RSASHA1Algorithm,
  SHA256Digest,
  SHA1Digest,
  SHA1NSEC3Digest
}
<commit_msg>Expose abi to premium price oracle<commit_after>const BaseRegistrar = require('./build/contracts/BaseRegistrar')
const BaseRegistrarImplementation = require('./build/contracts/BaseRegistrarImplementation')
const BulkRenewal = require('./build/contracts/BulkRenewal')
const ENS = require('./build/contracts/ENS')
const ENSRegistry = require('./build/contracts/ENSRegistry')
const ENSRegistryWithFallback = require('./build/contracts/ENSRegistryWithFallback')
const ExponentialPremiumPriceOracle = require('/build/contracts/ExponentialPremiumPriceOracle')
const ETHRegistrarController = require('./build/contracts/ETHRegistrarController')
const FIFSRegistrar = require('./build/contracts/FIFSRegistrar')
const LinearPremiumPriceOracle = require('./build/contracts/LinearPremiumPriceOracle')
const PriceOracle = require('./build/contracts/PriceOracle')
const PublicResolver = require('./build/contracts/PublicResolver')
const Resolver = require('./build/contracts/Resolver')
const ReverseRegistrar = require('./build/contracts/ReverseRegistrar')
const TestRegistrar = require('./build/contracts/TestRegistrar')
const StablePriceOracle = require('./build/contracts/StablePriceOracle')
const DNSRegistrar = require('./build/contracts/DNSRegistrar')
const PublicSuffixList = require('./build/contracts/PublicSuffixList')
const SimplePublicSuffixList = require('./build/contracts/SimplePublicSuffixList')
const TLDPublicSuffixList = require('./build/contracts/TLDPublicSuffixList')

const Root = require('./build/contracts/Root')
const DNSSEC = require('./build/contracts/DNSSEC')
const RSASHA256Algorithm = require('./build/contracts/RSASHA256Algorithm')
const RSASHA1Algorithm = require('./build/contracts/RSASHA1Algorithm')
const SHA256Digest = require('./build/contracts/SHA256Digest')
const SHA1Digest = require('./build/contracts/SHA1Digest')
const SHA1NSEC3Digest = require('./build/contracts/SHA1NSEC3Digest')

module.exports = {
  BaseRegistrar,
  BaseRegistrarImplementation,
  BulkRenewal,
  ENS,
  ENSRegistry,
  ENSRegistryWithFallback,
  ExponentialPremiumPriceOracle,
  ETHRegistrarController,
  FIFSRegistrar,
  LinearPremiumPriceOracle,
  PriceOracle,
  PublicResolver,
  Resolver,
  ReverseRegistrar,
  StablePriceOracle,
  TestRegistrar,
  DNSRegistrar,
  PublicSuffixList,
  SimplePublicSuffixList,
  TLDPublicSuffixList,
  Root,
  DNSSEC,
  RSASHA256Algorithm,
  RSASHA1Algorithm,
  SHA256Digest,
  SHA1Digest,
  SHA1NSEC3Digest,
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

var http = require('http')
var https = require('https')
var parseUrl = require('url').parse
var normalizeUrl = require('normalize-url')
var chalk = require('chalk')

var prevUrl
var start = Date.now()
var hops = 0

follow(process.argv[2], start)

function follow (url, ms) {
  url = normalizeUrl(url)

  if (url === prevUrl) {
    console.log('Self-referencing redirect detected - aborting...')
    process.exit(1)
  }
  prevUrl = url

  var opts = parseUrl(url)
  opts.method = 'HEAD'

  var protocol = opts.protocol === 'https:' ? https : http

  var req = protocol.request(opts, function (res) {
    var diff = Date.now() - ms

    console.log('%s %s %s %s', chalk.green('[' + res.statusCode + ']'), chalk.gray(opts.method), url, chalk.cyan('(' + diff + ' ms)'))

    switch (res.statusCode) {
      case 301:
      case 302:
      case 303:
      case 307:
        hops++
        follow(res.headers.location, Date.now())
        break
      default:
        diff = Date.now() - start
        console.log('Trace finished in %s using %s', chalk.cyan(diff + ' ms'), chalk.cyan(hops + ' hop' + (hops > 1 ? 's' : '')))
        process.exit(0)
    }
  })

  req.on('error', function (err) {
    console.error('Error:', err.message)
    console.error('\nCould not connect to:\n%s', url)
    process.exit(1)
  })

  req.end()
}
<commit_msg>Update index.js: Don't strip www from URLs<commit_after>#!/usr/bin/env node
'use strict'

var http = require('http')
var https = require('https')
var parseUrl = require('url').parse
var normalizeUrl = require('normalize-url')
var chalk = require('chalk')

var prevUrl
var start = Date.now()
var hops = 0

follow(process.argv[2], start)

function follow (url, ms) {
  url = normalizeUrl(url, { stripWWW: false })

  if (url === prevUrl) {
    console.log('Self-referencing redirect detected - aborting...')
    process.exit(1)
  }
  prevUrl = url

  var opts = parseUrl(url)
  opts.method = 'HEAD'

  var protocol = opts.protocol === 'https:' ? https : http

  var req = protocol.request(opts, function (res) {
    var diff = Date.now() - ms

    console.log('%s %s %s %s', chalk.green('[' + res.statusCode + ']'), chalk.gray(opts.method), url, chalk.cyan('(' + diff + ' ms)'))

    switch (res.statusCode) {
      case 301:
      case 302:
      case 303:
      case 307:
        hops++
        follow(res.headers.location, Date.now())
        break
      default:
        diff = Date.now() - start
        console.log('Trace finished in %s using %s', chalk.cyan(diff + ' ms'), chalk.cyan(hops + ' hop' + (hops > 1 ? 's' : '')))
        process.exit(0)
    }
  })

  req.on('error', function (err) {
    console.error('Error:', err.message)
    console.error('\nCould not connect to:\n%s', url)
    process.exit(1)
  })

  req.end()
}
<|endoftext|>


<commit_before>import { Server as WSserver } from 'ws';
import { createServer } from 'http';
import express from 'express';

const app = express()
  .use(express.static(`${__dirname}/public`))
  .use('/bundle.js', express.static(`${__dirname}/public/build/bundle.js`));

const server = createServer(app)
  .listen(7878, () => {
    console.log(`
      dark patterns is running on 7878
    `);
  });

const wsServer = new WSserver({ server });

wsServer.on('connection', (ws) => {
  console.log('___ ws server connection established');
  ws.on('close', () => {
    console.log('___ closing ws server connection');
  });
});
<commit_msg>WIP integrating gamepad<commit_after>import { Server as WSserver } from 'ws';
import { createServer } from 'http';
import gamepad  from 'gamepad';
import express from 'express';

// Initialize `gamepad` library
gamepad.init();

// Create a game loop and poll for events
setInterval(gamepad.processEvents, 16);

// Scan for new gamepads as a slower rate
setInterval(gamepad.detectDevices, 500);

// Create the `express` app
// Setup static assets serving
const app = express()
  .use(express.static(`${__dirname}/public`))
  .use('/bundle.js', express.static(`${__dirname}/public/build/bundle.js`));

// Create http server and listen
const server = createServer(app)
  .listen(7878, () => {
    console.log(`
      dark patterns is running on 7878
    `);
  });

// Create `WebSocket` server and pass in the `http` server
const wsServer = new WSserver({ server });

// Setup events
wsServer.on('connection', (ws) => {
  console.log('___ ws server connection established');
  ws.on('close', () => {
    console.log('___ closing ws server connection');
  });
});

// Listen for move events on all gamepads
gamepad.on('move', (id, axis, value) => {
  console.log('move', {
    id: id,
    axis: axis,
    value: value,
  });
});

// Listen for button up events on all gamepads
gamepad.on('up', (id, num) => {
  console.log('up', {
    id: id,
    num: num,
  });
});

// Listen for button down events on all gamepads
gamepad.on('down', (id, num) => {
  console.log('down', {
    id: id,
    num: num,
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const program = require('commander');
const fs = require('fs');
const os = require('os');
const async = require('async');
const child_process = require('child_process');
const logger = require('./logger.js');
const plist = require('plist');

program
  .version('0.1.0')
  .description('Incident response tool for iPhone or iPad')
  .option('-o, --output [directory]', 'Set output directory')
  .option('-v, --verbose', 'Display verbose output')

program
  .command('collect')
  .description('Collect IR artifacts from iPhone or iPad')
  .option('-b, --backup', 'Backup iOS device')
  .option('--syslog-timeout <ms>', 'Optional timeout for how long to collect syslong, e.g. 86400 to collect for a day')
  .action(function(options) {
      collectArtifacts(options);
  });

program
  .command('process')
  .description('Process collected artifacts')
  .action(function() {
    processArtifacts();
  });

program
  .command('report')
  .description('Generate iOS IR report')
  .action(function() {
    generateReport();
  });

program.parse(process.argv);

// if program was called with no arguments, show help.
if (program.args.length === 0) program.help();

function setWorkingDirectory (userOutputDir, udid, currentEpoch) {
  let wd = ""
  if (userOutputDir) {
    wd = userOutputDir;
  } else {
    wd = __dirname;
  }

  // need to move away from "/" and start using path.sep
  const wd_udid = wd + "/" + udid;
  const wd_udid_epoch = wd_udid + '/' + currentEpoch;

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

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

  if (!fs.existsSync(wd_udid_epoch + '/artifacts')){
    fs.mkdirSync(wd_udid_epoch + '/artifacts');
  }

  logger.info("output directory set to %s", wd_udid_epoch);
  return(wd_udid_epoch);
}

function collectArtifacts(options) {
  // let's first get the UDID...if we can't do this successfully, we have a problem
  getUDID(function (error, udid) {
    if (error) {
      return logger.error(error);
    }

    // no error getting UDID so time to fetch data
    // first we'll setup the working directory, saving data in unique dir each time based on epoch time
    const currentEpoch = new Date().getTime();
    const wd = setWorkingDirectory(program.output, udid, currentEpoch);

    const idevicesyslog = getDeviceSyslog(udid, wd, options.syslogTimeout);

    async.parallel({
      backup: function(callback) {
        if (options.backup) {
          doDeviceBackup(udid, wd, callback);
        } else {
          logger.info("Skipping device backup");
          // this callback() iw critical so async.parallel can returm
          callback();
        }
      },
      deviceInfo: function(callback) {
        getDeviceInfo(udid, wd, callback);
      },
      installedApps: function(callback) {
        getInstalledApps(udid, wd, callback);
      },
      provisioningProfiles: function(callback) {
        listProvisioningProfiles(udid, wd, callback);
      },
      crashReports: function(callback) {
        getCrashReports(udid, wd, callback);
      }
    }, function(err, results) {
      //handle any errors from extraction functions
      if(options.syslogTimeout === undefined) {
        logger.info("completed all extraction functions so we'll now kill deviceSyslog");
        idevicesyslog.kill('SIGINT');
      } else {
        logger.info("waiting %d ms for syslog to execute", options.syslogTimeout);
      };
    });

  });
};

function getUDID (callback) {
  var retval = '';
  const udid = child_process.spawn('idevice_id', ['-l']);

  udid.stdout.on('data', (chunk) => {
    // FIXME: if idevice_id fires the data event more than once the this would overwrite
    // retval which is likley problematic
    retval = chunk;
  });

  udid.on('close', code => {
    /*
    Unfortunately idevice_id returns a 0 in all situations I checked
    which differs from how ideviceinfo works. If you call idevice_id with
    an invalid parameter or no device is attached, it still returns a 0.
    I'm going to keep this return code != 0 in here for now in case they fix
    in the future. The work around is to test the length for retval and if it is
    41, then we have a UDID returned!
    */
    if (retval.length === 41) {
      // found a valid udid so return null error and uuid value
      // first let's make this a string and trim any newlines
      const udid_str = String.fromCharCode.apply(null, retval);
      logger.info("Authorized iDevice found, UDID: %s", udid_str.trim());
      callback(null, udid_str.trim());
    } else {
      // encountered some sort of error. If 0 len then no device attached, otherwise something else
      if (retval.length === 0) {
        return callback(new Error("No authorized iDevice found. Plug in and authorize a device first."));
      } else {
        return callback(new Error(retval));
      };
    };
  });
};

function getDeviceSyslog(udid, wd, syslogTimeout) {

  const file_name = 'syslog.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  let userTimeout = 0;
  // check to see if user specified a timeout
  if (syslogTimeout) {
    // syslog timeout was specified so run with that user setting
    // FIX: add check to make sure syslogTimeout is an int or catch the conversion error
    userTimeout = Number(syslogTimeout);
  };

  // execFile maxBuffer is set to 200k but I've overode it here to 5MB. I'll probably
  // need to change this call to exec or fork, need to research a little more
  // originally chose execFile so I could control the timeout...but we could also do
  // that in the calling function if we wanted.
  const opts = {
    timeout: userTimeout,
    maxBuffer: 5000*1024
  };

  // call idevicesyslog binary
  const idevicesyslog = child_process.execFile('idevicesyslog', [], opts );

  logger.info("capturing device syslog...");

  // on data events, write chunks to file
  idevicesyslog.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicesyslog.stdout.on('end', () => {
    file.end();
    logger.debug("in getDeviceSyslog, end event fired");
  });

  idevicesyslog.on('close', function(code) {
    if (code != 0) {
      logger.error("idevicesyslog returned error code " + code);
      // return callback(new Error('idevicesyslog returned error code ' + code));
    } else {
      logger.debug("in getDeviceSyslog, close event triggered without error");
      logger.info('iOS Device syslog saved');
      // callback(null, idevicesyslog);
    }
  });

  // for syslog, we call back immediately and return the childProcess so the calling program
  // has control over deciding when to kill the process. Could be immediately after other
  // extraction is complete or after a timeout value
  //callback(null, idevicesyslog);
  return(idevicesyslog);
};

function getDeviceInfo(udid, wd, callback) {

  const file_name = 'ideviceinfo.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceinfo binary
  const ideviceinfo = child_process.spawn('ideviceinfo', []);

  // on data events, write chunks to file
  ideviceinfo.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceinfo.stdout.on('end', () => {
    file.end();
    logger.info('iOS Device info saved');
    callback(null, ideviceinfo);
  });

  // should this event be on exit or on close?
  // per documentation, not all Streams emit a close event
  // https://nodejs.org/api/stream.html#stream_event_close
  ideviceinfo.on('close', function(code) {
    if (code != 0) {
      return callback(new Error('Error: ideviceinfo returned error code ' + code));
    }
  });
};

function getInstalledApps(udid, wd, callback) {

  const file_name = 'installed-apps.xml';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceinstaller binary
  const ideviceinstaller = child_process.spawn('ideviceinstaller', ['--list-apps', '-o','list_all', '-o', 'xml']);

  // on data events, write chunks to file
  ideviceinstaller.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceinstaller.stdout.on('end', () => {
    file.end();
    logger.info('iOS Device installed apps saved');
    callback(null, ideviceinstaller);
  });

  ideviceinstaller.on('close', function(code) {
    if (code != 0) {
      callback(new Error('ideviceinstaller returned error code ' + code));
    }
  });
};

function listProvisioningProfiles(udid, wd, callback) {

  const file_name = 'provisioning-profiles.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceprovision binary
  const ideviceprovision = child_process.spawn('ideviceprovision', ['list']);

  // on data events, write chunks to file
  ideviceprovision.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceprovision.stdout.on('end', () => {
    file.end();
    logger.info('Installed provisioning profiles saved');
    callback(null, ideviceprovision);
  });

  ideviceprovision.on('close', function(code) {
    if (code != 0) {
      callback(new Error('ideviceprovision returned error code ' + code));
    }
  });
};

function getCrashReports(udid, wd, callback) {

  // idevicecrashreport writes multiple files vs. returning to stdout
  // creating a directory to store this data and putting stdout into log file
  const wd_crashreports = wd + '/artifacts/crash_reports/';
  if (!fs.existsSync(wd_crashreports)){
    fs.mkdirSync(wd_crashreports);
  }

  const file_name = 'crashlogs.txt';
  const file = fs.createWriteStream(wd_crashreports + file_name);

  // call ideviceprovision binary
  const idevicecrashreport = child_process.spawn('idevicecrashreport', ['--extract', '--keep', wd_crashreports]);

  // on data events, write chunks to file
  idevicecrashreport.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicecrashreport.stdout.on('end', () => {
    file.end();
    logger.info('Crash reports and log saved');
    callback(null, idevicecrashreport);
  });

  idevicecrashreport.on('close', function(code) {
    if (code != 0) {
      callback(new Error('idevicecrashreport returned error code ' + code));
    }
  });
};

function doDeviceBackup(udid, wd, callback) {
  // idevicebackup2 backup --full .
  // idevicebackup2 writes many files and directories vs. returning to stdout
  // creating a directory to store this data and putting stdout into log file
  const wd_backup = wd + '/artifacts/backup/';
  if (!fs.existsSync(wd_backup)){
    fs.mkdirSync(wd_backup);
  }

  const file_name = 'backup_log.txt';
  const file = fs.createWriteStream(wd_backup + file_name);

  // call ideviceprovision binary
  const idevicebackup2 = child_process.spawn('idevicebackup2', ['backup', '--full', wd_backup]);

  // on data events, write chunks to file
  idevicebackup2.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicebackup2.stdout.on('end', () => {
    file.end();
    logger.info('Device backup and log saved');
    callback(null, idevicebackup2);
  });

  idevicebackup2.on('close', function(code) {
    if (code != 0) {
      callback(new Error('idevicebackup2 returned error code ' + code));
    }
  });
};

function processArtifacts () {
  logger.info("process artifacts");
}

function generateReport () {
  // hack for experimenting
  const installedAppsXML = "/Users/hiro/Desktop/ios-triage/993aa52471a3e6ea117eb619927d74f3aa7511bf/1484346254360/artifacts/installed-apps.xml";

  // read and parse plist file
  const obj = plist.parse(fs.readFileSync(installedAppsXML, 'utf8'));
  // console.log(JSON.stringify(obj));

  // setup object to represent installedApps
  const installedApps = {};
  installedApps.apps = [];

  for (let prop in obj) {
    // every prop in array is properties for an app
    const app = obj[prop];
    let appInfo = {}; //object to store individual app properties in
    for(let attrib in app) {
      switch(attrib) {
        case "CFBundleName":
          appInfo.name = app[attrib];
          break;
        case "CFBundleVersion":
          appInfo.version = app[attrib];
          break;
        case "CFBundleIdentifier":
          appInfo.bundleIdentifier = app[attrib];
          break;
        case "SignerIdentity":
          appInfo.signerIdentity = app[attrib];
          break;
        case "ApplicationType":
          appInfo.applicationType = app[attrib];
          break;
        default:
          // otherwise ignore property for now
          break;
      };
    // now push current appInfo into installedApps.apps array
      installedApps.apps.push(appInfo);
    };
    logger.debug("moving to next app");
  };
  console.log(JSON.stringify(installedApps));
};

<commit_msg>renamed collect -> extract added required directory to progress and report commands moved processing on installedApps XML into a separate function<commit_after>#!/usr/bin/env node
'use strict';

const program = require('commander');
const fs = require('fs');
const os = require('os');
const async = require('async');
const child_process = require('child_process');
const logger = require('./logger.js');
const plist = require('plist');
const path = require('path');

program
  .version('0.1.0')
  .description('Incident response tool for iPhone or iPad')
  .option('-o, --output [directory]', 'Set output directory')
  .option('-v, --verbose', 'Display verbose output')

program
  .command('extract')
  .description('Extract IR artifacts from iPhone or iPad')
  .option('-b, --backup', 'Backup iOS device')
  .option('--syslog-timeout <ms>', 'Optional timeout for how long to collect syslong, e.g. 86400 to collect for a day')
  .action(function(options) {
      extractArtifacts(options);
  });

program
  .command('process')
  .arguments('<dir>')
  .description('Process extracted artifacts in <dir>')
  .action(function(dir) {
    processArtifacts(dir);
  });

program
  .command('report')
  .arguments('<dir>')
  .description('Generate iOS IR reports from <dir>')
  .action(function(dir) {
    generateReport(dir);
  });

program.parse(process.argv);

// if program was called with no arguments, show help.
if (program.args.length === 0) program.help();

function setWorkingDirectory (userOutputDir, udid, currentEpoch) {
  let wd = ""
  if (userOutputDir) {
    wd = userOutputDir;
  } else {
    wd = __dirname;
  }

  // need to move away from "/" and start using path.sep
  const wd_udid = wd + "/" + udid;
  const wd_udid_epoch = wd_udid + '/' + currentEpoch;

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

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

  if (!fs.existsSync(wd_udid_epoch + '/artifacts')){
    fs.mkdirSync(wd_udid_epoch + '/artifacts');
  }

  logger.info("output directory set to %s", wd_udid_epoch);
  return(wd_udid_epoch);
}

function extractArtifacts(options) {
  // let's first get the UDID...if we can't do this successfully, we have a problem
  getUDID(function (error, udid) {
    if (error) {
      return logger.error(error);
    }

    // no error getting UDID so time to fetch data
    // first we'll setup the working directory, saving data in unique dir each time based on epoch time
    const currentEpoch = new Date().getTime();
    const wd = setWorkingDirectory(program.output, udid, currentEpoch);

    const idevicesyslog = getDeviceSyslog(udid, wd, options.syslogTimeout);

    async.parallel({
      backup: function(callback) {
        if (options.backup) {
          doDeviceBackup(udid, wd, callback);
        } else {
          logger.info("Skipping device backup");
          // this callback() iw critical so async.parallel can returm
          callback();
        }
      },
      deviceInfo: function(callback) {
        getDeviceInfo(udid, wd, callback);
      },
      installedApps: function(callback) {
        getInstalledApps(udid, wd, callback);
      },
      provisioningProfiles: function(callback) {
        listProvisioningProfiles(udid, wd, callback);
      },
      crashReports: function(callback) {
        getCrashReports(udid, wd, callback);
      }
    }, function(err, results) {
      //handle any errors from extraction functions
      if(options.syslogTimeout === undefined) {
        logger.info("completed all extraction functions so we'll now kill deviceSyslog");
        idevicesyslog.kill('SIGINT');
      } else {
        logger.info("waiting %d ms for syslog to execute", options.syslogTimeout);
      };
    });

  });
};

function getUDID (callback) {
  var retval = '';
  const udid = child_process.spawn('idevice_id', ['-l']);

  udid.stdout.on('data', (chunk) => {
    // FIXME: if idevice_id fires the data event more than once the this would overwrite
    // retval which is likley problematic
    retval = chunk;
  });

  udid.on('close', code => {
    /*
    Unfortunately idevice_id returns a 0 in all situations I checked
    which differs from how ideviceinfo works. If you call idevice_id with
    an invalid parameter or no device is attached, it still returns a 0.
    I'm going to keep this return code != 0 in here for now in case they fix
    in the future. The work around is to test the length for retval and if it is
    41, then we have a UDID returned!
    */
    if (retval.length === 41) {
      // found a valid udid so return null error and uuid value
      // first let's make this a string and trim any newlines
      const udid_str = String.fromCharCode.apply(null, retval);
      logger.info("Authorized iDevice found, UDID: %s", udid_str.trim());
      callback(null, udid_str.trim());
    } else {
      // encountered some sort of error. If 0 len then no device attached, otherwise something else
      if (retval.length === 0) {
        return callback(new Error("No authorized iDevice found. Plug in and authorize a device first."));
      } else {
        return callback(new Error(retval));
      };
    };
  });
};

function getDeviceSyslog(udid, wd, syslogTimeout) {

  const file_name = 'syslog.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  let userTimeout = 0;
  // check to see if user specified a timeout
  if (syslogTimeout) {
    // syslog timeout was specified so run with that user setting
    // FIX: add check to make sure syslogTimeout is an int or catch the conversion error
    userTimeout = Number(syslogTimeout);
  };

  // execFile maxBuffer is set to 200k but I've overode it here to 5MB. I'll probably
  // need to change this call to exec or fork, need to research a little more
  // originally chose execFile so I could control the timeout...but we could also do
  // that in the calling function if we wanted.
  const opts = {
    timeout: userTimeout,
    maxBuffer: 5000*1024
  };

  // call idevicesyslog binary
  const idevicesyslog = child_process.execFile('idevicesyslog', [], opts );

  logger.info("capturing device syslog...");

  // on data events, write chunks to file
  idevicesyslog.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicesyslog.stdout.on('end', () => {
    file.end();
    logger.debug("in getDeviceSyslog, end event fired");
  });

  idevicesyslog.on('close', function(code) {
    if (code != 0) {
      logger.error("idevicesyslog returned error code " + code);
      // return callback(new Error('idevicesyslog returned error code ' + code));
    } else {
      logger.debug("in getDeviceSyslog, close event triggered without error");
      logger.info('iOS Device syslog saved');
      // callback(null, idevicesyslog);
    }
  });

  // for syslog, we call back immediately and return the childProcess so the calling program
  // has control over deciding when to kill the process. Could be immediately after other
  // extraction is complete or after a timeout value
  //callback(null, idevicesyslog);
  return(idevicesyslog);
};

function getDeviceInfo(udid, wd, callback) {

  const file_name = 'ideviceinfo.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceinfo binary
  const ideviceinfo = child_process.spawn('ideviceinfo', []);

  // on data events, write chunks to file
  ideviceinfo.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceinfo.stdout.on('end', () => {
    file.end();
    logger.info('iOS Device info saved');
    callback(null, ideviceinfo);
  });

  // should this event be on exit or on close?
  // per documentation, not all Streams emit a close event
  // https://nodejs.org/api/stream.html#stream_event_close
  ideviceinfo.on('close', function(code) {
    if (code != 0) {
      return callback(new Error('Error: ideviceinfo returned error code ' + code));
    }
  });
};

function getInstalledApps(udid, wd, callback) {

  const file_name = 'installed-apps.xml';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceinstaller binary
  const ideviceinstaller = child_process.spawn('ideviceinstaller', ['--list-apps', '-o','list_all', '-o', 'xml']);

  // on data events, write chunks to file
  ideviceinstaller.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceinstaller.stdout.on('end', () => {
    file.end();
    logger.info('iOS Device installed apps saved');
    callback(null, ideviceinstaller);
  });

  ideviceinstaller.on('close', function(code) {
    if (code != 0) {
      callback(new Error('ideviceinstaller returned error code ' + code));
    }
  });
};

function listProvisioningProfiles(udid, wd, callback) {

  const file_name = 'provisioning-profiles.txt';
  const file = fs.createWriteStream(wd + '/artifacts/' + file_name);

  // call ideviceprovision binary
  const ideviceprovision = child_process.spawn('ideviceprovision', ['list']);

  // on data events, write chunks to file
  ideviceprovision.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  ideviceprovision.stdout.on('end', () => {
    file.end();
    logger.info('Installed provisioning profiles saved');
    callback(null, ideviceprovision);
  });

  ideviceprovision.on('close', function(code) {
    if (code != 0) {
      callback(new Error('ideviceprovision returned error code ' + code));
    }
  });
};

function getCrashReports(udid, wd, callback) {

  // idevicecrashreport writes multiple files vs. returning to stdout
  // creating a directory to store this data and putting stdout into log file
  const wd_crashreports = wd + '/artifacts/crash_reports/';
  if (!fs.existsSync(wd_crashreports)){
    fs.mkdirSync(wd_crashreports);
  }

  const file_name = 'crashlogs.txt';
  const file = fs.createWriteStream(wd_crashreports + file_name);

  // call ideviceprovision binary
  const idevicecrashreport = child_process.spawn('idevicecrashreport', ['--extract', '--keep', wd_crashreports]);

  // on data events, write chunks to file
  idevicecrashreport.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicecrashreport.stdout.on('end', () => {
    file.end();
    logger.info('Crash reports and log saved');
    callback(null, idevicecrashreport);
  });

  idevicecrashreport.on('close', function(code) {
    if (code != 0) {
      callback(new Error('idevicecrashreport returned error code ' + code));
    }
  });
};

function doDeviceBackup(udid, wd, callback) {
  // idevicebackup2 backup --full .
  // idevicebackup2 writes many files and directories vs. returning to stdout
  // creating a directory to store this data and putting stdout into log file
  const wd_backup = wd + '/artifacts/backup/';
  if (!fs.existsSync(wd_backup)){
    fs.mkdirSync(wd_backup);
  }

  const file_name = 'backup_log.txt';
  const file = fs.createWriteStream(wd_backup + file_name);

  // call ideviceprovision binary
  const idevicebackup2 = child_process.spawn('idevicebackup2', ['backup', '--full', wd_backup]);

  // on data events, write chunks to file
  idevicebackup2.stdout.on('data', (chunk) => {
    file.write(chunk);
  });

  // after Stream ends, close the file, inform user of saved file
  idevicebackup2.stdout.on('end', () => {
    file.end();
    logger.info('Device backup and log saved');
    callback(null, idevicebackup2);
  });

  idevicebackup2.on('close', function(code) {
    if (code != 0) {
      callback(new Error('idevicebackup2 returned error code ' + code));
    }
  });
};

function processArtifacts(dir) {
  //logger.info("process artifacts in %s", dir);

  const artifactPath = dir + path.sep + 'artifacts';
  const installedAppsXML = artifactPath + path.sep + 'installed-apps.xml';

  fs.stat(installedAppsXML, function(err, stat) {
    if(!err) {
      processInstalledAppsXML(installedAppsXML, function(err, installedApps) {
        if(!err) {
         console.log(JSON.stringify(installedApps));
        } else {
          logger.error("error processing installed apps: %s", err);
        };
      });
    } else {
        logger.warn("Could not read installed apps artifact. %s", err);
    };
  });

};

function processInstalledAppsXML(installedAppsXML, callback) {
  // hack for experimenting
  // const installedAppsXML = "/Users/hiro/Desktop/ios-triage/993aa52471a3e6ea117eb619927d74f3aa7511bf/1484346254360/artifacts/installed-apps.xml";

  // read and parse plist file
  const obj = plist.parse(fs.readFileSync(installedAppsXML, 'utf8'));
  // console.log(JSON.stringify(obj));

  // setup object to represent installedApps
  const installedApps = {};
  installedApps.apps = [];

  for (let prop in obj) {
    // every prop in array is properties for an app
    const app = obj[prop];
    let appInfo = {}; //object to store individual app properties in
    for(let attrib in app) {
      switch(attrib) {
        case "CFBundleName":
          appInfo.name = app[attrib];
          break;
        case "CFBundleVersion":
          appInfo.version = app[attrib];
          break;
        case "CFBundleIdentifier":
          appInfo.bundleIdentifier = app[attrib];
          break;
        case "SignerIdentity":
          appInfo.signerIdentity = app[attrib];
          break;
        case "ApplicationType":
          appInfo.applicationType = app[attrib];
          break;
        default:
          // otherwise ignore property for now
          break;
      };
    // now push current appInfo into installedApps.apps array
      installedApps.apps.push(appInfo);
    };
    // logger.debug("moving to next app");
  };
  // console.log(JSON.stringify(installedApps));
  callback(null, installedApps);
};

function generateReport(dir) {
  logger.info("generate report for processed data in %s", dir);
};

<|endoftext|>


<commit_before>const io = require("./io")
const diviner = require("./diviner")
const cut = require("./cut")
const reduce = require("./reduce")

io.write("learn_and_teach.out.txt", reduce(cut(io.read("learn_and_teach.in.txt")).map(diviner)));
<commit_msg>add blackbylines<commit_after>const io = require("./io")
const diviner = require("./diviner")
const cut = require("./cut")
const reduce = require("./reduce")
const pm = require("./black")

io.write("logo.out.txt", reduce(cut(io.read("logo.in.txt")).map(diviner)));
<|endoftext|>


<commit_before>'use strict';

module.exports = builder;

// ## Usage
// ```js
// builder(options)
// .on('warn', function () {
// })
// .parse(filename, callback);
// ```
function builder(entry, options, callback) {
  make_sure(options, 'pkg');
  make_sure(options, 'cwd');
  new Builder(options || {}).parse(entry, callback);
}

function make_sure (options, key) {
  if (key in options) {
    return;
  }

  throw new Error('`options.' + key + '` must be defined');
}

builder.Builder = Builder;

var fs = require('fs');
var node_path = require('path');
var util = require('util');
var async = require('async');
var _ = require('underscore');
var EE = require('events').EventEmitter;
var walker = require('commonjs-walker');
var make_array = require('make-array');
var mix = require('mix2');

function Builder(options) {
  var self = this;
  this._uuid = 0;
  this.options = options;
  this.cwd = node_path.resolve(options.cwd);
  this.pkg = options.pkg;
  this.locals = {};
  this.compilers = [];
  this.global_map = {};
};

util.inherits(Builder, EE);

Builder.prototype.parse = function(filename, callback) {
  var self = this;
  var resolved = {};
  var pkg = this.pkg;
  var locals = this.locals;

  async.waterfall([
    function(done) {
      self._get_dependency_tree(filename, done);
    },
    function(nodes, done) {
      self._collect_modules(nodes, done);
    },
    function(codes, done) { console.log(codes);
      self._generate_code(codes, done);
    }
  ], callback);
};

// Gets the dependency tree from the entry file
// @param {String} filename
// @param {function(err, nodes)} callback
Builder.prototype._get_dependency_tree = function(filename, callback) {
  var self = this;
  walker(filename, {
    allow_cyclic: true,
    check_require_length: true,
    allow_absolute_path: false,
    extensions: ['.js', '.json'],
    require_resolve: true,
    require_async: true

  }, function(err, nodes) {
    if (err) {
      return callback(err);
    }

    self.nodes = nodes;
    callback(null, nodes);
  })
  .on('warn', function(message) {
    self.emit('warn', message);
  });
};

// Collect all modules which should be bundled into one file
// @param {function(err, codes)} callback
// - codes `Object` the `{<path>: <parsed-module>}` map
Builder.prototype._collect_modules = function(nodes, callback) {
  var codes = {};
  var errmsg = '';
  var id;
  var mod
  for (id in nodes) {
    mod = nodes[id];
    if (mod.foreign) {
      continue;
    }

    try {
      mod.resolved = this._resolve_module_dependencies(id, mod);
    } catch (e) {
      if (e.code == 'ENOTINSTALLED') {
        errmsg = 'Explicit version of dependency <%= deps.map(function(dep){return dep}).join(", ") %> <%= deps.length > 1 ? "are" : "is" %> not defined in package.json.\n Use "cortex install <%= deps.join(" ") %> --save". file: <%= file %>';
      } else if (e.code == 'EOUTENTRY') {
        errmsg = 'Relative dependency "<%= deps[0] %>" out of main entry\'s directory. file: <%= file %>';
      } else {
        errmsg = e.message;
      }
      e.file = id;
      return callback(new Error(_.template(errmsg)(e)));
    }

    codes[id] = mod;
  }

  callback(null, codes);
};

// @param {String} id Path(file entry) or package name(foreign package)
Builder.prototype._resolve_module_dependencies = function(id, mod) {
  var self = this;
  var pkg = this.pkg;
  var cwd = this.cwd;
  var deps = mod.dependencies;
  var resolved = {};

  ['require', 'resolve', 'async'].forEach(function (key) {
    this._resolve_dependencies(id, mod, mod[key], resolved);
  }, this);

  return resolved;
};

// @param {*Object} resolved
Builder.prototype._resolve_dependencies = function(id, mod, deps, resolved) {
  var module_name;
  var r;
  var real;
  var not_installed = [];

  for (module_name in deps) {
    real = deps[module_name];

    if (this._is_foreign(real)) {
      // check dependency versions and apply
      // 'jquery' -> 'jquery@^1.9.2'
      r = this._apply_dependency_version(real);

      if (!r) {
        not_installed.push(real);
      }

    } else {
      if (this._out_of_dir(module_name, id)) {
        throw {
          code: 'EOUTENTRY',
          deps: [module_name]
        };
      }
      r = this._generate_module_id(real);
    }

    resolved[module_name] = r;
    this._add_locals(r);
  }

  if (not_installed.length) {
    throw {
      code: 'ENOTINSTALLED',
      deps: not_installed
    }
  }
};

var CODE_TEMPLATE =
  ';(function(){\n' +
    'function mix(a, b){ for(var k in b) { a[k]=b[k]; } return a; }\n' +
    '<%= variables %>' +
    '<%= code %>\n' +
  '})();';

Builder.prototype._generate_code = function(codes, callback) {
  var self = this;
  var locals = this.locals;
  var code = _.keys(codes).map(function(id) {
    var mod = codes[id];
    return self._wrap(id, mod);

  }).join('\n\n');

  var statements = [];

  function declare_varible(name, value, raw) {
    var statement = 'var ' + name + ' = ' + (raw ? value : JSON.stringify(value)) + ';\n';
    if (value) {
      statements.push(statement);
    }
  }

  _.keys(locals).forEach(function(v) {
    declare_varible(locals[v], v);
  });

  ['entries', 'asyncDeps', 'async_deps_to_mix'].forEach(function(key) {
    var value = self[key];
    (key == 'async_deps_to_mix' || value.length) && declare_varible(key, self._to_locals(value), true);
  });
  declare_varible(
    'global_map',
    _.keys(self.global_map).length
      ? 'mix(' + self._to_locals(self.global_map) + ',async_deps_to_mix)'
      : 'async_deps_to_mix', true
  );

  code = _.template(CODE_TEMPLATE)({
    variables: variables.join(''),
    code: code
  });

  callback(null, code);
};

var WRAPPING_TEMPLATE =
    'define(<%= id %>, <%= deps %>, function(require, exports, module, __filename, __dirname) {\n'
  +   '<%= code %>\n'
  + '}<%= module_options ? ", " + module_options : "" %>);';

// Wrap a commonjs module with wrappings so that it could run in browsers
Builder.prototype._wrap = function(filename, mod, callback) {
  // id
  var module_id = this._generate_module_id(filename);

  // dependencies
  var resolved_dependencies = _.keys(mod.require).map(function (dep) {
    return mod.resolved[dep] || dep;
  });

  // options
  var module_options = this._generateModuleOptions(id, mod);

  var pairs = [];
  var key;
  var value;
  for (key in module_options) {
    var value = module_options[key];
    value = ({
      'map': _.keys(value).length ? ('mix(' + self._to_locals(value) + ',global_map)') : 'global_map',
      'main': 'true'
    })[key];

    pairs.push(key + ':' + value);
  }

  module_options = pairs.length ? ('{\n\t' + pairs.join(',\n\t') + '\n}').replace(/\t/g, '    ') : '';

  var self = this;
  this._get_compiled_content(filename, function (err, content) {
    if (err) {
      return callback(err);
    }

    var result = _.template(WRAPPING_TEMPLATE)({
      id: self._to_locals(module_id),
      deps: self._to_locals(resolved_dependencies),
      code: content,
      module_options: module_options
    });

    callback(null, result);
  });
};

Builder.prototype._get_compiled_content = function(filename, callback) {
  var self = this;
  this._get_content(filename, function (err, content) {
    if (err) {
      return callback(err);
    }

    self._compile(filename, content, callback);
  });
};

Builder.prototype._get_content = function(filename, callback) {
  fs.readFile(filename, function (err, content) {
    callback(err, content && content.toString());
  });
};

// @param {string|RegExp} pattern
// @param {Object|Array.<Object>} new_compilers
// - compiler: `function(content, options, callback)`
// - options:
// - pattern:
Builder.prototype.register = function(pattern, new_compilers) {
  new_compilers = make_array(new_compilers);

  var compilers = this.compilers;
  new_compilers.forEach(function (c) {
    c.pattern = util.isRegExp(c.pattern)
      ? c.pattern
      : new RegExp(c.pattern);

    compilers.push(c);
  });

  return this;
};

// Applies all compilers to process the file content
Builder.prototype._compile = function(filename, content, callback) {
  var tasks = this.compilers.filter(function (c) {
    return c.pattern.test(filename);

  }).reduce(function (c, i) {
    return function (content, done) {
      var options = mix({
        // adds `filename` to options of each compiler
        filename: filename

      }, c.options, false);
      c.compiler(content, options, done);
    };

  }, [init]);

  // If no registered compilers, just return
  function init (done) {
    done(null, content);
  }

  async.waterfall(tasks, callback);
};

// filename: '/path/to/a.js'
// cwd: '/path'
// -> 'module@0.0.1/to/a.js'
Builder.prototype._generate_module_id = function(filename, relative) {
  // the exact identifier
  var cwd = this.cwd;
  var pkg = this.pkg;
  var main_id = [pkg.name, pkg.version].join('@');

  var relative_path = relative
    ? filename
    : node_path.relative(cwd, filename);

  // -> 'module@0.0.1/folder/foo'
  var id = node_path.join(main_id, relative_path);

  // fixes windows paths
  id = id
    .replace(new RegExp('\\' + node_path.sep, 'g'), '/');
    .toLowerCase();

  this._add_locals(id);
  return id;
};

Builder.prototype._is_foreign = function(str) {
  var isWindowsAbsolute = str.match(/^\w+:\\/);
  var isRelative = ['../', './'].some(function(prefix) {
    return str.indexOf(prefix) === 0;
  });
  var isUnixAbsolute = str.indexOf('/') == 0;
  return !isRelative && !isUnixAbsolute && !isWindowsAbsolute;
};

Builder.prototype._out_of_dir = function(dep, file) {
  var mod_path = node_path.resolve(node_path.join(node_path.dirname(file), dep));
  return mod_path.indexOf(this.cwd) == -1;
};

Builder.prototype._generateModuleOptions = function(id, mod) {
  var self = this;
  var pkg = this.pkg;
  var cwd = this.cwd;
  var asyncDeps = this.asyncDeps;
  var module_options = {};
  if (asyncDeps.length) {
    module_options.asyncDeps = true;
  }

  if (entries.length) {
    module_options.entries = true;
  }

  if (pkg.main && mod.entry && node_path.resolve(id) === node_path.resolve(cwd, pkg.main)) {
    module_options.main = true;
  }

  var map = this._generateMap(id, mod);
  module_options.map = map;

  return _.keys(module_options).length ? module_options : null;
};

Builder.prototype._generateMap = function(id, mod) {
  var self = this;
  var resolved = mod.resolved;
  var dependencies = mod.dependencies;
  var resolvedDeps = _.keys(resolved);
  var map = {};
  var nodes = this.nodes;
  var as = this.pkg.as || {};
  resolvedDeps.forEach(function(dep) {
    // to lower cases
    // resolve dir
    var result;
    var realDependency = dependencies[dep];

    if (!self._is_foreign(realDependency)) {
      result = realDependency.toLowerCase();
      result = self._generate_module_id(realDependency);
    } else if (as[dep]) {
      result = self._apply_dependency_version(realDependency);
      self.global_map[realDependency] = result;
    }

    if (result) {
      map[dep] = result;
      self._add_locals(result);
    }
  });
  return map;
};

Builder.prototype._apply_dependency_version = function(module_name) {
  var pkg = this.pkg;
  var deps = ['dependencies', 'asyncDependencies', 'devDependencies'];
  for (var i = 0; i < deps.length; i++) {
    var dep = deps[i];
    if (pkg[dep] && pkg[dep][module_name]) {
      return module_name + '@' + pkg[dep][module_name];
    }
  }
  return false;
};

// {
//   '/path/to/a.js': '_0',
//   '/path/to/b.js': '_1'
// }
Builder.prototype._add_locals = function(val) {
  var locals = this.locals;
  if (!locals[val]) {
    locals[val] = '_' + this._uuid ++;
  }
};

function not_null (subject) {
  return subject !== null;
}

Builder.prototype._to_locals = function(obj) {
  var locals = this.locals;

  function to_locals(item) {
    return locals[item] || null;
  }

  if (_.isString(obj)) {
    return to_locals(obj);
  }

  if (_.isArray(obj)) {
    return '[' + obj.map(to_locals).filter(notNull).join(',') + ']'
  };

  if (_.isObject(obj)) {
    return '{' + _.keys(obj).map(function(k) {
      var value = to_locals(obj[k]);
      return value ? ('"' + k + '"' + ':' + value) : null
    }).filter(notNull).join(',') + '}';
  }
};
<commit_msg>#31: in progress<commit_after>'use strict';

module.exports = builder;

// ## Usage
// ```js
// builder(options)
// .on('warn', function () {
// })
// .parse(filename, callback);
// ```
function builder(entry, options, callback) {
  make_sure(options, 'pkg');
  make_sure(options, 'cwd');
  new Builder(options || {}).parse(entry, callback);
}

function make_sure (options, key) {
  if (key in options) {
    return;
  }

  throw new Error('`options.' + key + '` must be defined');
}

builder.Builder = Builder;

var fs = require('fs');
var node_path = require('path');
var util = require('util');
var async = require('async');
var _ = require('underscore');
var EE = require('events').EventEmitter;
var walker = require('commonjs-walker');
var make_array = require('make-array');
var mix = require('mix2');

function Builder(options) {
  var self = this;
  this._uuid = 0;
  this.options = options;
  this.cwd = node_path.resolve(options.cwd);
  this.pkg = options.pkg;
  this.locals = {};
  this.compilers = [];
  this.global_map = {};
};

util.inherits(Builder, EE);

Builder.prototype.parse = function(filename, callback) {
  var self = this;
  var resolved = {};
  var pkg = this.pkg;
  var locals = this.locals;

  async.waterfall([
    function(done) {
      self._get_dependency_tree(filename, done);
    },
    function(nodes, done) {
      self._collect_modules(nodes, done);
    },
    function(codes, done) { console.log(codes);
      self._generate_code(codes, done);
    }
  ], callback);
};

// Gets the dependency tree from the entry file
// @param {String} filename
// @param {function(err, nodes)} callback
Builder.prototype._get_dependency_tree = function(filename, callback) {
  var self = this;
  walker(filename, {
    allow_cyclic: true,
    check_require_length: true,
    allow_absolute_path: false,
    extensions: ['.js', '.json'],
    require_resolve: true,
    require_async: true

  }, function(err, nodes) {
    if (err) {
      return callback(err);
    }

    self.nodes = nodes;
    callback(null, nodes);
  })
  .on('warn', function(message) {
    self.emit('warn', message);
  });
};

// Collect all modules which should be bundled into one file
// @param {function(err, codes)} callback
// - codes `Object` the `{<path>: <parsed-module>}` map
Builder.prototype._collect_modules = function(nodes, callback) {
  var codes = {};
  var errmsg = '';
  var id;
  var mod
  for (id in nodes) {
    mod = nodes[id];
    if (mod.foreign) {
      continue;
    }

    try {
      mod.resolved = this._resolve_module_dependencies(id, mod);
    } catch (e) {
      if (e.code == 'ENOTINSTALLED') {
        errmsg = 'Explicit version of dependency <%= deps.map(function(dep){return dep}).join(", ") %> <%= deps.length > 1 ? "are" : "is" %> not defined in package.json.\n Use "cortex install <%= deps.join(" ") %> --save". file: <%= file %>';
      } else if (e.code == 'EOUTENTRY') {
        errmsg = 'Relative dependency "<%= deps[0] %>" out of main entry\'s directory. file: <%= file %>';
      } else {
        errmsg = e.message;
      }
      e.file = id;
      return callback(new Error(_.template(errmsg)(e)));
    }

    codes[id] = mod;
  }

  callback(null, codes);
};

// @param {String} id Path(file entry) or package name(foreign package)
Builder.prototype._resolve_module_dependencies = function(id, mod) {
  var self = this;
  var pkg = this.pkg;
  var cwd = this.cwd;
  var deps = mod.dependencies;
  var resolved = {};

  ['require', 'resolve', 'async'].forEach(function (key) {
    this._resolve_dependencies(id, mod, mod[key], resolved);
  }, this);

  return resolved;
};

// @param {*Object} resolved
Builder.prototype._resolve_dependencies = function(id, mod, deps, resolved) {
  var module_name;
  var r;
  var real;
  var not_installed = [];

  for (module_name in deps) {
    real = deps[module_name];

    if (this._is_foreign(real)) {
      // check dependency versions and apply
      // 'jquery' -> 'jquery@^1.9.2'
      r = this._apply_dependency_version(real);

      if (!r) {
        not_installed.push(real);
      }

    } else {
      if (this._out_of_dir(module_name, id)) {
        throw {
          code: 'EOUTENTRY',
          deps: [module_name]
        };
      }
      r = this._generate_module_id(real);
    }

    resolved[module_name] = r;
    this._add_locals(r);
  }

  if (not_installed.length) {
    throw {
      code: 'ENOTINSTALLED',
      deps: not_installed
    }
  }
};

var CODE_TEMPLATE = [
  ';(function(){'         ,
  ''                      ,
  'function mix(a, b){'   ,
  '  for(var k in b) {'   ,
  '    a[k] = b[k];'      ,
  '  }'                   ,
  '  return a;'           ,
  '}'                     ,
  '<%= variables %>'      ,
  '<%= code %>'           ,
  ''                      ,
  '})();'

].join('\n');

Builder.prototype._generate_code = function(codes, callback) {
  var self = this;
  var locals = this.locals;
  var code = _.keys(codes).map(function(id) {
    var mod = codes[id];
    return self._wrap(id, mod);

  }).join('\n\n');

  var statements = [];
  function declare_varible(name, value, raw) {
    var statement = 'var ' + name + ' = ' + (raw ? value : JSON.stringify(value)) + ';';
    if (value) {
      statements.push(statement);
    }
  }

  _.keys(locals).forEach(function(v) {
    declare_varible(locals[v], v);
  });

  // ['entries', 'asyncDeps', 'async_deps_to_mix'].forEach(function(key) {
  //   var value = self[key];
  //   (key == 'async_deps_to_mix' || value.length) && declare_varible(key, self._to_locals(value), true);
  // });

  // declare_varible(
  //   'global_map',
  //   _.keys(self.global_map).length
  //     ? 'mix(' + self._to_locals(self.global_map) + ',async_deps_to_mix)'
  //     : 'async_deps_to_mix', true
  // );

  code = _.template(CODE_TEMPLATE)({
    variables: statements.join('\n'),
    code: code
  });

  callback(null, code);
};

var WRAPPING_TEMPLATE =
    'define(<%= id %>, <%= deps %>, function(require, exports, module, __filename, __dirname) {\n'
  +   '<%= code %>\n'
  + '}<%= module_options ? ", " + module_options : "" %>);';

// Wrap a commonjs module with wrappings so that it could run in browsers
Builder.prototype._wrap = function(filename, mod, callback) {
  // id
  var module_id = this._generate_module_id(filename);

  // dependencies
  var resolved_dependencies = _.keys(mod.require).map(function (dep) {
    return mod.resolved[dep] || dep;
  });

  // options
  var module_options = this._generate_module_options(id, mod);

  var pairs = [];
  var key;
  var value;
  for (key in module_options) {
    var value = module_options[key];
    value = ({
      'map': _.keys(value).length ? ('mix(' + self._to_locals(value) + ', global_map)') : 'global_map',
      'main': 'true'
    })[key];

    pairs.push(key + ':' + value);
  }

  module_options = pairs.length
    ? '{\n'
      + '  ' + pairs.join(',\n  ')
      + '\n}'

    : '';

  var self = this;
  this._get_compiled_content(filename, function (err, content) {
    if (err) {
      return callback(err);
    }

    var result = _.template(WRAPPING_TEMPLATE)({
      id: self._to_locals(module_id),
      deps: self._to_locals(resolved_dependencies),
      code: content,
      module_options: module_options
    });

    callback(null, result);
  });
};

Builder.prototype._get_compiled_content = function(filename, callback) {
  var self = this;
  this._get_content(filename, function (err, content) {
    if (err) {
      return callback(err);
    }

    self._compile(filename, content, callback);
  });
};

Builder.prototype._get_content = function(filename, callback) {
  fs.readFile(filename, function (err, content) {
    callback(err, content && content.toString());
  });
};

// @param {string|RegExp} pattern
// @param {Object|Array.<Object>} new_compilers
// - compiler: `function(content, options, callback)`
// - options:
// - pattern:
Builder.prototype.register = function(pattern, new_compilers) {
  new_compilers = make_array(new_compilers);

  var compilers = this.compilers;
  new_compilers.forEach(function (c) {
    c.pattern = util.isRegExp(c.pattern)
      ? c.pattern
      : new RegExp(c.pattern);

    compilers.push(c);
  });

  return this;
};

// Applies all compilers to process the file content
Builder.prototype._compile = function(filename, content, callback) {
  var tasks = this.compilers.filter(function (c) {
    return c.pattern.test(filename);

  }).reduce(function (c, i) {
    return function (content, done) {
      var options = mix({
        // adds `filename` to options of each compiler
        filename: filename

      }, c.options, false);
      c.compiler(content, options, done);
    };

  }, [init]);

  // If no registered compilers, just return
  function init (done) {
    done(null, content);
  }

  async.waterfall(tasks, callback);
};

// filename: '/path/to/a.js'
// cwd: '/path'
// -> 'module@0.0.1/to/a.js'
Builder.prototype._generate_module_id = function(filename, relative) {
  // the exact identifier
  var cwd = this.cwd;
  var pkg = this.pkg;
  var main_id = [pkg.name, pkg.version].join('@');

  var relative_path = relative
    ? filename
    : node_path.relative(cwd, filename);

  // -> 'module@0.0.1/folder/foo'
  var id = node_path.join(main_id, relative_path);

  // fixes windows paths
  id = id
    .replace(new RegExp('\\' + node_path.sep, 'g'), '/')
    .toLowerCase();

  this._add_locals(id);
  return id;
};

Builder.prototype._is_foreign = function(str) {
  var isWindowsAbsolute = str.match(/^\w+:\\/);
  var isRelative = ['../', './'].some(function(prefix) {
    return str.indexOf(prefix) === 0;
  });
  var isUnixAbsolute = str.indexOf('/') == 0;
  return !isRelative && !isUnixAbsolute && !isWindowsAbsolute;
};

Builder.prototype._out_of_dir = function(dep, file) {
  var mod_path = node_path.resolve(node_path.join(node_path.dirname(file), dep));
  return mod_path.indexOf(this.cwd) == -1;
};

// Returns `Object`
// - main: `Boolean`
// - map: `Object`
Builder.prototype._generate_module_options = function(id, mod) {
  var pkg = this.pkg;
  var cwd = this.cwd;
  var module_options = {};

  if (pkg.main && mod.entry && node_path.resolve(id) === node_path.resolve(cwd, pkg.main)) {
    module_options.main = true;
  }

  if (_.keys(mod.resolved).length) {
    module_options.map = mod.resolved;
  }

  return _.keys(module_options).length
    ? module_options
    : null;
};

Builder.prototype._apply_dependency_version = function(module_name) {
  var pkg = this.pkg;

  var module_id;
  ['dependencies', 'asyncDependencies', 'devDependencies'].some(function (key) {
    var dependencies = pkg[key];
    if (!dependencies) {
      return;
    }
    if (module_name in dependencies) {
      module_id = module_name + '@' + dependencies[module_name];
      return true;
    }
  });

  return module_id;
};

// {
//   '/path/to/a.js': '_0',
//   '/path/to/b.js': '_1'
// }
Builder.prototype._add_locals = function(val) {
  var locals = this.locals;
  if (!locals[val]) {
    locals[val] = '_' + this._uuid ++;
  }
};

function not_null (subject) {
  return subject !== null;
}

Builder.prototype._to_locals = function(obj) {
  var locals = this.locals;

  function to_locals(item) {
    return locals[item] || null;
  }

  if (_.isString(obj)) {
    return to_locals(obj);
  }

  if (_.isArray(obj)) {
    return '[' + obj.map(to_locals).filter(notNull).join(',') + ']'
  };

  if (_.isObject(obj)) {
    return '{' + _.keys(obj).map(function(k) {
      var value = to_locals(obj[k]);
      return value ? ('"' + k + '"' + ':' + value) : null
    }).filter(notNull).join(',') + '}';
  }
};
<|endoftext|>


<commit_before>/* *****************************************************************************
 * Caleydo - Visualization for Molecular Biology - http://caleydo.org
 * Copyright (c) The Caleydo Team. All rights reserved.
 * Licensed under the new BSD license, available at http://caleydo.org/license
 **************************************************************************** */

/**
 * generates and object that contain all modules in the src folder accessible as properties
 */

/**
 * magic file name for the pseudo root file
 * @type {string}
 */
var INDEX_FILE = './index.ts';
/**
 * sorts the given filename by name ensuring INDEX is the first one
 * @param a
 * @param b
 * @returns {number}
 */
function byName(a, b) {
  if (a === INDEX_FILE) {
    return a === b ? 0 : -1;
  }
  if (b === INDEX_FILE) {
    return 1;
  }
  return a.toLowerCase().localeCompare(b.toLowerCase());
}
// list all modules in the src folder excluding the one starting with _
var req = require.context('./src', true, /^\.\/(?!internal)(([^_][\w]+)|(\w+\/index))\.tsx?$/);

var files = req.keys().sort(byName);

// root file exists? else use anonymous root object
if (files[0] === INDEX_FILE) {
  module.exports = req(files.shift());
} else {
  module.exports = {};
}

// generate getter for all modules
files.forEach(function (f) {
  Object.defineProperty(module.exports, f.substring(2, f.lastIndexOf('/index.') > 0 ? f.lastIndexOf('/index.') : f.lastIndexOf('.')), {
    get: function () {
      return req(f);
    },
    enumerable: true
  });
});
<commit_msg>remove index.js<commit_after><|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//var Alexa = require('alexa-sdk');
//var http = require('http');
//var calDates = require("./cal-dates");

// global variables for reference
var alexa;  // alexa SDK
var APP_ID = "";    // @todo set
var skillName = "Seattle Public Schools Calendar";

// Various messages based on intents/events
var welcomeMsg = "You can ask if SPS is in session today. Search for school holidays by date";
var helpMsg = "Here are some things you can say: Is school in session today? Is there school on the 19th of March?";
var helpDescpMsg = "Here are some things you can say: Is there school today";
var noDataMsg = "There is no information found for that date. Would you like to search again?";
var shutdownMsg = "Okay see you later";

// Output for Alexa
var output = "";

// TODO create handler functions

/**
 * Denotes if given string is empty, null, undefined, or blank
 * @param {string} str
 * @returns {Boolean} denoting if empty or not
 */
function isEmpty(str) {
  return (!str || 0 === str.length || /^\s*$/.test(str));
}

/**
 * Converts ISO to CCYYMMDD, which is used as calendar event key in hashmap.
 * @param {Date} isoDate
 * @return {string} CCYYMMDD is converted ISO string
 */
function iso2key(isoDate) {
  var key = '';

  if (isEmpty(isoDate)) {
    return key;
  }

  var date = new Date(isoDate);
  if (isNaN(date)){
    return key;
  }

  key = date.toISOString().substring(0, 10).replace(/-/g, '');
  return key;
}

/**
 * Gets the current date and returns object of today
 * @return {Object} today that is {iso: string date, key: iso hashmapkey}
 */
function getToday() {
  var isoDate = new Date().toISOString();

  var today = {
    iso: isoDate,
    key: iso2key(isoDate)
  };

  return today;
}

/**
 * Converts a date.getDay() array index to String of the day
 * @param {Number} 0-6 of getDay() index
 * @return {string} represents day of the week
 */
function getDayStr(dayIndex) {
  if (dayIndex < 0 || dayIndex > 6) {
    return '';
  }
  if (isNaN(dayIndex)) {
    return '';
  }
  switch (dayIndex) {
    case 0: return 'Sunday';
    case 1: return 'Monday';
    case 2: return 'Tuesday';
    case 3: return 'Wednesday';
    case 4: return 'Thursday';
    case 5: return 'Friday';
    case 6: return 'Saturday';
    default: return '';
  }
}

/**
 * Converts a date.getMonth() array index to String of the month
 * @param {Number} 0-11 of getMonth() index
 * @return {string} represents month of a date
 */
function getMonthStr(monIndex) {
  if (monIndex < 0 || monIndex > 11) {
    return '';
  }
  if (isNaN(monIndex)) {
    return '';
  }
  switch (monIndex) {
    case 0: return 'January';
    case 1: return 'February';
    case 2: return 'March';
    case 3: return 'April';
    case 4: return 'May';
    case 5: return 'June';
    case 6: return 'July';
    case 7: return 'August';
    case 8: return 'September';
    case 9: return 'October';
    case 10: return 'November';
    case 11: return 'December';
    default: return '';
  }
}

/**
 * Converts an ISO date to date object for easy string conversation
 * @return {Object} date object represented
 */
function iso2obj(isoDate) {
  if (isEmpty(isoDate)) {
    return null;
  }

  var d = new Date(isoDate);
  if (isNaN(d)) {
    return null;
  }

  var dateObj = {
    day: getDayStr(d.getDay()),
    date: d.getDate(),
    month: getMonthStr(d.getMonth()),
    year: d.getFullYear()
  };

  return dateObj;
}

/**
 * Determines the ordinal for a given number
 * @param {Number} number to check ordinal for
 * @return {string} ordinal ex: st, nd, rd, or th
 */
function getOrdinal(num) {
  if (isNaN(num)) {
    return '';
  }

  num = Math.abs(num);

  if (num > 3 && num < 21) {
    return 'th';
  }

  switch (num % 10) {
    case 1: return 'st';
    case 2: return 'nd';
    case 3: return 'rd';
    default: return 'th';
  }
}

/**
 * Converts the iso date object to a string
 * @param {Object} iso date object
 * @return {string} Flatten object in string representation - ex: Tuesday the 12th of May 2017
 */
function isoObj2String(isoObj) {
  if (isoObj === undefined) {
    return '';
  }
  return isoObj.day + " the " + isoObj.date + getOrdinal(isoObj.date) + " of " + isoObj.month + " " + isoObj.year;
}

exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.appId = APP_ID;
  //alexa.registerHandlers(handlers); TODO create handlers
  alexa.execute();
};

<commit_msg>Switched to constants and fixed calendar require<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//var Alexa = require('alexa-sdk');
//var http = require('http');
const calDates = require("./cal-dates2016-2017");

// global variables for reference
var alexa;  // alexa SDK
const APP_ID = "";    // @todo set
const skillName = "Seattle Public Schools Calendar";

// Various messages based on intents/events
const welcomeMsg = "You can ask if SPS is in session today. Search for school holidays by date";
const helpMsg = "Here are some things you can say: Is school in session today? Is there school on the 19th of March?";
const helpDescpMsg = "Here are some things you can say: Is there school today";
const noDataMsg = "There is no information found for that date. Would you like to search again?";
const shutdownMsg = "Okay see you later";

// Output for Alexa
var output = "";

// TODO create handler functions

/**
 * Denotes if given string is empty, null, undefined, or blank
 * @param {string} str
 * @returns {Boolean} denoting if empty or not
 */
function isEmpty(str) {
  return (!str || 0 === str.length || /^\s*$/.test(str));
}

/**
 * Converts ISO to CCYYMMDD, which is used as calendar event key in hashmap.
 * @param {Date} isoDate
 * @return {string} CCYYMMDD is converted ISO string
 */
function iso2key(isoDate) {
  var key = '';

  if (isEmpty(isoDate)) {
    return key;
  }

  var date = new Date(isoDate);
  if (isNaN(date)){
    return key;
  }

  key = date.toISOString().substring(0, 10).replace(/-/g, '');
  return key;
}

/**
 * Gets the current date and returns object of today
 * @return {Object} today that is {iso: string date, key: iso hashmapkey}
 */
function getToday() {
  var isoDate = new Date().toISOString();

  var today = {
    iso: isoDate,
    key: iso2key(isoDate)
  };

  return today;
}

/**
 * Converts a date.getDay() array index to String of the day
 * @param {Number} 0-6 of getDay() index
 * @return {string} represents day of the week
 */
function getDayStr(dayIndex) {
  if (dayIndex < 0 || dayIndex > 6) {
    return '';
  }
  if (isNaN(dayIndex)) {
    return '';
  }
  switch (dayIndex) {
    case 0: return 'Sunday';
    case 1: return 'Monday';
    case 2: return 'Tuesday';
    case 3: return 'Wednesday';
    case 4: return 'Thursday';
    case 5: return 'Friday';
    case 6: return 'Saturday';
    default: return '';
  }
}

/**
 * Converts a date.getMonth() array index to String of the month
 * @param {Number} 0-11 of getMonth() index
 * @return {string} represents month of a date
 */
function getMonthStr(monIndex) {
  if (monIndex < 0 || monIndex > 11) {
    return '';
  }
  if (isNaN(monIndex)) {
    return '';
  }
  switch (monIndex) {
    case 0: return 'January';
    case 1: return 'February';
    case 2: return 'March';
    case 3: return 'April';
    case 4: return 'May';
    case 5: return 'June';
    case 6: return 'July';
    case 7: return 'August';
    case 8: return 'September';
    case 9: return 'October';
    case 10: return 'November';
    case 11: return 'December';
    default: return '';
  }
}

/**
 * Converts an ISO date to date object for easy string conversation
 * @return {Object} date object represented
 */
function iso2obj(isoDate) {
  if (isEmpty(isoDate)) {
    return null;
  }

  var d = new Date(isoDate);
  if (isNaN(d)) {
    return null;
  }

  var dateObj = {
    day: getDayStr(d.getDay()),
    date: d.getDate(),
    month: getMonthStr(d.getMonth()),
    year: d.getFullYear()
  };

  return dateObj;
}

/**
 * Determines the ordinal for a given number
 * @param {Number} number to check ordinal for
 * @return {string} ordinal ex: st, nd, rd, or th
 */
function getOrdinal(num) {
  if (isNaN(num)) {
    return '';
  }

  num = Math.abs(num);

  if (num > 3 && num < 21) {
    return 'th';
  }

  switch (num % 10) {
    case 1: return 'st';
    case 2: return 'nd';
    case 3: return 'rd';
    default: return 'th';
  }
}

/**
 * Converts the iso date object to a string
 * @param {Object} iso date object
 * @return {string} Flatten object in string representation - ex: Tuesday the 12th of May 2017
 */
function isoObj2String(isoObj) {
  if (isoObj === undefined) {
    return '';
  }
  return isoObj.day + " the " + isoObj.date + getOrdinal(isoObj.date) + " of " + isoObj.month + " " + isoObj.year;
}

exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.appId = APP_ID;
  //alexa.registerHandlers(handlers); TODO create handlers
  alexa.execute();
};

<|endoftext|>


<commit_before>var express = require('express'),
    rendr = require('rendr'),
    config = require('config'),
    mw = require('./server/middleware'),
    DataAdapter = require('./server/lib/data_adapter'),
    app;

app = express();

/**
 * Initialize Express middleware stack.
 */
function initMiddleware() {
  app.use(express.compress());
  app.use(express.static(__dirname + '/public'));
  app.use(express.logger());
  app.use(express.bodyParser());

  /**
   * Rendr provides its own instance of Express, for better encapsulation.
   * You could use it directly as your main app, but we find it's more flexible
   * to simply "mount" it as a sub-app onto another Express instance, which is
   * equivalent to just using it as middleware. This flexibility allows you to
   * mount your Rendr app at a certain path, or even host multiple, self-contained
   * Rendr apps in the same codebase with the same Express app.
   */
  app.use(initServer().expressApp);

  /**
   * Error handler goes last.
   */
  app.use(express.errorHandler());
}

/**
 * Initialize our Rendr server.
 *
 * We can pass inject various modules and options here to override
 * default behavior, i.e.:
 * - dataAdapter
 * - errorHandler
 * - appData
 */
function initServer() {
  var options = {
    dataAdapter: new DataAdapter(config.api),
    appData: config.rendrApp
  };
  return rendr.createServer(app, options);
}

/**
 * Start the Express server.
 */
function start() {
  var port = process.env.PORT || config.app.port;
  app.listen(port);
  console.log("server pid %s listening on port %s in %s mode",
    process.pid,
    port,
    app.settings.env);
}

/**
 * Here we actually initialize everything and start the Express server.
 */
initMiddleware();

/**
 * Only start server if this script is executed, not if it's require()'d.
 * This makes it easier to run integration tests on ephemeral ports.
 */
if (require.main === module) {
  start();
}

exports.app = app;
<commit_msg>Save a reference to the Rendr server<commit_after>var express = require('express'),
    rendr = require('rendr'),
    config = require('config'),
    mw = require('./server/middleware'),
    DataAdapter = require('./server/lib/data_adapter'),
    app;

app = express();

/**
 * Initialize Express middleware stack.
 */
function initMiddleware(rendrServer) {
  app.use(express.compress());
  app.use(express.static(__dirname + '/public'));
  app.use(express.logger());
  app.use(express.bodyParser());

  /**
   * Rendr provides its own instance of Express, for better encapsulation.
   * You could use it directly as your main app, but we find it's more flexible
   * to simply "mount" it as a sub-app onto another Express instance, which is
   * equivalent to just using it as middleware. This flexibility allows you to
   * mount your Rendr app at a certain path, or even host multiple, self-contained
   * Rendr apps in the same codebase with the same Express app.
   */
  app.use(rendrServer.expressApp);

  /**
   * Error handler goes last.
   */
  app.use(express.errorHandler());
}

/**
 * Initialize our Rendr server.
 *
 * We can pass inject various modules and options here to override
 * default behavior, i.e.:
 * - dataAdapter
 * - errorHandler
 * - appData
 */
function initServer() {
  var options = {
    dataAdapter: new DataAdapter(config.api),
    appData: config.rendrApp
  };
  return rendr.createServer(app, options);
}

/**
 * Start the Express server.
 */
function start() {
  var port = process.env.PORT || config.app.port;
  app.listen(port);
  console.log("server pid %s listening on port %s in %s mode",
    process.pid,
    port,
    app.settings.env);
}

/**
 * Here we actually initialize everything and start the Express server.
 */
var server = initServer();
initMiddleware(server);

/**
 * Only start server if this script is executed, not if it's require()'d.
 * This makes it easier to run integration tests on ephemeral ports.
 */
if (require.main === module) {
  start();
}

exports.app = app;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<commit_msg>Serve screens as static content<commit_after>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/screens'));
app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

<|endoftext|>