<commit_before>const models = module.exports = [
require('./models/tradle.APIBasedVerificationMethod_Wealth.json'),
require('./models/tradle.API_Wealth.json'),
require('./models/tradle.Ack.json'),
require('./models/tradle.AppState.json'),
require('./models/tradle.ApplicationDenial.json'),
require('./models/tradle.ApplicationSubmitted.json'),
require('./models/tradle.Aspect.json'),
require('./models/tradle.AssignRelationshipManager.json'),
require('./models/tradle.BasicContactInfo.json'),
require('./models/tradle.BetaTesterContactInfo.json'),
require('./models/tradle.ConfirmPackageRequest.json'),
require('./models/tradle.Confirmation.json'),
require('./models/tradle.Country.json'),
require('./models/tradle.CreditCards.json'),
require('./models/tradle.Currency.json'),
require('./models/tradle.CustomerWaiting.json'),
require('./models/tradle.Document.json'),
require('./models/tradle.Education.json'),
require('./models/tradle.EducationDegree.json'),
require('./models/tradle.EducationNL.json'),
require('./models/tradle.EmailAddress.json'),
require('./models/tradle.EmployeeOnboarding.json'),
require('./models/tradle.Enum.json'),
require('./models/tradle.File.json'),
require('./models/tradle.FinancialProduct.json'),
require('./models/tradle.ForgetMe.json'),
require('./models/tradle.ForgotYou.json'),
require('./models/tradle.Form.json'),
require('./models/tradle.FormError.json'),
require('./models/tradle.FormRequest.json'),
require('./models/tradle.GuestSessionProof.json'),
require('./models/tradle.Identity.json'),
require('./models/tradle.IdentityPublishRequest.json'),
require('./models/tradle.Introduction.json'),
require('./models/tradle.Item.json'),
require('./models/tradle.Language.json'),
require('./models/tradle.MaritalStatus.json'),
require('./models/tradle.MediaSnippet.json'),
require('./models/tradle.MerkleLeaf.json'),
require('./models/tradle.MerkleNode.json'),
require('./models/tradle.Message.json'),
require('./models/tradle.Method.json'),
require('./models/tradle.ModelsPack.json'),
require('./models/tradle.Money.json'),
require('./models/tradle.MyIdentities.json'),
require('./models/tradle.MyProduct.json'),
require('./models/tradle.Name.json'),
require('./models/tradle.Nationality.json'),
require('./models/tradle.NewMessageModel.json'),
require('./models/tradle.NextFormRequest.json'),
require('./models/tradle.Organization.json'),
require('./models/tradle.PairingData.json'),
require('./models/tradle.PairingRequest.json'),
require('./models/tradle.PairingResponse.json'),
require('./models/tradle.Partial.json'),
require('./models/tradle.PassportVerification.json'),
require('./models/tradle.Phone.json'),
require('./models/tradle.PhoneTypes.json'),
require('./models/tradle.Photo.json'),
require('./models/tradle.ProductApplication.json'),
require('./models/tradle.ProductList.json'),
require('./models/tradle.Profile.json'),
require('./models/tradle.PropertyType.json'),
require('./models/tradle.PropertyTypes.json'),
require('./models/tradle.Remediation.json'),
require('./models/tradle.RemediationSimpleMessage.json'),
require('./models/tradle.Residence.json'),
require('./models/tradle.ResidenceType.json'),
require('./models/tradle.ResidentialStatus.json'),
require('./models/tradle.SalaryVerification.json'),
require('./models/tradle.SecurityCode.json'),
require('./models/tradle.SelfIntroduction.json'),
require('./models/tradle.Settings.json'),
require('./models/tradle.ShareContext.json'),
require('./models/tradle.SharedResource.json'),
require('./models/tradle.SimpleMessage.json'),
require('./models/tradle.SkillVerification.json'),
require('./models/tradle.StylesPack.json'),
require('./models/tradle.TermsAndConditions.json'),
require('./models/tradle.UtilityBillVerification.json'),
require('./models/tradle.Verifiable.json'),
require('./models/tradle.Verification.json'),
require('./models/tradle.VerifiedItem.json'),
require('./models/tradle.VisualVerificationMethod_Wealth.json'),
require('./models/tradle.WebSite.json')]
models.forEach(function (m) {
  models[m.id] = m
})
<commit_msg>separating custom models<commit_after>const models = module.exports = [
require('./models/tradle.APIBasedVerificationMethod_Wealth.json'),
require('./models/tradle.API_Wealth.json'),
require('./models/tradle.Ack.json'),
require('./models/tradle.AppState.json'),
require('./models/tradle.ApplicationDenial.json'),
require('./models/tradle.ApplicationSubmitted.json'),
require('./models/tradle.Aspect.json'),
require('./models/tradle.AssignRelationshipManager.json'),
require('./models/tradle.BasicContactInfo.json'),
require('./models/tradle.BetaTesterContactInfo.json'),
require('./models/tradle.ConfirmPackageRequest.json'),
require('./models/tradle.Confirmation.json'),
require('./models/tradle.Country.json'),
require('./models/tradle.CreditCards.json'),
require('./models/tradle.Currency.json'),
require('./models/tradle.CustomerWaiting.json'),
require('./models/tradle.Document.json'),
require('./models/tradle.Education.json'),
require('./models/tradle.EducationDegree.json'),
require('./models/tradle.EducationNL.json'),
require('./models/tradle.EmailAddress.json'),
require('./models/tradle.EmployeeOnboarding.json'),
require('./models/tradle.Enum.json'),
require('./models/tradle.File.json'),
require('./models/tradle.FinancialProduct.json'),
require('./models/tradle.ForgetMe.json'),
require('./models/tradle.ForgotYou.json'),
require('./models/tradle.Form.json'),
require('./models/tradle.FormError.json'),
require('./models/tradle.FormRequest.json'),
require('./models/tradle.GuestSessionProof.json'),
require('./models/tradle.HowToFund.json'),
require('./models/tradle.Identity.json'),
require('./models/tradle.IdentityPublishRequest.json'),
require('./models/tradle.Introduction.json'),
require('./models/tradle.Item.json'),
require('./models/tradle.Language.json'),
require('./models/tradle.MaritalStatus.json'),
require('./models/tradle.MediaSnippet.json'),
require('./models/tradle.MerkleLeaf.json'),
require('./models/tradle.MerkleNode.json'),
require('./models/tradle.Message.json'),
require('./models/tradle.Method.json'),
require('./models/tradle.ModelsPack.json'),
require('./models/tradle.Money.json'),
require('./models/tradle.MyIdentities.json'),
require('./models/tradle.MyProduct.json'),
require('./models/tradle.Name.json'),
require('./models/tradle.Nationality.json'),
require('./models/tradle.NewMessageModel.json'),
require('./models/tradle.NextFormRequest.json'),
require('./models/tradle.Organization.json'),
require('./models/tradle.PairingData.json'),
require('./models/tradle.PairingRequest.json'),
require('./models/tradle.PairingResponse.json'),
require('./models/tradle.Partial.json'),
require('./models/tradle.PassportVerification.json'),
require('./models/tradle.Phone.json'),
require('./models/tradle.PhoneTypes.json'),
require('./models/tradle.Photo.json'),
require('./models/tradle.ProductApplication.json'),
require('./models/tradle.ProductList.json'),
require('./models/tradle.Profile.json'),
require('./models/tradle.ProgressMessage.json'),
require('./models/tradle.PropertyType.json'),
require('./models/tradle.PropertyTypes.json'),
require('./models/tradle.Remediation.json'),
require('./models/tradle.RemediationSimpleMessage.json'),
require('./models/tradle.Residence.json'),
require('./models/tradle.ResidenceType.json'),
require('./models/tradle.ResidentialStatus.json'),
require('./models/tradle.SalaryVerification.json'),
require('./models/tradle.SecurityCode.json'),
require('./models/tradle.SelfIntroduction.json'),
require('./models/tradle.Settings.json'),
require('./models/tradle.Sex.json'),
require('./models/tradle.ShareContext.json'),
require('./models/tradle.SharedResource.json'),
require('./models/tradle.SimpleMessage.json'),
require('./models/tradle.SkillVerification.json'),
require('./models/tradle.StylesPack.json'),
require('./models/tradle.TermsAndConditions.json'),
require('./models/tradle.UtilityBillVerification.json'),
require('./models/tradle.Verifiable.json'),
require('./models/tradle.Verification.json'),
require('./models/tradle.VerifiedItem.json'),
require('./models/tradle.VisualVerificationMethod_Wealth.json'),
require('./models/tradle.WebSite.json')]
models.forEach(function (m) {
  models[m.id] = m
})
<|endoftext|>


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

  // Project configuration.
  grunt.initConfig({
    pkg: require('../package.json'),
    clean: ['actual/'],
    zip: {
      single: {
        src: ['test_files/file.js'],
        dest: 'actual/single_zip/file.zip'
      },
      multi: {
        src: ['test_files/file.js', 'test_files/file2.js'],
        dest: 'actual/multi_zip/file.zip'
      },
      nested: {
        src: 'test_files/nested/**/*',
        dest: 'actual/nested_zip/file.zip'
      },
      image: {
        src: 'test_files/smile.gif',
        dest: 'actual/image_zip/file.zip'
      },
      router: {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/router_zip/file.zip',
        router: function (filepath) {
          var filename = path.basename(filepath);
          return filename;
        }
      },
      cwd: {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/cwd_zip/file.zip',
        cwd: 'test_files/nested'
      },
      dot: {
        src: ['test_files/dot/.test/hello.js', 'test_files/dot/test/.examplerc'],
        dest: 'actual/dot_zip/file.zip',
        dot: true
      },
      'skip-files': {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/skip_files_zip/file.zip',
        // router: function (filepath) {
        //   // Skip over txt files
        //   return filepath.indexOf('.txt') === -1 ? filepath : null;
        // }
      }
    },
    unzip: {
      single: {
        src: 'test_files/file.zip',
        dest: 'actual/single_unzip'
      },
      nested: {
        src: 'test_files/nested.zip',
        dest: 'actual/nested_unzip'
      },
      router: {
        src: 'test_files/nested.zip',
        dest: 'actual/router_unzip',
        router: function (filepath) {
          var filename = path.basename(filepath);
          return filename;
        }
      },
      'skip-files': {
        src: 'test_files/nested.zip',
        dest: 'actual/skip_files_unzip',
        // router: function (filepath) {
        //   // Skip over css files
        //   return filepath.indexOf('.css') === -1 ? filepath : null;
        // }
      },
      'test-zip-nested': {
        src: 'actual/nested_zip/file.zip',
        dest: 'actual/nested_zip/unzip'
      },
      'test-zip-image': {
        src: 'actual/image_zip/file.zip',
        dest: 'actual/image_zip/unzip'
      },
      'test-zip-router': {
        src: 'actual/router_zip/file.zip',
        dest: 'actual/router_zip/unzip'
      },
      'test-zip-cwd': {
        src: 'actual/cwd_zip/file.zip',
        dest: 'actual/cwd_zip/unzip'
      },
      'test-zip-dot': {
        src: 'actual/dot_zip/file.zip',
        dest: 'actual/dot_zip/unzip'
      },
      'test-zip-skip-files': {
        src: 'actual/skip_files_zip/file.zip',
        dest: 'actual/skip_files_zip/unzip'
      }
    },
    test: {
      common: 'zip_test.js'
    }
  });

  // Load local tasks.
  grunt.loadTasks('../tasks');

  // Load grunt contrib clean (chdir for 0.4)
  process.chdir('..');
  grunt.loadNpmTasks('grunt-contrib-clean');
  process.chdir(__dirname);

  // Run project task then tests.
  grunt.registerTask('default', 'clean zip unzip test');
};<commit_msg>Moved back to failing grunt tasks with proper implementations<commit_after>var path = require('path');
module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: require('../package.json'),
    clean: ['actual/'],
    zip: {
      single: {
        src: ['test_files/file.js'],
        dest: 'actual/single_zip/file.zip'
      },
      multi: {
        src: ['test_files/file.js', 'test_files/file2.js'],
        dest: 'actual/multi_zip/file.zip'
      },
      nested: {
        src: 'test_files/nested/**/*',
        dest: 'actual/nested_zip/file.zip'
      },
      image: {
        src: 'test_files/smile.gif',
        dest: 'actual/image_zip/file.zip'
      },
      router: {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/router_zip/file.zip',
        router: function (filepath) {
          var filename = path.basename(filepath);
          return filename;
        }
      },
      cwd: {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/cwd_zip/file.zip',
        cwd: 'test_files/nested'
      },
      dot: {
        src: ['test_files/dot/.test/hello.js', 'test_files/dot/test/.examplerc'],
        dest: 'actual/dot_zip/file.zip',
        dot: true
      },
      'skip-files': {
        src: ['test_files/nested/hello.js', 'test_files/nested/nested2/hello10.txt'],
        dest: 'actual/skip_files_zip/file.zip',
        router: function (filepath) {
          // Skip over txt files
          return filepath.indexOf('.txt') === -1 ? filepath : null;
        }
      }
    },
    unzip: {
      single: {
        src: 'test_files/file.zip',
        dest: 'actual/single_unzip'
      },
      nested: {
        src: 'test_files/nested.zip',
        dest: 'actual/nested_unzip'
      },
      router: {
        src: 'test_files/nested.zip',
        dest: 'actual/router_unzip',
        router: function (filepath) {
          var filename = path.basename(filepath);
          return filename;
        }
      },
      'skip-files': {
        src: 'test_files/nested.zip',
        dest: 'actual/skip_files_unzip',
        router: function (filepath) {
          // Skip over css files
          return filepath.indexOf('.css') === -1 ? filepath : null;
        }
      },
      'test-zip-nested': {
        src: 'actual/nested_zip/file.zip',
        dest: 'actual/nested_zip/unzip'
      },
      'test-zip-image': {
        src: 'actual/image_zip/file.zip',
        dest: 'actual/image_zip/unzip'
      },
      'test-zip-router': {
        src: 'actual/router_zip/file.zip',
        dest: 'actual/router_zip/unzip'
      },
      'test-zip-cwd': {
        src: 'actual/cwd_zip/file.zip',
        dest: 'actual/cwd_zip/unzip'
      },
      'test-zip-dot': {
        src: 'actual/dot_zip/file.zip',
        dest: 'actual/dot_zip/unzip'
      },
      'test-zip-skip-files': {
        src: 'actual/skip_files_zip/file.zip',
        dest: 'actual/skip_files_zip/unzip'
      }
    },
    test: {
      common: 'zip_test.js'
    }
  });

  // Load local tasks.
  grunt.loadTasks('../tasks');

  // Load grunt contrib clean (chdir for 0.4)
  process.chdir('..');
  grunt.loadNpmTasks('grunt-contrib-clean');
  process.chdir(__dirname);

  // Run project task then tests.
  grunt.registerTask('default', 'clean zip unzip test');
};<|endoftext|>


<commit_before>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const fs = require('fs');
const https = require('https');
const path = require('path');
const parseURL = require('url').parse;
const promisify = require('util').promisify;
const WebSocketServer = require('ws').Server;

const remoteDebuggingPort = parseInt(process.env.REMOTE_DEBUGGING_PORT, 10) || 9222;
const port = parseInt(process.env.PORT, 10);
const requestedPort = port || port === 0 ? port : 8090;
const readFile = promisify(fs.readFile);
const exists = promisify(fs.exists);

let pathToOutTargetDir = __dirname;
/**
 * If we are in the gen directory, we need to find the out/Default folder to use
 * as our base to find files from. We could do this with path.join(x, '..',
 * '..') until we get the right folder, but that's brittle. It's better to
 * search up for the directory containing args.gn to be robust to any folder structures.
 */
const fileSystemRootDirectory = path.parse(process.cwd()).root;
while (!fs.existsSync(path.join(pathToOutTargetDir, 'args.gn'))) {
  pathToOutTargetDir = path.resolve(pathToOutTargetDir, '..');
  if (pathToOutTargetDir === fileSystemRootDirectory) {
    console.error(
        'Could not find the build root directory. You must run the hosted server from within the build root directory containing the args.gn file for it to work. The hosted mode server only works on the built output from DevTools, not from the source input.');
    process.exit(1);
  }
}
// We care about everything in the gen/ directory.
const devtoolsFolder = path.resolve(path.join(pathToOutTargetDir, 'gen'));

// The certificate is taken from
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/tools/apache_config/webkit-httpd.pem
const options = {
  key: fs.readFileSync(__dirname + '/key.pem'),
  cert: fs.readFileSync(__dirname + '/cert.pem'),
};

const server = https.createServer(options, requestHandler);
server.once('error', error => {
  if (process.send) {
    process.send('ERROR');
  }
  throw error;
});
server.once('listening', () => {
  // If port 0 was used, then requested and actual port will be different.
  const actualPort = server.address().port;
  if (process.send) {
    process.send(actualPort);
  }
  console.log(`Started hosted mode server at http://localhost:${actualPort}\n`);
  console.log('For info on using the hosted mode server, see our contributing docs:');
  console.log('https://bit.ly/devtools-contribution-guide');
  console.log('Tip: Look for the \'Development server options\' section\n');
});
const wss = new WebSocketServer({server});

wss.on('connection', ws => {
  ws.on('message', (message, binary) => {
    ws.send(message, {binary});
  });
});

server.listen(requestedPort);

async function requestHandler(request, response) {
  const filePath = unescape(parseURL(request.url).pathname);
  if (filePath === '/') {
    const landingURL = `http://localhost:${remoteDebuggingPort}#custom=true`;
    sendResponse(200, `<html>Please go to <a href="${landingURL}">${landingURL}</a></html>`, 'utf8');
    return;
  }

  const absoluteFilePath = path.join(devtoolsFolder, filePath);
  if (!path.resolve(absoluteFilePath).startsWith(path.join(devtoolsFolder, '..'))) {
    console.log(`File requested (${absoluteFilePath}) is outside of devtools folder: ${devtoolsFolder}`);
    sendResponse(403, `403 - Access denied. File requested is outside of devtools folder: ${devtoolsFolder}`, 'utf8');
    return;
  }

  const fileExists = await exists(absoluteFilePath);
  if (!fileExists) {
    console.log(`Cannot find file ${absoluteFilePath}. Requested URL: ${filePath}`);
    sendResponse(404, '404 - File not found', 'utf8');
    return;
  }

  let statusCode, data, headers;
  const headersFileExists = await exists(absoluteFilePath + '.headers');
  if (headersFileExists) {
    try {
      const headersFile = await readFile(absoluteFilePath + '.headers', 'utf8');
      ({statusCode, headers} = parseRawResponse(headersFile));
    } catch (err) {
      console.log(`Unable to read local file ${absoluteFilePath}.headers:`, err);
      sendResponse(500, '500 - Internal Server Error', 'utf8');
    }
  }

  let encoding = 'utf8';
  if (absoluteFilePath.endsWith('.wasm') || absoluteFilePath.endsWith('.png') || absoluteFilePath.endsWith('.jpg') ||
      absoluteFilePath.endsWith('.avif') || absoluteFilePath.endsWith('.wbn')) {
    encoding = 'binary';
  }

  try {
    data = await readFile(absoluteFilePath, encoding);
    if (absoluteFilePath.endsWith('.rawresponse')) {
      ({statusCode, data, headers} = parseRawResponse(data));
    }
    sendResponse(statusCode || 200, data, encoding, headers);
  } catch (err) {
    console.log(`Unable to read local file ${absoluteFilePath}:`, err);
    sendResponse(500, '500 - Internal Server Error', 'utf8');
  }

  function inferContentType(url) {
    const path = parseURL(url).pathname;

    if (path.endsWith('.js') || path.endsWith('.mjs')) {
      return 'text/javascript; charset=utf-8';
    }
    if (path.endsWith('.css')) {
      return 'text/css; charset=utf-8';
    }
    if (path.endsWith('.wasm')) {
      return 'application/wasm';
    }
    if (path.endsWith('.svg')) {
      return 'image/svg+xml; charset=utf-8';
    }
    if (path.endsWith('.png')) {
      return 'image/png';
    }
    if (path.endsWith('.jpg')) {
      return 'image/jpg';
    }
    if (path.endsWith('.avif')) {
      return 'image/avif';
    }
    return null;
  }

  function sendResponse(statusCode, data, encoding, headers) {
    if (!headers) {
      headers = new Map();
    }
    if (!headers.get('Content-Type')) {
      const inferredContentType = inferContentType(request.url);
      if (inferredContentType) {
        headers.set('Content-Type', inferredContentType);
      }
    }
    headers.forEach((value, header) => {
      response.setHeader(header, value);
    });

    response.writeHead(statusCode);
    if (data && encoding) {
      response.write(data, encoding);
    }
    response.end();
  }

  function parseRawResponse(rawResponse) {
    const lines = rawResponse.split('\n');

    let isHeader = true;
    let line = lines.shift();
    const statusCode = parseInt(line, 10);

    const headers = new Map();
    let data = '';

    while ((line = lines.shift()) !== undefined) {
      if (line.trim() === '') {
        isHeader = false;
        if (request.headers['if-none-match'] && response.getHeader('ETag') === request.headers['if-none-match']) {
          return {statusCode: 304};
        }
        continue;
      }

      if (isHeader) {
        const firstColon = line.indexOf(':');
        let headerValue = line.substring(firstColon + 1).trim();
        headerValue = headerValue.replace('$host_port', `${server.address().port}`);
        headers.set(line.substring(0, firstColon), headerValue);
      } else {
        data += line;
      }
    }

    return {statusCode, data, headers};
  }
}
<commit_msg>[server] Add binary encoding for DWARF object+package files<commit_after>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const fs = require('fs');
const https = require('https');
const path = require('path');
const parseURL = require('url').parse;
const promisify = require('util').promisify;
const WebSocketServer = require('ws').Server;

const remoteDebuggingPort = parseInt(process.env.REMOTE_DEBUGGING_PORT, 10) || 9222;
const port = parseInt(process.env.PORT, 10);
const requestedPort = port || port === 0 ? port : 8090;
const readFile = promisify(fs.readFile);
const exists = promisify(fs.exists);

let pathToOutTargetDir = __dirname;
/**
 * If we are in the gen directory, we need to find the out/Default folder to use
 * as our base to find files from. We could do this with path.join(x, '..',
 * '..') until we get the right folder, but that's brittle. It's better to
 * search up for the directory containing args.gn to be robust to any folder structures.
 */
const fileSystemRootDirectory = path.parse(process.cwd()).root;
while (!fs.existsSync(path.join(pathToOutTargetDir, 'args.gn'))) {
  pathToOutTargetDir = path.resolve(pathToOutTargetDir, '..');
  if (pathToOutTargetDir === fileSystemRootDirectory) {
    console.error(
        'Could not find the build root directory. You must run the hosted server from within the build root directory containing the args.gn file for it to work. The hosted mode server only works on the built output from DevTools, not from the source input.');
    process.exit(1);
  }
}
// We care about everything in the gen/ directory.
const devtoolsFolder = path.resolve(path.join(pathToOutTargetDir, 'gen'));

// The certificate is taken from
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/tools/apache_config/webkit-httpd.pem
const options = {
  key: fs.readFileSync(__dirname + '/key.pem'),
  cert: fs.readFileSync(__dirname + '/cert.pem'),
};

const server = https.createServer(options, requestHandler);
server.once('error', error => {
  if (process.send) {
    process.send('ERROR');
  }
  throw error;
});
server.once('listening', () => {
  // If port 0 was used, then requested and actual port will be different.
  const actualPort = server.address().port;
  if (process.send) {
    process.send(actualPort);
  }
  console.log(`Started hosted mode server at http://localhost:${actualPort}\n`);
  console.log('For info on using the hosted mode server, see our contributing docs:');
  console.log('https://bit.ly/devtools-contribution-guide');
  console.log('Tip: Look for the \'Development server options\' section\n');
});
const wss = new WebSocketServer({server});

wss.on('connection', ws => {
  ws.on('message', (message, binary) => {
    ws.send(message, {binary});
  });
});

server.listen(requestedPort);

async function requestHandler(request, response) {
  const filePath = unescape(parseURL(request.url).pathname);
  if (filePath === '/') {
    const landingURL = `http://localhost:${remoteDebuggingPort}#custom=true`;
    sendResponse(200, `<html>Please go to <a href="${landingURL}">${landingURL}</a></html>`, 'utf8');
    return;
  }

  const absoluteFilePath = path.join(devtoolsFolder, filePath);
  if (!path.resolve(absoluteFilePath).startsWith(path.join(devtoolsFolder, '..'))) {
    console.log(`File requested (${absoluteFilePath}) is outside of devtools folder: ${devtoolsFolder}`);
    sendResponse(403, `403 - Access denied. File requested is outside of devtools folder: ${devtoolsFolder}`, 'utf8');
    return;
  }

  const fileExists = await exists(absoluteFilePath);
  if (!fileExists) {
    console.log(`Cannot find file ${absoluteFilePath}. Requested URL: ${filePath}`);
    sendResponse(404, '404 - File not found', 'utf8');
    return;
  }

  let statusCode, data, headers;
  const headersFileExists = await exists(absoluteFilePath + '.headers');
  if (headersFileExists) {
    try {
      const headersFile = await readFile(absoluteFilePath + '.headers', 'utf8');
      ({statusCode, headers} = parseRawResponse(headersFile));
    } catch (err) {
      console.log(`Unable to read local file ${absoluteFilePath}.headers:`, err);
      sendResponse(500, '500 - Internal Server Error', 'utf8');
    }
  }

  let encoding = 'utf8';
  if (absoluteFilePath.endsWith('.wasm') || absoluteFilePath.endsWith('.png') || absoluteFilePath.endsWith('.jpg') ||
      absoluteFilePath.endsWith('.avif') || absoluteFilePath.endsWith('.wbn') || absoluteFilePath.endsWith('.dwp') ||
      absoluteFilePath.endsWith('.dwo')) {
    encoding = 'binary';
  }

  try {
    data = await readFile(absoluteFilePath, encoding);
    if (absoluteFilePath.endsWith('.rawresponse')) {
      ({statusCode, data, headers} = parseRawResponse(data));
    }
    sendResponse(statusCode || 200, data, encoding, headers);
  } catch (err) {
    console.log(`Unable to read local file ${absoluteFilePath}:`, err);
    sendResponse(500, '500 - Internal Server Error', 'utf8');
  }

  function inferContentType(url) {
    const path = parseURL(url).pathname;

    if (path.endsWith('.js') || path.endsWith('.mjs')) {
      return 'text/javascript; charset=utf-8';
    }
    if (path.endsWith('.css')) {
      return 'text/css; charset=utf-8';
    }
    if (path.endsWith('.wasm')) {
      return 'application/wasm';
    }
    if (path.endsWith('.svg')) {
      return 'image/svg+xml; charset=utf-8';
    }
    if (path.endsWith('.png')) {
      return 'image/png';
    }
    if (path.endsWith('.jpg')) {
      return 'image/jpg';
    }
    if (path.endsWith('.avif')) {
      return 'image/avif';
    }
    return null;
  }

  function sendResponse(statusCode, data, encoding, headers) {
    if (!headers) {
      headers = new Map();
    }
    if (!headers.get('Content-Type')) {
      const inferredContentType = inferContentType(request.url);
      if (inferredContentType) {
        headers.set('Content-Type', inferredContentType);
      }
    }
    headers.forEach((value, header) => {
      response.setHeader(header, value);
    });

    response.writeHead(statusCode);
    if (data && encoding) {
      response.write(data, encoding);
    }
    response.end();
  }

  function parseRawResponse(rawResponse) {
    const lines = rawResponse.split('\n');

    let isHeader = true;
    let line = lines.shift();
    const statusCode = parseInt(line, 10);

    const headers = new Map();
    let data = '';

    while ((line = lines.shift()) !== undefined) {
      if (line.trim() === '') {
        isHeader = false;
        if (request.headers['if-none-match'] && response.getHeader('ETag') === request.headers['if-none-match']) {
          return {statusCode: 304};
        }
        continue;
      }

      if (isHeader) {
        const firstColon = line.indexOf(':');
        let headerValue = line.substring(firstColon + 1).trim();
        headerValue = headerValue.replace('$host_port', `${server.address().port}`);
        headers.set(line.substring(0, firstColon), headerValue);
      } else {
        data += line;
      }
    }

    return {statusCode, data, headers};
  }
}
<|endoftext|>


<commit_before><commit_msg>Added test for default values<commit_after><|endoftext|>


<commit_before>var moment = require('moment');

var MS_PER_DAY = 86400000;

/**
 * A submission bounce signifying that the submission was kicked back to the
 * author.
 *
 * @typedef {Object} SubmissionBounce
 * @prop {String} _type - Elastic search type name (always "SubmissionBounce").
 * @prop {String} ProjectPath - The Gitlab project path (group/project-name).
 * @prop {String} ProjectGroup - The Gitlab project group.
 * @prop {String} SubmissionType - The submission type.
 * @prop {String} Title - Submission title.
 * @prop {String} Url - Gitlab submission URL.
 * @prop {String} Timestamp - ISO 8601 formatted creation date for the note.
 * @prop {String} SubmissionDate - ISO 8601 formatted creation date for the
 *  submission.
 * @prop {Number} DaysSinceSubmission - Number of days since the submission was
 *  created.
 * @prop {String} Author - Submission author's username.
 * @prop {String} Reason - Reason for the bounce.
 * @prop {String} Message - The supplied message describing the bounce.
 */

/**
 * Create a submission bounce object.
 *
 * @param {Object} props - Submission bounce properties.
 * @param {Object} props.note - Gitlab note object.
 * @param {Object} props.project - Gitlab project object.
 * @param {Object} props.submission - Gitlab submission object (either the
 *  Gitlab issue or merge request).
 * @param {Object} props.author - Gitlab author (user) information.
 * @param {String} props.reason - The reason for the bounce.
 * @param {String} props.message - The message of the bounce.
 * @param {String} props.submissionType - The submission type, either "Issue" or
 *  "MergeRequest".
 * @param {Boolean} props.rejection - The bounce rejects the submission
 *  completely.
 * @return {SubmissionBounce} The submission bounce object.
 */
function createSubissionBounce(props) {
  var projectPath = props.project.path_with_namespace;
  var projectGroup = projectPath.split('/')[0];
  var elapsed = moment(props.note.created_at).diff(moment(props.submission.created_at)) / MS_PER_DAY;

  return {
    _type: 'SubmissionBounce',
    ProjectPath: projectPath,
    ProjectGroup: projectGroup,
    SubmissionType: props.submissionType,
    Timestamp: props.note.created_at,
    Title: props.submission.title,
    Url: props.note.url,
    SubmissionDate: props.submission.created_at,
    DaysSinceSubmission: elapsed,
    Author: props.author.username,
    Reason: props.reason || 'Unknown',
    Message: props.message || '',
    IsRejection: props.rejected || false
  };
}

/**
 * A submission that wraps a Gitlab issue or merge request.
 *
 * @typedef {Object} Submission
 * @prop {String} _type - Elastic search type name (always "Submission").
 * @prop {String} ProjectPath - The Gitlab project path (group/project-name).
 * @prop {String} ProjectGroup - The Gitlab project group.
 * @prop {String} SubmissionType - The submission type.
 * @prop {String} Title - Submission title.
 * @prop {String} Url - Gitlab submission URL.
 * @prop {String} Timestamp - ISO 8601 formatted creation date for the note.
 * @prop {String} SubmissionDate - ISO 8601 formatted creation date for the
 *  submission (this will always be identical to "Timestamp").
 */

/**
 * Create a submission object, wrapping a Gitlab Issue or Merge Request.
 *
 * @param {Object} props - Submission properties.
 * @param {Object} props.project - Gitlab Project object.
 * @param {Object} props.author - Gitlab author object.
 * @param {Object} props.submission - Gitlab submission payload.
 * @param {String} props.submissionType - Submission type, either "Issue" or
 *  "MergeRequest".
 * @return {Submission} The submission object.
 */
function createSubmission(props) {
  // var project = props.webhook.project;
  // var author = props.webhook.user;
  // var submission = props.webhook.object_attributes;
  var projectPath = props.project.path_with_namespace;
  var projectGroup = projectPath.split('/')[0];

  return {
    _type: 'Submission',
    ProjectPath: projectPath,
    ProjectGroup: projectGroup,
    SubmissionType: props.submissionType,
    Timestamp: props.submission.created_at,
    SubmissionDate: props.submission.created_at,
    Title: props.submission.title,
    Url: props.submission.url,
    Author: props.author.username
  };
}

exports.createSubmissionBounce = createSubissionBounce;
exports.createSubmission = createSubmission;
<commit_msg>add docs<commit_after>/**
 * Elasticsearch data models for:
 *
 *  - Submissions - Items that were submitted by a user. This currently only
 *    includes Gitlab issues and merge requests.
 *
 *  - Submission Bounces - Events where a Submission was reassigned to the
 *    original submission author or the submission was permanently rejected. A
 *    bounce event occurs when the author needs to take some action to resolve
 *    inconsistencies or problems with the code submission.
 *
 * @copyright Adam Meily <meily.adam@gmail.com> 2017
 * @license BSD 2-Clause
 */

var moment = require('moment');

var MS_PER_DAY = 86400000;

/**
 * A submission bounce signifying that the submission was kicked back to the
 * author.
 *
 * @typedef {Object} SubmissionBounce
 * @prop {String} _type - Elastic search type name (always "SubmissionBounce").
 * @prop {String} ProjectPath - The Gitlab project path (group/project-name).
 * @prop {String} ProjectGroup - The Gitlab project group.
 * @prop {String} SubmissionType - The submission type.
 * @prop {String} Title - Submission title.
 * @prop {String} Url - Gitlab submission URL.
 * @prop {String} Timestamp - ISO 8601 formatted creation date for the note.
 * @prop {String} SubmissionDate - ISO 8601 formatted creation date for the
 *  submission.
 * @prop {Number} DaysSinceSubmission - Number of days since the submission was
 *  created.
 * @prop {String} Author - Submission author's username.
 * @prop {String} Reason - Reason for the bounce.
 * @prop {String} Message - The supplied message describing the bounce.
 */

/**
 * Create a submission bounce object.
 *
 * @param {Object} props - Submission bounce properties.
 * @param {Object} props.note - Gitlab note object.
 * @param {Object} props.project - Gitlab project object.
 * @param {Object} props.submission - Gitlab submission object (either the
 *  Gitlab issue or merge request).
 * @param {Object} props.author - Gitlab author (user) information.
 * @param {String} props.reason - The reason for the bounce.
 * @param {String} props.message - The message of the bounce.
 * @param {String} props.submissionType - The submission type, either "Issue" or
 *  "MergeRequest".
 * @param {Boolean} props.rejection - The bounce rejects the submission
 *  completely.
 * @return {SubmissionBounce} The submission bounce object.
 */
function createSubissionBounce(props) {
  var projectPath = props.project.path_with_namespace;
  var projectGroup = projectPath.split('/')[0];
  var elapsed = moment(props.note.created_at).diff(moment(props.submission.created_at)) / MS_PER_DAY;

  return {
    _type: 'SubmissionBounce',
    ProjectPath: projectPath,
    ProjectGroup: projectGroup,
    SubmissionType: props.submissionType,
    Timestamp: props.note.created_at,
    Title: props.submission.title,
    Url: props.note.url,
    SubmissionDate: props.submission.created_at,
    DaysSinceSubmission: elapsed,
    Author: props.author.username,
    Reason: props.reason || 'Unknown',
    Message: props.message || '',
    IsRejection: props.rejected || false
  };
}

/**
 * A submission that wraps a Gitlab issue or merge request.
 *
 * @typedef {Object} Submission
 * @prop {String} _type - Elastic search type name (always "Submission").
 * @prop {String} ProjectPath - The Gitlab project path (group/project-name).
 * @prop {String} ProjectGroup - The Gitlab project group.
 * @prop {String} SubmissionType - The submission type.
 * @prop {String} Title - Submission title.
 * @prop {String} Url - Gitlab submission URL.
 * @prop {String} Timestamp - ISO 8601 formatted creation date for the note.
 * @prop {String} SubmissionDate - ISO 8601 formatted creation date for the
 *  submission (this will always be identical to "Timestamp").
 */

/**
 * Create a submission object, wrapping a Gitlab Issue or Merge Request.
 *
 * @param {Object} props - Submission properties.
 * @param {Object} props.project - Gitlab Project object.
 * @param {Object} props.author - Gitlab author object.
 * @param {Object} props.submission - Gitlab submission payload.
 * @param {String} props.submissionType - Submission type, either "Issue" or
 *  "MergeRequest".
 * @return {Submission} The submission object.
 */
function createSubmission(props) {
  // var project = props.webhook.project;
  // var author = props.webhook.user;
  // var submission = props.webhook.object_attributes;
  var projectPath = props.project.path_with_namespace;
  var projectGroup = projectPath.split('/')[0];

  return {
    _type: 'Submission',
    ProjectPath: projectPath,
    ProjectGroup: projectGroup,
    SubmissionType: props.submissionType,
    Timestamp: props.submission.created_at,
    SubmissionDate: props.submission.created_at,
    Title: props.submission.title,
    Url: props.submission.url,
    Author: props.author.username
  };
}

exports.createSubmissionBounce = createSubissionBounce;
exports.createSubmission = createSubmission;
<|endoftext|>


<commit_before>var should = require('should');
var http = require('http');
var Router = require('../index');
var verity = require('verity');

var getServer = function(router, cb){
  var server = http.createServer(function(req, res){
    router.middleware(req, res);
  }).listen(9999, function(err){
      if (err) throw err;
      cb(null, server);
    });
};

describe("detour", function(){
  var server;
  var v;

  describe("getMethods", function(){
    it ("gets the implemented methods for a resource", function(done){
      var router = new Router();
      router.route('/test/:testid', {
        GET : function(req, res){
          req.pathVar.testid.should.equal('1234');
          res.end('worked: ' + JSON.stringify(req.pathVar));
        }
      });
      var route = router.getRoute("/test/1234");
      router.getMethods(route.resource)
        .should.eql(["GET", "HEAD", "OPTIONS"]);
      done();
    });
  });

  describe("in a server environment", function(){

    beforeEach(function(done){
      v = verity('http://localhost:9999', 'GET');
      v.expectedBody = 'worked';
      v.expectedStatus = 200;
      done();
    });

    afterEach(function(done){
      if (server){
        server.close(function(){
          done();
        });
      }
    });

    it ("200s for plain GET", function(done){
      var router = new Router();
      router.route('/', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.test(done);
      });
    });
    it ("can be created without `new`", function(done){
      var router = Router();
      router.route('/', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.test(done);
      });
    });
    it ("can route multiple times", function(done){
      var router = new Router();
      router.route('/', {
        GET : function(req, res){
          res.end('failed');
        }
      });
      router.route('/test', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      router.route('/test/:id', {
        GET : function(req, res){
          res.end('failed');
        }
      });
      router.routes.length.should.equal(3);
      getServer(router, function(err, serv){
        server = serv;
        v.uri = v.uri.path("test");
        v.test(done);
      });
    });
    it ("200s for plain POST", function(done){
      var router = new Router();
      router.route('/', {
        POST : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.method = 'POST';
        v.test(done);
      });
    });
    describe("pathVar", function(){
      it ("sets pathVar with variables from the url", function(done){
        var router = new Router();
        router.route('/test/:testid', {
          GET : function(req, res){
            req.pathVar.testid.should.equal('1234');
            res.end('worked: ' + JSON.stringify(req.pathVar));
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.path("test/1234");
          v.expectedBody = 'worked: {"testid":"1234"}';
          v.test(done);
        });
      });
    });
    describe("404", function(){
      it ("has a default 404 if none is specified the middleware is not given a next()",
        function(done){
        var router = new Router();
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 404;
          v.expectedBody = 'Not found';
          v.test(function(e, r, b){
            done();
          });
        });
      });

      it ("has on(404) for registering a new 404 handler", function(done){
        var router = new Router();
        router.on(404, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
      it ("uses middleware's next() param for 404s, if defined", function(done){
        var getServer = function(router, cb){
          var server = http.createServer(function(req, res){
            router.middleware(req, res, function(){
              res.end("next works!");
            });
          }).listen(9999, function(err){
              if (err) throw err;
              cb(null, server);
            });
        };
        var router = new Router();
        router.on(404, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 200;
          v.expectedBody = 'next works!';
          v.test(done);
        });
      });
    });
    describe("405", function(){
      it ("has a default 405 handler if none is specified",
        function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = "DELETE";
          v.expectHeader('allow', 'GET,HEAD,OPTIONS');
          v.expectedStatus = 405;
          v.expectedBody = 'Not allowed';
          v.test(function(e, r, b){
            done();
          });
        });
      });
      it ("has on(405) for registering a new 405 handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on(405, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'DELETE';
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
    });

    describe("HEAD", function(){
      it ("routes to GET when HEAD is requested (and returns an empty body)", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 200;
          v.expectedBody = '';
          v.test(done);
        });
      });

      it ("405s when HEAD is requested if GET is not defined", function(done){
        var router = new Router();
        router.route('/', {
          POST : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 405;
          v.expectedBody = '';
          v.test(done);
        });
      });
      it ("allows the resource to override the default HEAD", function(done){
        var router = new Router();
        router.route('/', {
          HEAD : function(req, res){
            res.writeHead(400);
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedBody = "";
          v.expectedStatus = 400;
          v.test(done);
        });
      });
      it ("has on('HEAD') for registering a new HEAD handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on('HEAD', function(req, res){
          res.writeHead(400);
          res.write("bad request"); // this will get muted
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 400;
          v.expectedBody = '';
          v.test(done);
        });
      });
    });
    describe("OPTIONS", function(){
      it ("200s for plain OPTIONS with a default OPTIONs handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          v.method = 'OPTIONS';
          v.expectHeader('allow', 'GET,HEAD,OPTIONS');
          v.expectedBody = "Allow: GET,HEAD,OPTIONS";
          server = serv;
          v.test(done);
        });
      });
      it ("allows the resource to override the default OPTIONS", function(done){
        var router = new Router();
        router.route('/', {
          OPTIONS : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'OPTIONS';
          v.expectedBody = "worked";
          v.test(done);
        });
      });
      it ("doesn't show HEAD if GET is not defined", function(done){
        var router = new Router();
        router.route('/', {
          POST : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          v.method = 'OPTIONS';
          v.expectedBody = "Allow: POST,OPTIONS";
          server = serv;
          v.test(done);
        });
      });
      it ("has on('OPTIONS') for registering a new OPTIONS handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on('OPTIONS', function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'OPTIONS';
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
    });
  });
});
<commit_msg>add a test if a next callback is passed to a route<commit_after>var should = require('should');
var http = require('http');
var Router = require('../index');
var verity = require('verity');

var getServer = function(router, cb){
  var server = http.createServer(function(req, res){
    router.middleware(req, res);
  }).listen(9999, function(err){
      if (err) throw err;
      cb(null, server);
    });
};

describe("detour", function(){
  var server;
  var v;

  describe("getMethods", function(){
    it ("gets the implemented methods for a resource", function(done){
      var router = new Router();
      router.route('/test/:testid', {
        GET : function(req, res){
          req.pathVar.testid.should.equal('1234');
          res.end('worked: ' + JSON.stringify(req.pathVar));
        }
      });
      var route = router.getRoute("/test/1234");
      router.getMethods(route.resource)
        .should.eql(["GET", "HEAD", "OPTIONS"]);
      done();
    });
  });

  describe("in a server environment", function(){

    beforeEach(function(done){
      v = verity('http://localhost:9999', 'GET');
      v.expectedBody = 'worked';
      v.expectedStatus = 200;
      done();
    });

    afterEach(function(done){
      if (server){
        server.close(function(){
          done();
        });
      }
    });

    it ("200s for plain GET", function(done){
      var router = new Router();
      router.route('/', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.test(done);
      });
    });
    it ("can be created without `new`", function(done){
      var router = Router();
      router.route('/', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.test(done);
      });
    });
    it ("can route multiple times", function(done){
      var router = new Router();
      router.route('/', {
        GET : function(req, res){
          res.end('failed');
        }
      });
      router.route('/test', {
        GET : function(req, res){
          res.end('worked');
        }
      });
      router.route('/test/:id', {
        GET : function(req, res){
          res.end('failed');
        }
      });
      router.routes.length.should.equal(3);
      getServer(router, function(err, serv){
        server = serv;
        v.uri = v.uri.path("test");
        v.test(done);
      });
    });
    it ("200s for plain POST", function(done){
      var router = new Router();
      router.route('/', {
        POST : function(req, res){
          res.end('worked');
        }
      });
      getServer(router, function(err, serv){
        server = serv;
        v.method = 'POST';
        v.test(done);
      });
    });
  it ("in middleware a next callback is passed to a route", function(done){
	  var getServer = function(router, cb){
		  server = http.createServer(function(req, res){
			  router.middleware(req, res, function(err){
				  res.end(err.message);
			  });
		  }).listen(9999, function(err){
			  if (err) throw err;
			  cb(null, server);
		  });
	  };
	  var router = new Router();
	  router.route('/test', {
		  GET: function(req, res, next){
			  next({
				  message: 'next works!'
			  })
		  }
	  });
	  getServer(router, function(err, server){
		  v = verity('http://localhost:9999/test', 'GET');
		  v.expectedBody = 'next works!';
		  v.test(done);
	  });
  });
    describe("pathVar", function(){
      it ("sets pathVar with variables from the url", function(done){
        var router = new Router();
        router.route('/test/:testid', {
          GET : function(req, res){
            req.pathVar.testid.should.equal('1234');
            res.end('worked: ' + JSON.stringify(req.pathVar));
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.path("test/1234");
          v.expectedBody = 'worked: {"testid":"1234"}';
          v.test(done);
        });
      });
    });
    describe("404", function(){
      it ("has a default 404 if none is specified the middleware is not given a next()",
        function(done){
        var router = new Router();
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 404;
          v.expectedBody = 'Not found';
          v.test(function(e, r, b){
            done();
          });
        });
      });

      it ("has on(404) for registering a new 404 handler", function(done){
        var router = new Router();
        router.on(404, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
      it ("uses middleware's next() param for 404s, if defined", function(done){
        var getServer = function(router, cb){
          var server = http.createServer(function(req, res){
            router.middleware(req, res, function(){
              res.end("next works!");
            });
          }).listen(9999, function(err){
              if (err) throw err;
              cb(null, server);
            });
        };
        var router = new Router();
        router.on(404, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.uri = v.uri.child("doesNotExist");
          v.expectedStatus = 200;
          v.expectedBody = 'next works!';
          v.test(done);
        });
      });
    });
    describe("405", function(){
      it ("has a default 405 handler if none is specified",
        function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = "DELETE";
          v.expectHeader('allow', 'GET,HEAD,OPTIONS');
          v.expectedStatus = 405;
          v.expectedBody = 'Not allowed';
          v.test(function(e, r, b){
            done();
          });
        });
      });
      it ("has on(405) for registering a new 405 handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on(405, function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'DELETE';
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
    });

    describe("HEAD", function(){
      it ("routes to GET when HEAD is requested (and returns an empty body)", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 200;
          v.expectedBody = '';
          v.test(done);
        });
      });

      it ("405s when HEAD is requested if GET is not defined", function(done){
        var router = new Router();
        router.route('/', {
          POST : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 405;
          v.expectedBody = '';
          v.test(done);
        });
      });
      it ("allows the resource to override the default HEAD", function(done){
        var router = new Router();
        router.route('/', {
          HEAD : function(req, res){
            res.writeHead(400);
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedBody = "";
          v.expectedStatus = 400;
          v.test(done);
        });
      });
      it ("has on('HEAD') for registering a new HEAD handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on('HEAD', function(req, res){
          res.writeHead(400);
          res.write("bad request"); // this will get muted
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'HEAD';
          v.expectedStatus = 400;
          v.expectedBody = '';
          v.test(done);
        });
      });
    });
    describe("OPTIONS", function(){
      it ("200s for plain OPTIONS with a default OPTIONs handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          v.method = 'OPTIONS';
          v.expectHeader('allow', 'GET,HEAD,OPTIONS');
          v.expectedBody = "Allow: GET,HEAD,OPTIONS";
          server = serv;
          v.test(done);
        });
      });
      it ("allows the resource to override the default OPTIONS", function(done){
        var router = new Router();
        router.route('/', {
          OPTIONS : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'OPTIONS';
          v.expectedBody = "worked";
          v.test(done);
        });
      });
      it ("doesn't show HEAD if GET is not defined", function(done){
        var router = new Router();
        router.route('/', {
          POST : function(req, res){
            res.end('worked');
          }
        });
        getServer(router, function(err, serv){
          v.method = 'OPTIONS';
          v.expectedBody = "Allow: POST,OPTIONS";
          server = serv;
          v.test(done);
        });
      });
      it ("has on('OPTIONS') for registering a new OPTIONS handler", function(done){
        var router = new Router();
        router.route('/', {
          GET : function(req, res){
            res.end('worked');
          }
        });
        router.on('OPTIONS', function(req, res){
          res.writeHead(400);
          res.write("bad request");
          res.end();
        });
        getServer(router, function(err, serv){
          server = serv;
          v.method = 'OPTIONS';
          v.expectedStatus = 400;
          v.expectedBody = 'bad request';
          v.test(done);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

/* global describe */
/* global it */

require('babel/register')

var faker = require('faker')
var assert = require('assert')
var validate = require('./bpvalidator.es6')
var BPlusIndex = require('../dist/bplus-index')
var bpindex = new BPlusIndex({branchingFactor: 10})
var benchArray = []

describe('BPlusIndex', function () {
  it('should have a test property', function () {
    assert.equal(bpindex, true)
  })
})

for (let i = 0; i < 2000000; i++) {
  let key = faker.random.number({max: 999999}) + 1
  let val = faker.name.findName()

  // console.log('=========================== BEFORE INSERT ' + key)
  bpindex.insert(key, val)
  benchArray.push({key: key, val: val})

  // var errors = validate(bpindex)
  // if (errors.length > 0) {
  //   console.log('++++++++++++++++++++ BROKE AFTER ' + i + ' INSERTIONS')
  //   console.log(errors)
  //   break
  // }

}

// console.log(JSON.stringify(bpindex.dumpTree(), null, 4))

for (let i = 0; i < 2; i++) {
  var age = benchArray[faker.random.number({max: benchArray.length - 1})].key

  var result
  console.log(`FIND: ${age}`)
  console.time('find key in array ================================================')
  result = []
  for (let i = 0; i < benchArray.length; i++) {
    if (benchArray[i].key === age) {
      result.push(benchArray[i].val)
    }
  }
  console.log(result)
  console.timeEnd('find key in array ================================================')

  console.time('find key in bpindex ====================================================')
  result = bpindex.get(age)
  console.log(result)
  console.timeEnd('find key in bpindex ====================================================')
}

// console.log(bpindex.root)
<commit_msg>more work on tests<commit_after>'use strict'

/* global describe */
/* global it */

require('babel/register')

var _ = require('lodash')
var faker = require('faker')
var assert = require('assert')
var validate = require('./bpvalidator.es6')
var BPlusIndex = require('../dist/bplus-index')
// var benchArray = []

var db = []
var recCount = 1000

console.log('Creating database of ' + recCount + ' records.')
console.time('Done!')
for (let i = 0; i < recCount; i++) {
  let rec = {
    age: faker.random.number({max: 1000}),
    name: faker.name.findName(),
    phone: faker.phone.phoneNumber(),
    title: faker.name.jobTitle()
  }
  if (i === 0) console.log(rec)
  db.push(rec)
}
console.timeEnd('Done!')

describe('BPlusIndex', function () {
  it('should have a valid structure after every insert (testing 100 times)', function () {
    let bpindex = new BPlusIndex()
    var errors = []

    for (let rec of db) {
      bpindex.insert(rec.age, rec.name)
      errors = validate(bpindex)
      if (errors.length > 0) { break }
    }

    if (errors.length > 0) console.log(errors)

    assert.equal(errors.length, 0)
  })

  it('should have a valid structure after 1,000 numeric key inserts', function () {
    let bpindex = new BPlusIndex()

    for (let rec of db) {
      bpindex.insert(rec.age, rec.name)
    }

    let errors = validate(bpindex)

    if (errors.length > 0) console.log(errors)

    assert.equal(errors.length, 0)
  })

  it('should have a valid structure after 1,000 string key inserts', function () {
    let bpindex = new BPlusIndex()

    for (let rec of db) {
      bpindex.insert(rec.title, rec.name)
    }

    let errors = validate(bpindex)

    if (errors.length > 0) console.log(errors)

    assert.equal(errors.length, 0)
  })
})

// console.time('==== Load Array')
// for (let rec of db) {
//   benchArray.push(rec)
// }
// console.timeEnd('==== Load Array')
//
// console.time('==== Load BTree')
// for (let rec of db) {
//   bpindex.insert(rec.age, rec.name)
// }
// console.timeEnd('==== Load BTree')

// var errors = validate(bpindex)
// if (errors.length > 0) {
//   console.log('++++++++++++++++++++ BROKE AFTER ' + i + ' INSERTIONS')
//   console.log(errors)
//   break
// }

// console.log(JSON.stringify(bpindex.dumpTree(), null, 4))

// for (let i = 0; i < 20; i++) {
//   var age = db[faker.random.number({max: benchArray.length - 1})].age
//
//   var result
//   console.log(`FIND: ${age}`)
//   console.time('find key in array')
//   result = []
//   for (let i = 0; i < benchArray.length; i++) {
//     if (benchArray[i].age === age) {
//       result.push(benchArray[i].name)
//     }
//   }
//   console.timeEnd('find key in array')
//
//   console.time('find key in bpindex')
//   result = bpindex.get(age)
//   console.timeEnd('find key in bpindex')
// }
<|endoftext|>


<commit_before>const inquirer = require('inquirer');
const _ = require('lodash');
const path = require('path');
const fs = require('fs').promises;
const serialport = require('serialport');

const SerialScanner = require('../app/src/main/serial/scanner');
const SerialConnector = require('../app/src/main/serial/connector');

const modulesDirPath = path.join(__dirname, '..', 'app', 'modules');
const isDebugMode = process.argv.some((arg) => arg === '--verbose');

const printError = (e, msg) => {
    if (isDebugMode) {
        console.error(e);
    }
    console.error(msg);
};

const consoleWrite = (msg) => {
    const ANSIGreen = '\x1b[32m';
    const ANSIReset = '\x1b[0m';
    const ANSIBoldOn = '\x1b[1m';
    const ANSIBoldOff = '\x1b[22m';
    console.log(`${ANSIGreen}? ${ANSIReset}${ANSIBoldOn}${msg}${ANSIBoldOff}`);
};

const stdoutWrite = (msg) => {
    const ANSIGreen = '\x1b[32m';
    const ANSIReset = '\x1b[0m';
    const ANSIBoldOn = '\x1b[1m';
    const ANSIBoldOff = '\x1b[22m';
    process.stdout.write(`${ANSIGreen}? ${ANSIReset}${ANSIBoldOn}${msg}${ANSIBoldOff}\r`);
};

/*
해야할일
1. 인자로서 모듈명을 받는다
2. 모듈명으로 json 파일을 찾는다
3. 찾은 파일을 config 으로 등록한다
4. 포트를 스캔한다
5. 포트스캔 하고 scanner 에서 선택된 친구는 노란색으로 표기한다
6.
 */
const getHardwareConfig = async () => {
    const { question: answer } = await inquirer.prompt([{
        name: 'question',
        message: 'Select Module JSON file name',
        default: 'arduinoExt',
    }]);
    try {
        const fileBuffer = await fs.readFile(path.join(modulesDirPath, `${answer}.json`));
        return JSON.parse(fileBuffer.toString());
    } catch (e) {
        printError(e, 'JSON file not found!');
    }
};

const getHardwareModule = (config) => {
    try {
        if (config) {
            return require(`../app/modules/${config.module}`);
        }
    } catch (e) {
        printError(e, 'module js file not found!\nif exists, probably \'module\' property is not present');
    }
};

const getComPort = async (config) => {
    const scanner = new SerialScanner();
    let selectedPort = undefined;

    while (!selectedPort) {
        const portList = await serialport.list();

        // see serial/scanner.js#L104
        const selectedPorts = [];
        selectedPorts.push(
            ..._.compact(
                portList.map((port) => scanner._selectCOMPortUsingProperties(config.hardware, port)),
            ));

        const message = selectedPorts.length
            ? `Select COM Port\n  Auto Selected Port is ${selectedPorts.join(',')}`
            : 'Select COM Port';

        const { question: answer } = await inquirer.prompt([{
            type: 'list',
            name: 'question',
            message,
            choices: [
                ...portList.map((port) => port.path),
                new inquirer.Separator(),
                'rescan',
            ],
        }]);

        if (answer !== 'rescan') {
            selectedPort = portList.find((port) => port.path === answer);
        }
    }

    return selectedPort;
};

const initializeConnector = async (connector) => {
    let requestInitialDataCount = 0;
    const getMessage = () => `requestInitialData count: ${requestInitialDataCount}`;

    // inject logger function into requestInitialData
    const originalRequestInitialData = connector.hwModule.requestInitialData.bind(connector.hwModule);
    connector.hwModule.requestInitialData = (serialPort) => {
        requestInitialDataCount++;
        stdoutWrite(getMessage());
        return originalRequestInitialData(serialPort);
    };
    await connector.initialize();
    consoleWrite('Connector initialize successed');
};

// main code
(async () => {
    const config = await getHardwareConfig() || (process.exit(0));
    const hwModule = getHardwareModule(config) || (process.exit(0));
    const comPort = await getComPort(config) || (process.exit(0));

    try {
        const connector = new SerialConnector(hwModule, config.hardware);
        const serialPort = await connector.open(comPort.path);
        consoleWrite(`SerialPort connector opened ${comPort.path}`);

        await initializeConnector(connector);

        process.exit(0);
    } catch (e) {
        printError(e, 'serial connector throw error');
    }
})();
<commit_msg>[feature] 하드웨어 connected 까지 연결 테스트 가능한 CLI 테스트 코드 작성<commit_after>const inquirer = require('inquirer');
const _ = require('lodash');
const path = require('path');
const fs = require('fs').promises;
const serialport = require('serialport');

const SerialScanner = require('../app/src/main/serial/scanner');
const SerialConnector = require('../app/src/main/serial/connector');

const dummyRouter = {
    setHandlerData: () => {},
    sendEncodedDataToServer: () => {},
    sendState: (state) => {
        consoleWrite(`router ${state} called`);

        if (state === 'connected') {
            consoleWrite('connection test completed. test will be close after 3 second.');
            setTimeout(() => {
                process.exit(0);
            }, 3000);
        }
    },
};

const modulesDirPath = path.join(__dirname, '..', 'app', 'modules');
const isDebugMode = process.argv.some((arg) => arg === '--verbose');

const printError = (e, msg) => {
    if (isDebugMode) {
        console.error(e);
    }
    console.error(msg);
};

const consoleWrite = (msg) => {
    const ANSIGreen = '\x1b[32m';
    const ANSIReset = '\x1b[0m';
    const ANSIBoldOn = '\x1b[1m';
    const ANSIBoldOff = '\x1b[22m';
    console.log(`${ANSIGreen}? ${ANSIReset}${ANSIBoldOn}${msg}${ANSIBoldOff}`);
};

const stdoutWrite = (msg) => {
    const ANSIGreen = '\x1b[32m';
    const ANSIReset = '\x1b[0m';
    const ANSIBoldOn = '\x1b[1m';
    const ANSIBoldOff = '\x1b[22m';
    process.stdout.write(`${ANSIGreen}? ${ANSIReset}${ANSIBoldOn}${msg}${ANSIBoldOff}\r`);
};

const resetableStdoutWrite = (clear, multiLineMessage) => {
    clear && process.stdout.clearScreenDown();
    multiLineMessage.forEach((msg) => {
        process.stdout.write(msg);
        process.stdout.write('\n');
    });
    process.stdout.moveCursor(0, -1 * multiLineMessage.length);
    process.stdout.cursorTo(0);
    process.stdout.clearScreenDown();
};

/*
해야할일
1. 인자로서 모듈명을 받는다
2. 모듈명으로 json 파일을 찾는다
3. 찾은 파일을 config 으로 등록한다
4. 포트를 스캔한다
5. 포트스캔 하고 scanner 에서 선택된 친구는 노란색으로 표기한다
6.
 */
const getHardwareConfig = async () => {
    const { question: answer } = await inquirer.prompt([{
        name: 'question',
        message: 'Select Module JSON file name',
        default: 'arduinoExt',
    }]);
    try {
        const fileBuffer = await fs.readFile(path.join(modulesDirPath, `${answer}.json`));
        return JSON.parse(fileBuffer.toString());
    } catch (e) {
        printError(e, 'JSON file not found!');
    }
};

const getHardwareModule = (config) => {
    try {
        if (config) {
            return require(`../app/modules/${config.module}`);
        }
    } catch (e) {
        printError(e, 'module js file not found!\nif exists, probably \'module\' property is not present');
    }
};

const getComPort = async (config) => {
    const scanner = new SerialScanner();
    let selectedPort = undefined;

    while (!selectedPort) {
        const portList = await serialport.list();

        // see serial/scanner.js#L104
        const selectedPorts = [];
        selectedPorts.push(
            ..._.compact(
                portList.map((port) => scanner._selectCOMPortUsingProperties(config.hardware, port)),
            ));

        const message = selectedPorts.length
            ? `Select COM Port\n  Auto Selected Port is ${selectedPorts.join(',')}`
            : 'Select COM Port';

        const { question: answer } = await inquirer.prompt([{
            type: 'list',
            name: 'question',
            message,
            choices: [
                ...portList.map((port) => port.path),
                new inquirer.Separator(),
                'rescan',
            ],
        }]);

        if (answer !== 'rescan') {
            selectedPort = portList.find((port) => port.path === answer);
        }
    }

    return selectedPort;
};

const initializeConnector = async (connector) => {
    let requestInitialDataCount = 0;
    const getMessage = () => `requestInitialData count: ${requestInitialDataCount}`;

    // inject logger function into requestInitialData
    const originalRequestInitialData = connector.hwModule.requestInitialData.bind(connector.hwModule);
    connector.hwModule.requestInitialData = (serialPort) => {
        requestInitialDataCount++;
        stdoutWrite(getMessage());
        return originalRequestInitialData(serialPort);
    };
    await connector.initialize();
    consoleWrite('Connector initialize success');
};

// main code
(async () => {
    const config = await getHardwareConfig() || (process.exit(0));
    const hwModule = getHardwareModule(config) || (process.exit(0));
    const comPort = await getComPort(config) || (process.exit(0));

    try {
        const connector = new SerialConnector(hwModule, config.hardware);
        const serialPort = await connector.open(comPort.path);
        connector.setRouter(dummyRouter);
        consoleWrite(`SerialPort connector opened ${comPort.path}`);

        await initializeConnector(connector);

        // mainRouter._connect()
        if (connector.executeFlash) {
            consoleWrite('Entry hardware will be execute Flash (from firmwarecheck property)');
        }
        connector.connect();
    } catch (e) {
        printError(e, 'serial connector throw error');
        process.exit(-1);
    }
})();
<|endoftext|>


<commit_before>/**
* Mixin for adding WAI-ARIA attributes to controls
*
* @module enyo/AccessibilitySupport
*/

var
	dispatcher = require('../dispatcher'),
	kind = require('../kind'),
	utils = require('../utils');

var defaultObservers = [
	{from: 'tabIndex', to: 'tabindex'},
	{from: 'accessibilityDisabled', method: function () {
		this.setAriaAttribute('aria-hidden', this.accessibilityDisabled ? 'true' : null);
	}},
	{from: 'accessibilityLive', method: function () {
		var live = this.accessibilityLive === true && 'assertive' || this.accessibilityLive || null;
		this.setAriaAttribute('aria-live', live);
	}},
	{path: ['accessibilityAlert', 'accessibilityRole'], method: function () {
		var role = this.accessibilityAlert && 'alert' || this.accessibilityRole || null;
		this.setAriaAttribute('role', role);
	}},
	{path: ['content', 'accessibilityHint', 'accessibilityLabel'], method: function () {
		var prefix = this.accessibilityLabel || this.content || null,
			label = this.accessibilityHint && prefix && (prefix + ' ' + this.accessibilityHint) ||
					this.accessibilityHint ||
					this.accessibilityLabel ||
					null;

		this.setAriaAttribute('aria-label', label);
	}}
];

/**
* Prevents browser-initiated scrolling contained controls into view when those controls are
* explicitly focus()'ed.
*
* @private
*/
function preventScroll (node) {
	if (node) {
		dispatcher.listen(node, 'scroll', function () {
			node.scrollTop = 0;
			node.scrollLeft = 0;
		});
	}
}

function updateAriaAttributes (all) {
	var i, l, obs;

	for (i = 0, l = this._ariaObservers.length; i < l; i++) {
		obs = this._ariaObservers[i];
		if ((all || obs.pending) && obs.method) {
			obs.method();
			obs.pending = false;
		}
	}
}

function registerAriaUpdate (obj) {
	var fn;
	if (!obj.pending) {
		obj.pending = true;
		fn = this.bindSafely(updateAriaAttributes);
		if (!this.accessibilityDefer) {
			fn();
		} else {
			this.startJob('updateAriaAttributes', fn, 16);
		}
	}
}

function toAriaAttribute (from, to) {
	var value = this[from];
	this.setAriaAttribute(to, value === undefined ? null : value);
}

function staticToAriaAttribute (to, value) {
	this.setAriaAttribute(to, value);
}

function initAriaObservers (control) {
	var conf = control._ariaObservers,
		i, l, fn;

	control._ariaObservers = [];
	for (i = 0, l = defaultObservers.length; i < l; i++) {
		initAriaObserver(control, defaultObservers[i]);
	}
	if (conf) {
		for (i = 0, l = conf.length; i < l; i++) {
			initAriaObserver(control, conf[i]);
		}
	}

	// setup disabled observer and kickoff first run of observers
	fn = updateAriaAttributes.bind(control, true);
	control.addObserver('accessibilityDisabled', fn);
	fn();
}

function initAriaObserver (control, c) {
	var
		// path can either source from 'path' or 'from' (for binding-style configs)
		path = c.path || c.from,

		// method is either:
		// 		'method', if it exists, or
		// 		staticToAriaAttribute if 'to' and 'value' exist - static binding-style config, or
		// 		toAriaAttribute if a 'to' path exists - binding-style config
		method = c.method && control.bindSafely(c.method) ||
				!path && c.to && c.value !== undefined && control.bindSafely(staticToAriaAttribute, c.to, c.value) ||
				c.to && control.bindSafely(toAriaAttribute, path, c.to) ||
				null,

		// import the relevant and pre-validated parts into the instance-level config
		config = {
			path: path,
			method: method,
			pending: false
		},

		// pre-bind the register method as it's used multiple times when 'path' is an array
		fn = registerAriaUpdate.bind(control, config),

		// iterator
		l;

	control._ariaObservers.push(config);
	if (utils.isArray(path)) {
		for (l = path.length - 1; l >= 0; --l) {
			control.addObserver(path[l], fn);
		}
	}
	else if (path) {
		control.addObserver(path, fn);
	}
}

/**
* @mixin
*/
var AccessibilitySupport = {

	/**
	* @private
	*/
	name: 'enyo.AccessibilitySupport',

	/**
	* AccessibilityLabel is used for accessibility voice readout.
	* If accessibilityLabel is set, screen reader reads the label when control is focused.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityLabel: '',

	/**
	* AccessibilityHint is used for additional information of control.
	* If accessibilityHint is set and content exists, screen reader
	* reads accessibilityHint with content when control is focused.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityHint: '',

	/**
	* The `role` of the control. May be superceded by a truthy `accessibilityAlert` value.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityRole: '',

	/**
	* AccessibilityAlert is for alert message or page description.
	* If accessibilityAlert is true, aria role will be set to "alert" and
	* screen reader will automatically reads content or accessibilityLabel
	* regardless focus.
	* Note that if you use accessibilityAlert, previous role will be
	* replaced with "alert" role.
	*
	* Range: [`true`, `false`]
	* - true: screen reader automatically reads label regardless focus.
	* - false: screen reader reads label with focus.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityAlert: false,

	/**
	* AccessibilityLive is for dynamic content which updates without a page reload.
	* If AccessibilityLive is true, screen reader will read content or accessibilityLabel
	* when it changed.
	*
	* Range: [`true`, `false`]
	* - true: screen reader reads content when it changed.
	* - false: screen reader reads content with focus.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityLive: false,

	/**
	* AccessibilityDisabled prevents VoiceReadout.
	* If accessibilityDisabled is true, screen reader doesn't read any label for the control.
	* Note that this is not working on HTML form elements which can get focus without tabindex.
	*
	* Range: [`true`, `false`]
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityDisabled: false,

	/**
	* When true, `onscroll` events will be observed and scrolling prevented by resetting the
	* `scrollTop` and `scrollLeft` of the node. This prevents inadvertent layout issues introduced
	* by the browser scrolling contained controls into view when `focus()`'ed.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityPreventScroll: false,

	/**
	* @method
	* @private
	*/
	create: kind.inherit(function (sup) {
		return function (props) {
			sup.apply(this, arguments);
			initAriaObservers(this);
		};
	}),

	/**
	* If accessibilityDisabled is `false`, sets the node attribute. Otherwise, removes it.
	*
	* @param {String} name  Attribute name
	* @param {String} value Attribute value
	* @public
	*/
	setAriaAttribute: function (name, value) {
		// if the control is disabled, don't set any aria properties except aria-hidden
		if (this.accessibilityDisabled && name != 'aria-hidden') {
			value = null;
		}
		// if the value is defined and non-null, cast it to a String
		else if (value !== undefined && value !== null) {
			value = String(value);
		}
		this.setAttribute(name, value);
	},

	/**
	* @private
	*/
	rendered: kind.inherit(function (sup) {
		return function () {
			sup.apply(this, arguments);
			if (this.accessibilityPreventScroll) {
				preventScroll(this.hasNode());
			}
		};
	})
};

var sup = kind.concatHandler;
kind.concatHandler = function (ctor, props, instance) {
	sup.call(this, ctor, props, instance);

	var proto = ctor.prototype || ctor,
		ariaObservers = proto._ariaObservers && proto._ariaObservers.slice(),
		incoming = props.ariaObservers;

	if (incoming && incoming instanceof Array) {
		if (ariaObservers) {
			ariaObservers.push.apply(ariaObservers, incoming);
		} else {
			ariaObservers = incoming.slice();
		}
	}

	proto._ariaObservers = ariaObservers;
};

module.exports = AccessibilitySupport;<commit_msg>add default tabindex support for webOS<commit_after>/**
* Mixin for adding WAI-ARIA attributes to controls
*
* @module enyo/AccessibilitySupport
*/

var
	dispatcher = require('../dispatcher'),
	kind = require('../kind'),
	platform = require('../platform'),
	utils = require('../utils');

var defaultObservers = [
	{from: 'accessibilityDisabled', method: function () {
		this.setAriaAttribute('aria-hidden', this.accessibilityDisabled ? 'true' : null);
	}},
	{from: 'accessibilityLive', method: function () {
		var live = this.accessibilityLive === true && 'assertive' || this.accessibilityLive || null;
		this.setAriaAttribute('aria-live', live);
	}},
	{path: ['accessibilityAlert', 'accessibilityRole'], method: function () {
		var role = this.accessibilityAlert && 'alert' || this.accessibilityRole || null;
		this.setAriaAttribute('role', role);
	}},
	{path: ['content', 'accessibilityHint', 'accessibilityLabel', 'tabIndex'], method: function () {
		var focusable = this.accessibilityLabel || this.content || this.accessibilityHint || false,
			prefix = this.accessibilityLabel || this.content || null,
			label = this.accessibilityHint && prefix && (prefix + ' ' + this.accessibilityHint) ||
					this.accessibilityHint ||
					this.accessibilityLabel ||
					null;

		this.setAriaAttribute('aria-label', label);

		// A truthy or zero tabindex will be set directly
		if (this.tabIndex || this.tabIndex === 0) {
			this.setAriaAttribute('tabindex', this.tabIndex);
		}
		// The webOS browser will only read nodes with a non-null tabindex so if the node has
		// readable content, make it programmably focusable.
		else if (focusable && this.tabIndex === undefined && platform.webos) {
			this.setAriaAttribute('tabindex', -1);
		}
		// Otherwise, remove it
		else {
			this.setAriaAttribute('tabindex', null);
		}
	}}
];

/**
* Prevents browser-initiated scrolling contained controls into view when those controls are
* explicitly focus()'ed.
*
* @private
*/
function preventScroll (node) {
	if (node) {
		dispatcher.listen(node, 'scroll', function () {
			node.scrollTop = 0;
			node.scrollLeft = 0;
		});
	}
}

function updateAriaAttributes (all) {
	var i, l, obs;

	for (i = 0, l = this._ariaObservers.length; i < l; i++) {
		obs = this._ariaObservers[i];
		if ((all || obs.pending) && obs.method) {
			obs.method();
			obs.pending = false;
		}
	}
}

function registerAriaUpdate (obj) {
	var fn;
	if (!obj.pending) {
		obj.pending = true;
		fn = this.bindSafely(updateAriaAttributes);
		if (!this.accessibilityDefer) {
			fn();
		} else {
			this.startJob('updateAriaAttributes', fn, 16);
		}
	}
}

function toAriaAttribute (from, to) {
	var value = this[from];
	this.setAriaAttribute(to, value === undefined ? null : value);
}

function staticToAriaAttribute (to, value) {
	this.setAriaAttribute(to, value);
}

function initAriaObservers (control) {
	var conf = control._ariaObservers,
		i, l, fn;

	control._ariaObservers = [];
	for (i = 0, l = defaultObservers.length; i < l; i++) {
		initAriaObserver(control, defaultObservers[i]);
	}
	if (conf) {
		for (i = 0, l = conf.length; i < l; i++) {
			initAriaObserver(control, conf[i]);
		}
	}

	// setup disabled observer and kickoff first run of observers
	fn = updateAriaAttributes.bind(control, true);
	control.addObserver('accessibilityDisabled', fn);
	fn();
}

function initAriaObserver (control, c) {
	var
		// path can either source from 'path' or 'from' (for binding-style configs)
		path = c.path || c.from,

		// method is either:
		// 		'method', if it exists, or
		// 		staticToAriaAttribute if 'to' and 'value' exist - static binding-style config, or
		// 		toAriaAttribute if a 'to' path exists - binding-style config
		method = c.method && control.bindSafely(c.method) ||
				!path && c.to && c.value !== undefined && control.bindSafely(staticToAriaAttribute, c.to, c.value) ||
				c.to && control.bindSafely(toAriaAttribute, path, c.to) ||
				null,

		// import the relevant and pre-validated parts into the instance-level config
		config = {
			path: path,
			method: method,
			pending: false
		},

		// pre-bind the register method as it's used multiple times when 'path' is an array
		fn = registerAriaUpdate.bind(control, config),

		// iterator
		l;

	control._ariaObservers.push(config);
	if (utils.isArray(path)) {
		for (l = path.length - 1; l >= 0; --l) {
			control.addObserver(path[l], fn);
		}
	}
	else if (path) {
		control.addObserver(path, fn);
	}
}

/**
* @mixin
*/
var AccessibilitySupport = {

	/**
	* @private
	*/
	name: 'enyo.AccessibilitySupport',

	/**
	* AccessibilityLabel is used for accessibility voice readout.
	* If accessibilityLabel is set, screen reader reads the label when control is focused.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityLabel: '',

	/**
	* AccessibilityHint is used for additional information of control.
	* If accessibilityHint is set and content exists, screen reader
	* reads accessibilityHint with content when control is focused.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityHint: '',

	/**
	* The `role` of the control. May be superceded by a truthy `accessibilityAlert` value.
	*
	* @type {String}
	* @default ''
	* @public
	*/
	accessibilityRole: '',

	/**
	* AccessibilityAlert is for alert message or page description.
	* If accessibilityAlert is true, aria role will be set to "alert" and
	* screen reader will automatically reads content or accessibilityLabel
	* regardless focus.
	* Note that if you use accessibilityAlert, previous role will be
	* replaced with "alert" role.
	*
	* Range: [`true`, `false`]
	* - true: screen reader automatically reads label regardless focus.
	* - false: screen reader reads label with focus.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityAlert: false,

	/**
	* AccessibilityLive is for dynamic content which updates without a page reload.
	* If AccessibilityLive is true, screen reader will read content or accessibilityLabel
	* when it changed.
	*
	* Range: [`true`, `false`]
	* - true: screen reader reads content when it changed.
	* - false: screen reader reads content with focus.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityLive: false,

	/**
	* AccessibilityDisabled prevents VoiceReadout.
	* If accessibilityDisabled is true, screen reader doesn't read any label for the control.
	* Note that this is not working on HTML form elements which can get focus without tabindex.
	*
	* Range: [`true`, `false`]
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityDisabled: false,

	/**
	* When true, `onscroll` events will be observed and scrolling prevented by resetting the
	* `scrollTop` and `scrollLeft` of the node. This prevents inadvertent layout issues introduced
	* by the browser scrolling contained controls into view when `focus()`'ed.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	accessibilityPreventScroll: false,

	/**
	* Sets the `tabindex` of the control. When `undefined` on webOS, it will be set to -1 to enable
	* screen reading. A value of `null` (or `undefined` on non-webOS) ensures that no `tabindex` is
	* set.
	*
	* @type {Number}
	* @default undefined
	* @public
	*/

	/**
	* @method
	* @private
	*/
	create: kind.inherit(function (sup) {
		return function (props) {
			sup.apply(this, arguments);
			initAriaObservers(this);
		};
	}),

	/**
	* If accessibilityDisabled is `false`, sets the node attribute. Otherwise, removes it.
	*
	* @param {String} name  Attribute name
	* @param {String} value Attribute value
	* @public
	*/
	setAriaAttribute: function (name, value) {
		// if the control is disabled, don't set any aria properties except aria-hidden
		if (this.accessibilityDisabled && name != 'aria-hidden') {
			value = null;
		}
		// if the value is defined and non-null, cast it to a String
		else if (value !== undefined && value !== null) {
			value = String(value);
		}
		this.setAttribute(name, value);
	},

	/**
	* @private
	*/
	rendered: kind.inherit(function (sup) {
		return function () {
			sup.apply(this, arguments);
			if (this.accessibilityPreventScroll) {
				preventScroll(this.hasNode());
			}
		};
	})
};

var sup = kind.concatHandler;
kind.concatHandler = function (ctor, props, instance) {
	sup.call(this, ctor, props, instance);

	var proto = ctor.prototype || ctor,
		ariaObservers = proto._ariaObservers && proto._ariaObservers.slice(),
		incoming = props.ariaObservers;

	if (incoming && incoming instanceof Array) {
		if (ariaObservers) {
			ariaObservers.push.apply(ariaObservers, incoming);
		} else {
			ariaObservers = incoming.slice();
		}
	}

	proto._ariaObservers = ariaObservers;
};

module.exports = AccessibilitySupport;<|endoftext|>


<commit_before>var Lab = require('lab');
var Hapi = require('hapi');
var config = require('getconfig');
var inspect = require('eyes').inspector({hideFunctions: true, maxLength: null});

var startServerInstance = require('../server-instance');

// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;

// shared test context
var ctx = {
	server: null,
	table: null,

	setName: null,
	baseSetUrl: null,

	app: null,

	getSet: function(done) {
		if (!this.server || !this.baseSetUrl) return done({bad:'fail'}, null);
		this.server.inject({method: 'get', url: this.baseSetUrl}, done);
	},
	inspect: inspect
};

before(function(done) {
	startServerInstance(function(server, app) {
		ctx.server = server;
		ctx.app = app;
		console.log('test is running at', ctx.server.info.uri);
		done();
	});
});

require('./server')(ctx, lab);
require('./mongo-mongoose')(ctx, lab);
// require('./api-set')(ctx, lab);
// require('./api-pool-entry')(ctx, lab);
// require('./api-pattern')(ctx, lab);
// require('./api-set-pattern')(ctx, lab);
// require('./api-song')(ctx, lab);
// require('./delete-set')(ctx, lab, 'reserved-test-set');
// require('./api-tree-ops')(ctx, lab);
// require('./delete-set')(ctx, lab, 'reserved-test-tree-stuff');
// require('./api-set-tree-ops')(ctx, lab);
// require('./api-set-step-updates')(ctx, lab);
// require('./api-order')(ctx, lab);
// require('./delete-set')(ctx, lab, 'reserved-test-order-stuff');
// require('./delete-set')(ctx, lab, 'bogus', 404);
require('./api-sample')(ctx, lab);
<commit_msg>Turn tests back on.<commit_after>var Lab = require('lab');
var Hapi = require('hapi');
var config = require('getconfig');
var inspect = require('eyes').inspector({hideFunctions: true, maxLength: null});

var startServerInstance = require('../server-instance');

// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;

// shared test context
var ctx = {
	server: null,
	table: null,

	setName: null,
	baseSetUrl: null,

	app: null,

	getSet: function(done) {
		if (!this.server || !this.baseSetUrl) return done({bad:'fail'}, null);
		this.server.inject({method: 'get', url: this.baseSetUrl}, done);
	},
	inspect: inspect
};

before(function(done) {
	startServerInstance(function(server, app) {
		ctx.server = server;
		ctx.app = app;
		console.log('test is running at', ctx.server.info.uri);
		done();
	});
});

require('./server')(ctx, lab);
require('./mongo-mongoose')(ctx, lab);
require('./api-set')(ctx, lab);
require('./api-pool-entry')(ctx, lab);
require('./api-pattern')(ctx, lab);
require('./api-set-pattern')(ctx, lab);
require('./api-song')(ctx, lab);
require('./delete-set')(ctx, lab, 'reserved-test-set');
require('./api-tree-ops')(ctx, lab);
require('./delete-set')(ctx, lab, 'reserved-test-tree-stuff');
require('./api-set-tree-ops')(ctx, lab);
require('./api-set-step-updates')(ctx, lab);
require('./api-order')(ctx, lab);
require('./delete-set')(ctx, lab, 'reserved-test-order-stuff');
require('./delete-set')(ctx, lab, 'bogus', 404);
require('./api-sample')(ctx, lab);
<|endoftext|>


<commit_before>/*jslint node:true indent:2 */
/*globals describe, it */
'use strict';

var jSend = function () { return; };

var assert = require('assert');

describe('jSend', function () {
  it('should exist', function () {
    assert(jSend);
  });
  it('should be a function', function () {
    assert(typeof jSend === 'function');
  });
  it('should call third parameter "next" function as callback', function () {
    var called = false,
      req = null,
      res = null,
      next = function () { called = true; };
    jSend(req, res, next);
    assert(called);
  });
});
<commit_msg>[GREEN] add "next" callback call to jSend<commit_after>/*jslint node:true indent:2 */
/*globals describe, it */
'use strict';

var jSend = function (req, res, next) { return next(); };

var assert = require('assert');

describe('jSend', function () {
  it('should exist', function () {
    assert(jSend);
  });
  it('should be a function', function () {
    assert(typeof jSend === 'function');
  });
  it('should call third parameter "next" function as callback', function () {
    var called = false,
      req = null,
      res = null,
      next = function () { called = true; };
    jSend(req, res, next);
    assert(called);
  });
});
<|endoftext|>


<commit_before>var should = require('chai').should(),
    escapeUtil = require('../index'),
    escape = escapeUtil.escape,
    unescape = escapeUtil.unescape;

describe('#escape', function() {
  it('converts & into &', function(){
    escape('&').should.equal('ff&');
  });

  it('converts " into "', function(){
    escape('"').should.equal('"');
  });

  it('converts \' into '', function(){
    escape('\'').should.equal(''');
  });

  it('converts < into <', function(){
    escape('<').should.equal('<');
  });

  it('converts > into >', function(){
    escape('>').should.equal('>');
  });
});

describe('#unescape', function(){
  it('converts & into &', function(){
    unescape('&').should.equal('&');
  });

  it('converts " into "', function(){
    unescape('"').should.equal('"');
  });

  it('converts ' into \'', function(){
    unescape(''').should.equal('\'');
  });

  it('converts < into <', function(){
    unescape('<').should.equal('<');
  });

  it('converts > into >', function(){
    unescape('>').should.equal('>');
  });
});
<commit_msg>fix test failed<commit_after>var should = require('chai').should(),
    escapeUtil = require('../index'),
    escape = escapeUtil.escape,
    unescape = escapeUtil.unescape;

describe('#escape', function() {
  it('converts & into &', function(){
    escape('&').should.equal('&');
  });

  it('converts " into "', function(){
    escape('"').should.equal('"');
  });

  it('converts \' into '', function(){
    escape('\'').should.equal(''');
  });

  it('converts < into <', function(){
    escape('<').should.equal('<');
  });

  it('converts > into >', function(){
    escape('>').should.equal('>');
  });
});

describe('#unescape', function(){
  it('converts & into &', function(){
    unescape('&').should.equal('&');
  });

  it('converts " into "', function(){
    unescape('"').should.equal('"');
  });

  it('converts ' into \'', function(){
    unescape(''').should.equal('\'');
  });

  it('converts < into <', function(){
    unescape('<').should.equal('<');
  });

  it('converts > into >', function(){
    unescape('>').should.equal('>');
  });
});
<|endoftext|>


<commit_before>// Dependencies
var test = require("prova"),
    EnBible = require("../index");

var validVerse = {
    reference: "Matthew 1:1",
    verses: [{
        book_id: "MAT",
        book_name: "Matthew",
        chapter: 1,
        verse: 1,
        text: "Livro da genealogia de Jesus Cristo, filho de Davi, filho de Abraão.   "
    }],
    text: "Livro da genealogia de Jesus Cristo, filho de Davi, filho de Abraão.   ",
    translation_id: "almeida",
    translation_name: "João Ferreira de Almeida",
    translation_note: "Public Domain"
}

test("Return proper verse", function(t) {
    t.plan(2);

    // Get verse
    EnBible.getVerse("Mateus 1:1", function(err, data) {
        t.error(err);
        t.same(data, validVerse);
    });
});<commit_msg>update variable name<commit_after>// Dependencies
var test = require("prova"),
    PtBible = require("../index");

var validVerse = {
    reference: "Mateus 1:1",
    verses: [{
        book_id: "MAT",
        book_name: "Mateus",
        chapter: 1,
        verse: 1,
        text: "Livro da genealogia de Jesus Cristo, filho de Davi, filho de Abraão.   "
    }],
    text: "Livro da genealogia de Jesus Cristo, filho de Davi, filho de Abraão.   ",
    translation_id: "almeida",
    translation_name: "João Ferreira de Almeida",
    translation_note: "Public Domain"
}

test("Return proper verse", function(t) {
    t.plan(2);

    // Get verse
    PtBible.getVerse("Mateus 1:1", function(err, data) {
        t.error(err);
        t.same(data, validVerse);
    });
});<|endoftext|>